babylon.viewer.max.js 5.2 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411934129341393414934159341693417934189341993420934219342293423934249342593426934279342893429934309343193432934339343493435934369343793438934399344093441934429344393444934459344693447934489344993450934519345293453934549345593456934579345893459934609346193462934639346493465934669346793468934699347093471934729347393474934759347693477934789347993480934819348293483934849348593486934879348893489934909349193492934939349493495934969349793498934999350093501935029350393504935059350693507935089350993510935119351293513935149351593516935179351893519935209352193522935239352493525935269352793528935299353093531935329353393534935359353693537935389353993540935419354293543935449354593546935479354893549935509355193552935539355493555935569355793558935599356093561935629356393564935659356693567935689356993570935719357293573935749357593576935779357893579935809358193582935839358493585935869358793588935899359093591935929359393594935959359693597935989359993600936019360293603936049360593606936079360893609936109361193612936139361493615936169361793618936199362093621936229362393624936259362693627936289362993630936319363293633936349363593636936379363893639936409364193642936439364493645936469364793648936499365093651936529365393654936559365693657936589365993660936619366293663936649366593666936679366893669936709367193672936739367493675936769367793678936799368093681936829368393684936859368693687936889368993690936919369293693936949369593696936979369893699937009370193702937039370493705937069370793708937099371093711937129371393714937159371693717937189371993720937219372293723937249372593726937279372893729937309373193732937339373493735937369373793738937399374093741937429374393744937459374693747937489374993750937519375293753937549375593756937579375893759937609376193762937639376493765937669376793768937699377093771937729377393774937759377693777937789377993780937819378293783937849378593786937879378893789937909379193792937939379493795937969379793798937999380093801938029380393804938059380693807938089380993810938119381293813938149381593816938179381893819938209382193822938239382493825938269382793828938299383093831938329383393834938359383693837938389383993840938419384293843938449384593846938479384893849938509385193852938539385493855938569385793858938599386093861938629386393864938659386693867938689386993870938719387293873938749387593876938779387893879938809388193882938839388493885938869388793888938899389093891938929389393894938959389693897938989389993900939019390293903939049390593906939079390893909939109391193912939139391493915939169391793918939199392093921939229392393924939259392693927939289392993930939319393293933939349393593936939379393893939939409394193942939439394493945939469394793948939499395093951939529395393954939559395693957939589395993960939619396293963939649396593966939679396893969939709397193972939739397493975939769397793978939799398093981939829398393984939859398693987939889398993990939919399293993939949399593996939979399893999940009400194002940039400494005940069400794008940099401094011940129401394014940159401694017940189401994020940219402294023940249402594026940279402894029940309403194032940339403494035940369403794038940399404094041940429404394044940459404694047940489404994050940519405294053940549405594056940579405894059940609406194062940639406494065940669406794068940699407094071940729407394074940759407694077940789407994080940819408294083940849408594086940879408894089940909409194092940939409494095940969409794098940999410094101941029410394104941059410694107941089410994110941119411294113941149411594116941179411894119941209412194122941239412494125941269412794128941299413094131941329413394134941359413694137941389413994140941419414294143941449414594146941479414894149941509415194152941539415494155941569415794158941599416094161941629416394164941659416694167941689416994170941719417294173941749417594176941779417894179941809418194182941839418494185941869418794188941899419094191941929419394194941959419694197941989419994200942019420294203942049420594206942079420894209942109421194212942139421494215942169421794218942199422094221942229422394224942259422694227942289422994230942319423294233942349423594236942379423894239942409424194242942439424494245942469424794248942499425094251942529425394254942559425694257942589425994260942619426294263942649426594266942679426894269942709427194272942739427494275942769427794278942799428094281942829428394284942859428694287942889428994290942919429294293942949429594296942979429894299943009430194302943039430494305943069430794308943099431094311943129431394314943159431694317943189431994320943219432294323943249432594326943279432894329943309433194332943339433494335943369433794338943399434094341943429434394344943459434694347943489434994350943519435294353943549435594356943579435894359943609436194362943639436494365943669436794368943699437094371943729437394374943759437694377943789437994380943819438294383943849438594386943879438894389943909439194392943939439494395943969439794398943999440094401944029440394404944059440694407944089440994410944119441294413944149441594416944179441894419944209442194422944239442494425944269442794428944299443094431944329443394434944359443694437944389443994440944419444294443944449444594446944479444894449944509445194452944539445494455944569445794458944599446094461944629446394464944659446694467944689446994470944719447294473944749447594476944779447894479944809448194482944839448494485944869448794488944899449094491944929449394494944959449694497944989449994500945019450294503945049450594506945079450894509945109451194512945139451494515945169451794518945199452094521945229452394524945259452694527945289452994530945319453294533945349453594536945379453894539945409454194542945439454494545945469454794548945499455094551945529455394554945559455694557945589455994560945619456294563945649456594566945679456894569945709457194572945739457494575945769457794578945799458094581945829458394584945859458694587945889458994590945919459294593945949459594596945979459894599946009460194602946039460494605946069460794608946099461094611946129461394614946159461694617946189461994620946219462294623946249462594626946279462894629946309463194632946339463494635946369463794638946399464094641946429464394644946459464694647946489464994650946519465294653946549465594656946579465894659946609466194662946639466494665946669466794668946699467094671946729467394674946759467694677946789467994680946819468294683946849468594686946879468894689946909469194692946939469494695946969469794698946999470094701947029470394704947059470694707947089470994710947119471294713947149471594716947179471894719947209472194722947239472494725947269472794728947299473094731947329473394734947359473694737947389473994740947419474294743947449474594746947479474894749947509475194752947539475494755947569475794758947599476094761947629476394764947659476694767947689476994770947719477294773947749477594776947779477894779947809478194782947839478494785947869478794788947899479094791947929479394794947959479694797947989479994800948019480294803948049480594806948079480894809948109481194812948139481494815948169481794818948199482094821948229482394824948259482694827948289482994830948319483294833948349483594836948379483894839948409484194842948439484494845948469484794848948499485094851948529485394854948559485694857948589485994860948619486294863948649486594866948679486894869948709487194872948739487494875948769487794878948799488094881948829488394884948859488694887948889488994890948919489294893948949489594896948979489894899949009490194902949039490494905949069490794908949099491094911949129491394914949159491694917949189491994920949219492294923949249492594926949279492894929949309493194932949339493494935949369493794938949399494094941949429494394944949459494694947949489494994950949519495294953949549495594956949579495894959949609496194962949639496494965949669496794968949699497094971949729497394974949759497694977949789497994980949819498294983949849498594986949879498894989949909499194992949939499494995949969499794998949999500095001950029500395004950059500695007950089500995010950119501295013950149501595016950179501895019950209502195022950239502495025950269502795028950299503095031950329503395034950359503695037950389503995040950419504295043950449504595046950479504895049950509505195052950539505495055950569505795058950599506095061950629506395064950659506695067950689506995070950719507295073950749507595076950779507895079950809508195082950839508495085950869508795088950899509095091950929509395094950959509695097950989509995100951019510295103951049510595106951079510895109951109511195112951139511495115951169511795118951199512095121951229512395124951259512695127951289512995130951319513295133951349513595136951379513895139951409514195142951439514495145951469514795148951499515095151951529515395154951559515695157951589515995160951619516295163951649516595166951679516895169951709517195172951739517495175951769517795178951799518095181951829518395184951859518695187951889518995190951919519295193951949519595196951979519895199952009520195202952039520495205952069520795208952099521095211952129521395214952159521695217952189521995220952219522295223952249522595226952279522895229952309523195232952339523495235952369523795238952399524095241952429524395244952459524695247952489524995250952519525295253952549525595256952579525895259952609526195262952639526495265952669526795268952699527095271952729527395274952759527695277952789527995280952819528295283952849528595286952879528895289952909529195292952939529495295952969529795298952999530095301953029530395304953059530695307953089530995310953119531295313953149531595316953179531895319953209532195322953239532495325953269532795328953299533095331953329533395334953359533695337953389533995340953419534295343953449534595346953479534895349953509535195352953539535495355953569535795358953599536095361953629536395364953659536695367953689536995370953719537295373953749537595376953779537895379953809538195382953839538495385953869538795388953899539095391953929539395394953959539695397953989539995400954019540295403954049540595406954079540895409954109541195412954139541495415954169541795418954199542095421954229542395424954259542695427954289542995430954319543295433954349543595436954379543895439954409544195442954439544495445954469544795448954499545095451954529545395454954559545695457954589545995460954619546295463954649546595466954679546895469954709547195472954739547495475954769547795478954799548095481954829548395484954859548695487954889548995490954919549295493954949549595496954979549895499955009550195502955039550495505955069550795508955099551095511955129551395514955159551695517955189551995520955219552295523955249552595526955279552895529955309553195532955339553495535955369553795538955399554095541955429554395544955459554695547955489554995550955519555295553955549555595556955579555895559955609556195562955639556495565955669556795568955699557095571955729557395574955759557695577955789557995580955819558295583955849558595586955879558895589955909559195592955939559495595955969559795598955999560095601956029560395604956059560695607956089560995610956119561295613956149561595616956179561895619956209562195622956239562495625956269562795628956299563095631956329563395634956359563695637956389563995640956419564295643956449564595646956479564895649956509565195652956539565495655956569565795658956599566095661956629566395664956659566695667956689566995670956719567295673956749567595676956779567895679956809568195682956839568495685956869568795688956899569095691956929569395694956959569695697956989569995700957019570295703957049570595706957079570895709957109571195712957139571495715957169571795718957199572095721957229572395724957259572695727957289572995730957319573295733957349573595736957379573895739957409574195742957439574495745957469574795748957499575095751957529575395754957559575695757957589575995760957619576295763957649576595766957679576895769957709577195772957739577495775957769577795778957799578095781957829578395784957859578695787957889578995790957919579295793957949579595796957979579895799958009580195802958039580495805958069580795808958099581095811958129581395814958159581695817958189581995820958219582295823958249582595826958279582895829958309583195832958339583495835958369583795838958399584095841958429584395844958459584695847958489584995850958519585295853958549585595856958579585895859958609586195862958639586495865958669586795868958699587095871958729587395874958759587695877958789587995880958819588295883958849588595886958879588895889958909589195892958939589495895958969589795898958999590095901959029590395904959059590695907959089590995910959119591295913959149591595916959179591895919959209592195922959239592495925959269592795928959299593095931959329593395934959359593695937959389593995940959419594295943959449594595946959479594895949959509595195952959539595495955959569595795958959599596095961959629596395964959659596695967959689596995970959719597295973959749597595976959779597895979959809598195982959839598495985959869598795988959899599095991959929599395994959959599695997959989599996000960019600296003960049600596006960079600896009960109601196012960139601496015960169601796018960199602096021960229602396024960259602696027960289602996030960319603296033960349603596036960379603896039960409604196042960439604496045960469604796048960499605096051960529605396054960559605696057960589605996060960619606296063960649606596066960679606896069960709607196072960739607496075960769607796078960799608096081960829608396084960859608696087960889608996090960919609296093960949609596096960979609896099961009610196102961039610496105961069610796108961099611096111961129611396114961159611696117961189611996120961219612296123961249612596126961279612896129961309613196132961339613496135961369613796138961399614096141961429614396144961459614696147961489614996150961519615296153961549615596156961579615896159961609616196162961639616496165961669616796168961699617096171961729617396174961759617696177961789617996180961819618296183961849618596186961879618896189961909619196192961939619496195961969619796198961999620096201962029620396204962059620696207962089620996210962119621296213962149621596216962179621896219962209622196222962239622496225962269622796228962299623096231962329623396234962359623696237962389623996240962419624296243962449624596246962479624896249962509625196252962539625496255962569625796258962599626096261962629626396264962659626696267962689626996270962719627296273962749627596276962779627896279962809628196282962839628496285962869628796288962899629096291962929629396294962959629696297962989629996300963019630296303963049630596306963079630896309963109631196312963139631496315963169631796318963199632096321963229632396324963259632696327963289632996330963319633296333963349633596336963379633896339963409634196342963439634496345963469634796348963499635096351963529635396354963559635696357963589635996360963619636296363963649636596366963679636896369963709637196372963739637496375963769637796378963799638096381963829638396384963859638696387963889638996390963919639296393963949639596396963979639896399964009640196402964039640496405964069640796408964099641096411964129641396414964159641696417964189641996420964219642296423964249642596426964279642896429964309643196432964339643496435964369643796438964399644096441964429644396444964459644696447964489644996450964519645296453964549645596456964579645896459964609646196462964639646496465964669646796468964699647096471964729647396474964759647696477964789647996480964819648296483964849648596486964879648896489964909649196492964939649496495964969649796498964999650096501965029650396504965059650696507965089650996510965119651296513965149651596516965179651896519965209652196522965239652496525965269652796528965299653096531965329653396534965359653696537965389653996540965419654296543965449654596546965479654896549965509655196552965539655496555965569655796558965599656096561965629656396564965659656696567965689656996570965719657296573965749657596576965779657896579965809658196582965839658496585965869658796588965899659096591965929659396594965959659696597965989659996600966019660296603966049660596606966079660896609966109661196612966139661496615966169661796618966199662096621966229662396624966259662696627966289662996630966319663296633966349663596636966379663896639966409664196642966439664496645966469664796648966499665096651966529665396654966559665696657966589665996660966619666296663966649666596666966679666896669966709667196672966739667496675966769667796678966799668096681966829668396684966859668696687966889668996690966919669296693966949669596696966979669896699967009670196702967039670496705967069670796708967099671096711967129671396714967159671696717967189671996720967219672296723967249672596726967279672896729967309673196732967339673496735967369673796738967399674096741967429674396744967459674696747967489674996750967519675296753967549675596756967579675896759967609676196762967639676496765967669676796768967699677096771967729677396774967759677696777967789677996780967819678296783967849678596786967879678896789967909679196792967939679496795967969679796798967999680096801968029680396804968059680696807968089680996810968119681296813968149681596816968179681896819968209682196822968239682496825968269682796828968299683096831968329683396834968359683696837968389683996840968419684296843968449684596846968479684896849968509685196852968539685496855968569685796858968599686096861968629686396864968659686696867968689686996870968719687296873968749687596876968779687896879968809688196882968839688496885968869688796888968899689096891968929689396894968959689696897968989689996900969019690296903969049690596906969079690896909969109691196912969139691496915969169691796918969199692096921969229692396924969259692696927969289692996930969319693296933969349693596936969379693896939969409694196942969439694496945969469694796948969499695096951969529695396954969559695696957969589695996960969619696296963969649696596966969679696896969969709697196972969739697496975969769697796978969799698096981969829698396984969859698696987969889698996990969919699296993969949699596996969979699896999970009700197002970039700497005970069700797008970099701097011970129701397014970159701697017970189701997020970219702297023970249702597026970279702897029970309703197032970339703497035970369703797038970399704097041970429704397044970459704697047970489704997050970519705297053970549705597056970579705897059970609706197062970639706497065970669706797068970699707097071970729707397074970759707697077970789707997080970819708297083970849708597086970879708897089970909709197092970939709497095970969709797098970999710097101971029710397104971059710697107971089710997110971119711297113971149711597116971179711897119971209712197122971239712497125971269712797128971299713097131971329713397134971359713697137971389713997140971419714297143971449714597146971479714897149971509715197152971539715497155971569715797158971599716097161971629716397164971659716697167971689716997170971719717297173971749717597176971779717897179971809718197182971839718497185971869718797188971899719097191971929719397194971959719697197971989719997200972019720297203972049720597206972079720897209972109721197212972139721497215972169721797218972199722097221972229722397224972259722697227972289722997230972319723297233972349723597236972379723897239972409724197242972439724497245972469724797248972499725097251972529725397254972559725697257972589725997260972619726297263972649726597266972679726897269972709727197272972739727497275972769727797278972799728097281972829728397284972859728697287972889728997290972919729297293972949729597296972979729897299973009730197302973039730497305973069730797308973099731097311973129731397314973159731697317973189731997320973219732297323973249732597326973279732897329973309733197332973339733497335973369733797338973399734097341973429734397344973459734697347973489734997350973519735297353973549735597356973579735897359973609736197362973639736497365973669736797368973699737097371973729737397374973759737697377973789737997380973819738297383973849738597386973879738897389973909739197392973939739497395973969739797398973999740097401974029740397404974059740697407974089740997410974119741297413974149741597416974179741897419974209742197422974239742497425974269742797428974299743097431974329743397434974359743697437974389743997440974419744297443974449744597446974479744897449974509745197452974539745497455974569745797458974599746097461974629746397464974659746697467974689746997470974719747297473974749747597476974779747897479974809748197482974839748497485974869748797488974899749097491974929749397494974959749697497974989749997500975019750297503975049750597506975079750897509975109751197512975139751497515975169751797518975199752097521975229752397524975259752697527975289752997530975319753297533975349753597536975379753897539975409754197542975439754497545975469754797548975499755097551975529755397554975559755697557975589755997560975619756297563975649756597566975679756897569975709757197572975739757497575975769757797578975799758097581975829758397584975859758697587975889758997590975919759297593975949759597596975979759897599976009760197602976039760497605976069760797608976099761097611976129761397614976159761697617976189761997620976219762297623976249762597626976279762897629976309763197632976339763497635976369763797638976399764097641976429764397644976459764697647976489764997650976519765297653976549765597656976579765897659976609766197662976639766497665976669766797668976699767097671976729767397674976759767697677976789767997680976819768297683976849768597686976879768897689976909769197692976939769497695976969769797698976999770097701977029770397704977059770697707977089770997710977119771297713977149771597716977179771897719977209772197722977239772497725977269772797728977299773097731977329773397734977359773697737977389773997740977419774297743977449774597746977479774897749977509775197752977539775497755977569775797758977599776097761977629776397764977659776697767977689776997770977719777297773977749777597776977779777897779977809778197782977839778497785977869778797788977899779097791977929779397794977959779697797977989779997800978019780297803978049780597806978079780897809978109781197812978139781497815978169781797818978199782097821978229782397824978259782697827978289782997830978319783297833978349783597836978379783897839978409784197842978439784497845978469784797848978499785097851978529785397854978559785697857978589785997860978619786297863978649786597866978679786897869978709787197872978739787497875978769787797878978799788097881978829788397884978859788697887978889788997890978919789297893978949789597896978979789897899979009790197902979039790497905979069790797908979099791097911979129791397914979159791697917979189791997920979219792297923979249792597926979279792897929979309793197932979339793497935979369793797938979399794097941979429794397944979459794697947979489794997950979519795297953979549795597956979579795897959979609796197962979639796497965979669796797968979699797097971979729797397974979759797697977979789797997980979819798297983979849798597986979879798897989979909799197992979939799497995979969799797998979999800098001980029800398004980059800698007980089800998010980119801298013980149801598016980179801898019980209802198022980239802498025980269802798028980299803098031980329803398034980359803698037980389803998040980419804298043980449804598046980479804898049980509805198052980539805498055980569805798058980599806098061980629806398064980659806698067980689806998070980719807298073980749807598076980779807898079980809808198082980839808498085980869808798088980899809098091980929809398094980959809698097980989809998100981019810298103981049810598106981079810898109981109811198112981139811498115981169811798118981199812098121981229812398124981259812698127981289812998130981319813298133981349813598136981379813898139981409814198142981439814498145981469814798148981499815098151981529815398154981559815698157981589815998160981619816298163981649816598166981679816898169981709817198172981739817498175981769817798178981799818098181981829818398184981859818698187981889818998190981919819298193981949819598196981979819898199982009820198202982039820498205982069820798208982099821098211982129821398214982159821698217982189821998220982219822298223982249822598226982279822898229982309823198232982339823498235982369823798238982399824098241982429824398244982459824698247982489824998250982519825298253982549825598256982579825898259982609826198262982639826498265982669826798268982699827098271982729827398274982759827698277982789827998280982819828298283982849828598286982879828898289982909829198292982939829498295982969829798298982999830098301983029830398304983059830698307983089830998310983119831298313983149831598316983179831898319983209832198322983239832498325983269832798328983299833098331983329833398334983359833698337983389833998340983419834298343983449834598346983479834898349983509835198352983539835498355983569835798358983599836098361983629836398364983659836698367983689836998370983719837298373983749837598376983779837898379983809838198382983839838498385983869838798388983899839098391983929839398394983959839698397983989839998400984019840298403984049840598406984079840898409984109841198412984139841498415984169841798418984199842098421984229842398424984259842698427984289842998430984319843298433984349843598436984379843898439984409844198442984439844498445984469844798448984499845098451984529845398454984559845698457984589845998460984619846298463984649846598466984679846898469984709847198472984739847498475984769847798478984799848098481984829848398484984859848698487984889848998490984919849298493984949849598496984979849898499985009850198502985039850498505985069850798508985099851098511985129851398514985159851698517985189851998520985219852298523985249852598526985279852898529985309853198532985339853498535985369853798538985399854098541985429854398544985459854698547985489854998550985519855298553985549855598556985579855898559985609856198562985639856498565985669856798568985699857098571985729857398574985759857698577985789857998580985819858298583985849858598586985879858898589985909859198592985939859498595985969859798598985999860098601986029860398604986059860698607986089860998610986119861298613986149861598616986179861898619986209862198622986239862498625986269862798628986299863098631986329863398634986359863698637986389863998640986419864298643986449864598646986479864898649986509865198652986539865498655986569865798658986599866098661986629866398664986659866698667986689866998670986719867298673986749867598676986779867898679986809868198682986839868498685986869868798688986899869098691986929869398694986959869698697986989869998700987019870298703987049870598706987079870898709987109871198712987139871498715987169871798718987199872098721987229872398724987259872698727987289872998730987319873298733987349873598736987379873898739987409874198742987439874498745987469874798748987499875098751987529875398754987559875698757987589875998760987619876298763987649876598766987679876898769987709877198772987739877498775987769877798778987799878098781987829878398784987859878698787987889878998790987919879298793987949879598796987979879898799988009880198802988039880498805988069880798808988099881098811988129881398814988159881698817988189881998820988219882298823988249882598826988279882898829988309883198832988339883498835988369883798838988399884098841988429884398844988459884698847988489884998850988519885298853988549885598856988579885898859988609886198862988639886498865988669886798868988699887098871988729887398874988759887698877988789887998880988819888298883988849888598886988879888898889988909889198892988939889498895988969889798898988999890098901989029890398904989059890698907989089890998910989119891298913989149891598916989179891898919989209892198922989239892498925989269892798928989299893098931989329893398934989359893698937989389893998940989419894298943989449894598946989479894898949989509895198952989539895498955989569895798958989599896098961989629896398964989659896698967989689896998970989719897298973989749897598976989779897898979989809898198982989839898498985989869898798988989899899098991989929899398994989959899698997989989899999000990019900299003990049900599006990079900899009990109901199012990139901499015990169901799018990199902099021990229902399024990259902699027990289902999030990319903299033990349903599036990379903899039990409904199042990439904499045990469904799048990499905099051990529905399054990559905699057990589905999060990619906299063990649906599066990679906899069990709907199072990739907499075990769907799078990799908099081990829908399084990859908699087990889908999090990919909299093990949909599096990979909899099991009910199102991039910499105991069910799108991099911099111991129911399114991159911699117991189911999120991219912299123991249912599126991279912899129991309913199132991339913499135991369913799138991399914099141991429914399144991459914699147991489914999150991519915299153991549915599156991579915899159991609916199162991639916499165991669916799168991699917099171991729917399174991759917699177991789917999180991819918299183991849918599186991879918899189991909919199192991939919499195991969919799198991999920099201992029920399204992059920699207992089920999210992119921299213992149921599216992179921899219992209922199222992239922499225992269922799228992299923099231992329923399234992359923699237992389923999240992419924299243992449924599246992479924899249992509925199252992539925499255992569925799258992599926099261992629926399264992659926699267992689926999270992719927299273992749927599276992779927899279992809928199282992839928499285992869928799288992899929099291992929929399294992959929699297992989929999300993019930299303993049930599306993079930899309993109931199312993139931499315993169931799318993199932099321993229932399324993259932699327993289932999330993319933299333993349933599336993379933899339993409934199342993439934499345993469934799348993499935099351993529935399354993559935699357993589935999360993619936299363993649936599366993679936899369993709937199372993739937499375993769937799378993799938099381993829938399384993859938699387993889938999390993919939299393993949939599396993979939899399994009940199402994039940499405994069940799408994099941099411994129941399414994159941699417994189941999420994219942299423994249942599426994279942899429994309943199432994339943499435994369943799438994399944099441994429944399444994459944699447994489944999450994519945299453994549945599456994579945899459994609946199462994639946499465994669946799468994699947099471994729947399474994759947699477994789947999480994819948299483994849948599486994879948899489994909949199492994939949499495994969949799498994999950099501995029950399504995059950699507995089950999510995119951299513995149951599516995179951899519995209952199522995239952499525995269952799528995299953099531995329953399534995359953699537995389953999540995419954299543995449954599546995479954899549995509955199552995539955499555995569955799558995599956099561995629956399564995659956699567995689956999570995719957299573995749957599576995779957899579995809958199582995839958499585995869958799588995899959099591995929959399594995959959699597995989959999600996019960299603996049960599606996079960899609996109961199612996139961499615996169961799618996199962099621996229962399624996259962699627996289962999630996319963299633996349963599636996379963899639996409964199642996439964499645996469964799648996499965099651996529965399654996559965699657996589965999660996619966299663996649966599666996679966899669996709967199672996739967499675996769967799678996799968099681996829968399684996859968699687996889968999690996919969299693996949969599696996979969899699997009970199702997039970499705997069970799708997099971099711997129971399714997159971699717997189971999720997219972299723997249972599726997279972899729997309973199732997339973499735997369973799738997399974099741997429974399744997459974699747997489974999750997519975299753997549975599756997579975899759997609976199762997639976499765997669976799768997699977099771997729977399774997759977699777997789977999780997819978299783997849978599786997879978899789997909979199792997939979499795997969979799798997999980099801998029980399804998059980699807998089980999810998119981299813998149981599816998179981899819998209982199822998239982499825998269982799828998299983099831998329983399834998359983699837998389983999840998419984299843998449984599846998479984899849998509985199852998539985499855998569985799858998599986099861998629986399864998659986699867998689986999870998719987299873998749987599876998779987899879998809988199882998839988499885998869988799888998899989099891998929989399894998959989699897998989989999900999019990299903999049990599906999079990899909999109991199912999139991499915999169991799918999199992099921999229992399924999259992699927999289992999930999319993299933999349993599936999379993899939999409994199942999439994499945999469994799948999499995099951999529995399954999559995699957999589995999960999619996299963999649996599966999679996899969999709997199972999739997499975999769997799978999799998099981999829998399984999859998699987999889998999990999919999299993999949999599996999979999899999100000100001100002100003100004100005100006100007100008100009100010100011100012100013100014100015100016100017100018100019100020100021100022100023100024100025100026100027100028100029100030100031100032100033100034100035100036100037100038100039100040100041100042100043100044100045100046100047100048100049100050100051100052100053100054100055100056100057100058100059100060100061100062100063100064100065100066100067100068100069100070100071100072100073100074100075100076100077100078100079100080100081100082100083100084100085100086100087100088100089100090100091100092100093100094100095100096100097100098100099100100100101100102100103100104100105100106100107100108100109100110100111100112100113100114100115100116100117100118100119100120100121100122100123100124100125100126100127100128100129100130100131100132100133100134100135100136100137100138100139100140100141100142100143100144100145100146100147100148100149100150100151100152100153100154100155100156100157100158100159100160100161100162100163100164100165100166100167100168100169100170100171100172100173100174100175100176100177100178100179100180100181100182100183100184100185100186100187100188100189100190100191100192100193100194100195100196100197100198100199100200100201100202100203100204100205100206100207100208100209100210100211100212100213100214100215100216100217100218100219100220100221100222100223100224100225100226100227100228100229100230100231100232100233100234100235100236100237100238100239100240100241100242100243100244100245100246100247100248100249100250100251100252100253100254100255100256100257100258100259100260100261100262100263100264100265100266100267100268100269100270100271100272100273100274100275100276100277100278100279100280100281100282100283100284100285100286100287100288100289100290100291100292100293100294100295100296100297100298100299100300100301100302100303100304100305100306100307100308100309100310100311100312100313100314100315100316100317100318100319100320100321100322100323100324100325100326100327100328100329100330100331100332100333100334100335100336100337100338100339100340100341100342100343100344100345100346100347100348100349100350100351100352100353100354100355100356100357100358100359100360100361100362100363100364100365100366100367100368100369100370100371100372100373100374100375100376100377100378100379100380100381100382100383100384100385100386100387100388100389100390100391100392100393100394100395100396100397100398100399100400100401100402100403100404100405100406100407100408100409100410100411100412100413100414100415100416100417100418100419100420100421100422100423100424100425100426100427100428100429100430100431100432100433100434100435100436100437100438100439100440100441100442100443100444100445100446100447100448100449100450100451100452100453100454100455100456100457100458100459100460100461100462100463100464100465100466100467100468100469100470100471100472100473100474100475100476100477100478100479100480100481100482100483100484100485100486100487100488100489100490100491100492100493100494100495100496100497100498100499100500100501100502100503100504100505100506100507100508100509100510100511100512100513100514100515100516100517100518100519100520100521100522100523100524100525100526100527100528100529100530100531100532100533100534100535100536100537100538100539100540100541100542100543100544100545100546100547100548100549100550100551100552100553100554100555100556100557100558100559100560100561100562100563100564100565100566100567100568100569100570100571100572100573100574100575100576100577100578100579100580100581100582100583100584100585100586100587100588100589100590100591100592100593100594100595100596100597100598100599100600100601100602100603100604100605100606100607100608100609100610100611100612100613100614100615100616100617100618100619100620100621100622100623100624100625100626100627100628100629100630100631100632100633100634100635100636100637100638100639100640100641100642100643100644100645100646100647100648100649100650100651100652100653100654100655100656100657100658100659100660100661100662100663100664100665100666100667100668100669100670100671100672100673100674100675100676100677100678100679100680100681100682100683100684100685100686100687100688100689100690100691100692100693100694100695100696100697100698100699100700100701100702100703100704100705100706100707100708100709100710100711100712100713100714100715100716100717100718100719100720100721100722100723100724100725100726100727100728100729100730100731100732100733100734100735100736100737100738100739100740100741100742100743100744100745100746100747100748100749100750100751100752100753100754100755100756100757100758100759100760100761100762100763100764100765100766100767100768100769100770100771100772100773100774100775100776100777100778100779100780100781100782100783100784100785100786100787100788100789100790100791100792100793100794100795100796100797100798100799100800100801100802100803100804100805100806100807100808100809100810100811100812100813100814100815100816100817100818100819100820100821100822100823100824100825100826100827100828100829100830100831100832100833100834100835100836100837100838100839100840100841100842100843100844100845100846100847100848100849100850100851100852100853100854100855100856100857100858100859100860100861100862100863100864100865100866100867100868100869100870100871100872100873100874100875100876100877100878100879100880100881100882100883100884100885100886100887100888100889100890100891100892100893100894100895100896100897100898100899100900100901100902100903100904100905100906100907100908100909100910100911100912100913100914100915100916100917100918100919100920100921100922100923100924100925100926100927100928100929100930100931100932100933100934100935100936100937100938100939100940100941100942100943100944100945100946100947100948100949100950100951100952100953100954100955100956100957100958100959100960100961100962100963100964100965100966100967100968100969100970100971100972100973100974100975100976100977100978100979100980100981100982100983100984100985100986100987100988100989100990100991100992100993100994100995100996100997100998100999101000101001101002101003101004101005101006101007101008101009101010101011101012101013101014101015101016101017101018101019101020101021101022101023101024101025101026101027101028101029101030101031101032101033101034101035101036101037101038101039101040101041101042101043101044101045101046101047101048101049101050101051101052101053101054101055101056101057101058101059101060101061101062101063101064101065101066101067101068101069101070101071101072101073101074101075101076101077101078101079101080101081101082101083101084101085101086101087101088101089101090101091101092101093101094101095101096101097101098101099101100101101101102101103101104101105101106101107101108101109101110101111101112101113101114101115101116101117101118101119101120101121101122101123101124101125101126101127101128101129101130101131101132101133101134101135101136101137101138101139101140101141101142101143101144101145101146101147101148101149101150101151101152101153101154101155101156101157101158101159101160101161101162101163101164101165101166101167101168101169101170101171101172101173101174101175101176101177101178101179101180101181101182101183101184101185101186101187101188101189101190101191101192101193101194101195101196101197101198101199101200101201101202101203101204101205101206101207101208101209101210101211101212101213101214101215101216101217101218101219101220101221101222101223101224101225101226101227101228101229101230101231101232101233101234101235101236101237101238101239101240101241101242101243101244101245101246101247101248101249101250101251101252101253101254101255101256101257101258101259101260101261101262101263101264101265101266101267101268101269101270101271101272101273101274101275101276101277101278101279101280101281101282101283101284101285101286101287101288101289101290101291101292101293101294101295101296101297101298101299101300101301101302101303101304101305101306101307101308101309101310101311101312101313101314101315101316101317101318101319101320101321101322101323101324101325101326101327101328101329101330101331101332101333101334101335101336101337101338101339101340101341101342101343101344101345101346101347101348101349101350101351101352101353101354101355101356101357101358101359101360101361101362101363101364101365101366101367101368101369101370101371101372101373101374101375101376101377101378101379101380101381101382101383101384101385101386101387101388101389101390101391101392101393101394101395101396101397101398101399101400101401101402101403101404101405101406101407101408101409101410101411101412101413101414101415101416101417101418101419101420101421101422101423101424101425101426101427101428101429101430101431101432101433101434101435101436101437101438101439101440101441101442101443101444101445101446101447101448101449101450101451101452101453101454101455101456101457101458101459101460101461101462101463101464101465101466101467101468101469101470101471101472101473101474101475101476101477101478101479101480101481101482101483101484101485101486101487101488101489101490101491101492101493101494101495101496101497101498101499101500101501101502101503101504101505101506101507101508101509101510101511101512101513101514101515101516101517101518101519101520101521101522101523101524101525101526101527101528101529101530101531101532101533101534101535101536101537101538101539101540101541101542101543101544101545101546101547101548101549101550101551101552101553101554101555101556101557101558101559101560101561101562101563101564101565101566101567101568101569101570101571101572101573101574101575101576101577101578101579101580101581101582101583101584101585101586101587101588101589101590101591101592101593101594101595101596101597101598101599101600101601101602101603101604101605101606101607101608101609101610101611101612101613101614101615101616101617101618101619101620101621101622101623101624101625101626101627101628101629101630101631101632101633101634101635101636101637101638101639101640101641101642101643101644101645101646101647101648101649101650101651101652101653101654101655101656101657101658101659101660101661101662101663101664101665101666101667101668101669101670101671101672101673101674101675101676101677101678101679101680101681101682101683101684101685101686101687101688101689101690101691101692101693101694101695101696101697101698101699101700101701101702101703101704101705101706101707101708101709101710101711101712101713101714101715101716101717101718101719101720101721101722101723101724101725101726101727101728101729101730101731101732101733101734101735101736101737101738101739101740101741101742101743101744101745101746101747101748101749101750101751101752101753101754101755101756101757101758101759101760101761101762101763101764101765101766101767101768101769101770101771101772101773101774101775101776101777101778101779101780101781101782101783101784101785101786101787101788101789101790101791101792101793101794101795101796101797101798101799101800101801101802101803101804101805101806101807101808101809101810101811101812101813101814101815101816101817101818101819101820101821101822101823101824101825101826101827101828101829101830101831101832101833101834101835101836101837101838101839101840101841101842101843101844101845101846101847101848101849101850101851101852101853101854101855101856101857101858101859101860101861101862101863101864101865101866101867101868101869101870101871101872101873101874101875101876101877101878101879101880101881101882101883101884101885101886101887101888101889101890101891101892101893101894101895101896101897101898101899101900101901101902101903101904101905101906101907101908101909101910101911101912101913101914101915101916101917101918101919101920101921101922101923101924101925101926101927101928101929101930101931101932101933101934101935101936101937101938101939101940101941101942101943101944101945101946101947101948101949101950101951101952101953101954101955101956101957101958101959101960101961101962101963101964101965101966101967101968101969101970101971101972101973101974101975101976101977101978101979101980101981101982101983101984101985101986101987101988101989101990101991101992101993101994101995101996101997101998101999102000102001102002102003102004102005102006102007102008102009102010102011102012102013102014102015102016102017102018102019102020102021102022102023102024102025102026102027102028102029102030102031102032102033102034102035102036102037102038102039102040102041102042102043102044102045102046102047102048102049102050102051102052102053102054102055102056102057102058102059102060102061102062102063102064102065102066102067102068102069102070102071102072102073102074102075102076102077102078102079102080102081102082102083102084102085102086102087102088102089102090102091102092102093102094102095102096102097102098102099102100102101102102102103102104102105102106102107102108102109102110102111102112102113102114102115102116102117102118102119102120102121102122102123102124102125102126102127102128102129102130102131102132102133102134102135102136102137102138102139102140102141102142102143102144102145102146102147102148102149102150102151102152102153102154102155102156102157102158102159102160102161102162102163102164102165102166102167102168102169102170102171102172102173102174102175102176102177102178102179102180102181102182102183102184102185102186102187102188102189102190102191102192102193102194102195102196102197102198102199102200102201102202102203102204102205102206102207102208102209102210102211102212102213102214102215102216102217102218102219102220102221102222102223102224102225102226102227102228102229102230102231102232102233102234102235102236102237102238102239102240102241102242102243102244102245102246102247102248102249102250102251102252102253102254102255102256102257102258102259102260102261102262102263102264102265102266102267102268102269102270102271102272102273102274102275102276102277102278102279102280102281102282102283102284102285102286102287102288102289102290102291102292102293102294102295102296102297102298102299102300102301102302102303102304102305102306102307102308102309102310102311102312102313102314102315102316102317102318102319102320102321102322102323102324102325102326102327102328102329102330102331102332102333102334102335102336102337102338102339102340102341102342102343102344102345102346102347102348102349102350102351102352102353102354102355102356102357102358102359102360102361102362102363102364102365102366102367102368102369102370102371102372102373102374102375102376102377102378102379102380102381102382102383102384102385102386102387102388102389102390102391102392102393102394102395102396102397102398102399102400102401102402102403102404102405102406102407102408102409102410102411102412102413102414102415102416102417102418102419102420102421102422102423102424102425102426102427102428102429102430102431102432102433102434102435102436102437102438102439102440102441102442102443102444102445102446102447102448102449102450102451102452102453102454102455102456102457102458102459102460102461102462102463102464102465102466102467102468102469102470102471102472102473102474102475102476102477102478102479102480102481102482102483102484102485102486102487102488102489102490102491102492102493102494102495102496102497102498102499102500102501102502102503102504102505102506102507102508102509102510102511102512102513102514102515102516102517102518102519102520102521102522102523102524102525102526102527102528102529102530102531102532102533102534102535102536102537102538102539102540102541102542102543102544102545102546102547102548102549102550102551102552102553102554102555102556102557102558102559102560102561102562102563102564102565102566102567102568102569102570102571102572102573102574102575102576102577102578102579102580102581102582102583102584102585102586102587102588102589102590102591102592102593102594102595102596102597102598102599102600102601102602102603102604102605102606102607102608102609102610102611102612102613102614102615102616102617102618102619102620102621102622102623102624102625102626102627102628102629102630102631102632102633102634102635102636102637102638102639102640102641102642102643102644102645102646102647102648102649102650102651102652102653102654102655102656102657102658102659102660102661102662102663102664102665102666102667102668102669102670102671102672102673102674102675102676102677102678102679102680102681102682102683102684102685102686102687102688102689102690102691102692102693102694102695102696102697102698102699102700102701102702102703102704102705102706102707102708102709102710102711102712102713102714102715102716102717102718102719102720102721102722102723102724102725102726102727102728102729102730102731102732102733102734102735102736102737102738102739102740102741102742102743102744102745102746102747102748102749102750102751102752102753102754102755102756102757102758102759102760102761102762102763102764102765102766102767102768102769102770102771102772102773102774102775102776102777102778102779102780102781102782102783102784102785102786102787102788102789102790102791102792102793102794102795102796102797102798102799102800102801102802102803102804102805102806102807102808102809102810102811102812102813102814102815102816102817102818102819102820102821102822102823102824102825102826102827102828102829102830102831102832102833102834102835102836102837102838102839102840102841102842102843102844102845102846102847102848102849102850102851102852102853102854102855102856102857102858102859102860102861102862102863102864102865102866102867102868102869102870102871102872102873102874102875102876102877102878102879102880102881102882102883102884102885102886102887102888102889102890102891102892102893102894102895102896102897102898102899102900102901102902102903102904102905102906102907102908102909102910102911102912102913102914102915102916102917102918102919102920102921102922102923102924102925102926102927102928102929102930102931102932102933102934102935102936102937102938102939102940102941102942102943102944102945102946102947102948102949102950102951102952102953102954102955102956102957102958102959102960102961102962102963102964102965102966102967102968102969102970102971102972102973102974102975102976102977102978102979102980102981102982102983102984102985102986102987102988102989102990102991102992102993102994102995102996102997102998102999103000103001103002103003103004103005103006103007103008103009103010103011103012103013103014103015103016103017103018103019103020103021103022103023103024103025103026103027103028103029103030103031103032103033103034103035103036103037103038103039103040103041103042103043103044103045103046103047103048103049103050103051103052103053103054103055103056103057103058103059103060103061103062103063103064103065103066103067103068103069103070103071103072103073103074103075103076103077103078103079103080103081103082103083103084103085103086103087103088103089103090103091103092103093103094103095103096103097103098103099103100103101103102103103103104103105103106103107103108103109103110103111103112103113103114103115103116103117103118103119103120103121103122103123103124103125103126103127103128103129103130103131103132103133103134103135103136103137103138103139103140103141103142103143103144103145103146103147103148103149103150103151103152103153103154103155103156103157103158103159103160103161103162103163103164103165103166103167103168103169103170103171103172103173103174103175103176103177103178103179103180103181103182103183103184103185103186103187103188103189103190103191103192103193103194103195103196103197103198103199103200103201103202103203103204103205103206103207103208103209103210103211103212103213103214103215103216103217103218103219103220103221103222103223103224103225103226103227103228103229103230103231103232103233103234103235103236103237103238103239103240103241103242103243103244103245103246103247103248103249103250103251103252103253103254103255103256103257103258103259103260103261103262103263103264103265103266103267103268103269103270103271103272103273103274103275103276103277103278103279103280103281103282103283103284103285103286103287103288103289103290103291103292103293103294103295103296103297103298103299103300103301103302103303103304103305103306103307103308103309103310103311103312103313103314103315103316103317103318103319103320103321103322103323103324103325103326103327103328103329103330103331103332103333103334103335103336103337103338103339103340103341103342103343103344103345103346103347103348103349103350103351103352103353103354103355103356103357103358103359103360103361103362103363103364103365103366103367103368103369103370103371103372103373103374103375103376103377103378103379103380103381103382103383103384103385103386103387103388103389103390103391103392103393103394103395103396103397103398103399103400103401103402103403103404103405103406103407103408103409103410103411103412103413103414103415103416103417103418103419103420103421103422103423103424103425103426103427103428103429103430103431103432103433103434103435103436103437103438103439103440103441103442103443103444103445103446103447103448103449103450103451103452103453103454103455103456103457103458103459103460103461103462103463103464103465103466103467103468103469103470103471103472103473103474103475103476103477103478103479103480103481103482103483103484103485103486103487103488103489103490103491103492103493103494103495103496103497103498103499103500103501103502103503103504103505103506103507103508103509103510103511103512103513103514103515103516103517103518103519103520103521103522103523103524103525103526103527103528103529103530103531103532103533103534103535103536103537103538103539103540103541103542103543103544103545103546103547103548103549103550103551103552103553103554103555103556103557103558103559103560103561103562103563103564103565103566103567103568103569103570103571103572103573103574103575103576103577103578103579103580103581103582103583103584103585103586103587103588103589103590103591103592103593103594103595103596103597103598103599103600103601103602103603103604103605103606103607103608103609103610103611103612103613103614103615103616103617103618103619103620103621103622103623103624103625103626103627103628103629103630103631103632103633103634103635103636103637103638103639103640103641103642103643103644103645103646103647103648103649103650103651103652103653103654103655103656103657103658103659103660103661103662103663103664103665103666103667103668103669103670103671103672103673103674103675103676103677103678103679103680103681103682103683103684103685103686103687103688103689103690103691103692103693103694103695103696103697103698103699103700103701103702103703103704103705103706103707103708103709103710103711103712103713103714103715103716103717103718103719103720103721103722103723103724103725103726103727103728103729103730103731103732103733103734103735103736103737103738103739103740103741103742103743103744103745103746103747103748103749103750103751103752103753103754103755103756103757103758103759103760103761103762103763103764103765103766103767103768103769103770103771103772103773103774103775103776103777103778103779103780103781103782103783103784103785103786103787103788103789103790103791103792103793103794103795103796103797103798103799103800103801103802103803103804103805103806103807103808103809103810103811103812103813103814103815103816103817103818103819103820103821103822103823103824103825103826103827103828103829103830103831103832103833103834103835103836103837103838103839103840103841103842103843103844103845103846103847103848103849103850103851103852103853103854103855103856103857103858103859103860103861103862103863103864103865103866103867103868103869103870103871103872103873103874103875103876103877103878103879103880103881103882103883103884103885103886103887103888103889103890103891103892103893103894103895103896103897103898103899103900103901103902103903103904103905103906103907103908103909103910103911103912103913103914103915103916103917103918103919103920103921103922103923103924103925103926103927103928103929103930103931103932103933103934103935103936103937103938103939103940103941103942103943103944103945103946103947103948103949103950103951103952103953103954103955103956103957103958103959103960103961103962103963103964103965103966103967103968103969103970103971103972103973103974103975103976103977103978103979103980103981103982103983103984103985103986103987103988103989103990103991103992103993103994103995103996103997103998103999104000104001104002104003104004104005104006104007104008104009104010104011104012104013104014104015104016104017104018104019104020104021104022104023104024104025104026104027104028104029104030104031104032104033104034104035104036104037104038104039104040104041104042104043104044104045104046104047104048104049104050104051104052104053104054104055104056104057104058104059104060104061104062104063104064104065104066104067104068104069104070104071104072104073104074104075104076104077104078104079104080104081104082104083104084104085104086104087104088104089104090104091104092104093104094104095104096104097104098104099104100104101104102104103104104104105104106104107104108104109104110104111104112104113104114104115104116104117104118104119104120104121104122104123104124104125104126104127104128104129104130104131104132104133104134104135104136104137104138104139104140104141104142104143104144104145104146104147104148104149104150104151104152104153104154104155104156104157104158104159104160104161104162104163104164104165104166104167104168104169104170104171104172104173104174104175104176104177104178104179104180104181104182104183104184104185104186104187104188104189104190104191104192104193104194104195104196104197104198104199104200104201104202104203104204104205104206104207104208104209104210104211104212104213104214104215104216104217104218104219104220104221104222104223104224104225104226104227104228104229104230104231104232104233104234104235104236104237104238104239104240104241104242104243104244104245104246104247104248104249104250104251104252104253104254104255104256104257104258104259104260104261104262104263104264104265104266104267104268104269104270104271104272104273104274104275104276104277104278104279104280104281104282104283104284104285104286104287104288104289104290104291104292104293104294104295104296104297104298104299104300104301104302104303104304104305104306104307104308104309104310104311104312104313104314104315104316104317104318104319104320104321104322104323104324104325104326104327104328104329104330104331104332104333104334104335104336104337104338104339104340104341104342104343104344104345104346104347104348104349104350104351104352104353104354104355104356104357104358104359104360104361104362104363104364104365104366104367104368104369104370104371104372104373104374104375104376104377104378104379104380104381104382104383104384104385104386104387104388104389104390104391104392104393104394104395104396104397104398104399104400104401104402104403104404104405104406104407104408104409104410104411104412104413104414104415104416104417104418104419104420104421104422104423104424104425104426104427104428104429104430104431104432104433104434104435104436104437104438104439104440104441104442104443104444104445104446104447104448104449104450104451104452104453104454104455104456104457104458104459104460104461104462104463104464104465104466104467104468104469104470104471104472104473104474104475104476104477104478104479104480104481104482104483104484104485104486104487104488104489104490104491104492104493104494104495104496104497104498104499104500104501104502104503104504104505104506104507104508104509104510104511104512104513104514104515104516104517104518104519104520104521104522104523104524104525104526104527104528104529104530104531104532104533104534104535104536104537104538104539104540104541104542104543104544104545104546104547104548104549104550104551104552104553104554104555104556104557104558104559104560104561104562104563104564104565104566104567104568104569104570104571104572104573104574104575104576104577104578104579104580104581104582104583104584104585104586104587104588104589104590104591104592104593104594104595104596104597104598104599104600104601104602104603104604104605104606104607104608104609104610104611104612104613104614104615104616104617104618104619104620104621104622104623104624104625104626104627104628104629104630104631104632104633104634104635104636104637104638104639104640104641104642104643104644104645104646104647104648104649104650104651104652104653104654104655104656104657104658104659104660104661104662104663104664104665104666104667104668104669104670104671104672104673104674104675104676104677104678104679104680104681104682104683104684104685104686104687104688104689104690104691104692104693104694104695104696104697104698104699104700104701104702104703104704104705104706104707104708104709104710104711104712104713104714104715104716104717104718104719104720104721104722104723104724104725104726104727104728104729104730104731104732104733104734104735104736104737104738104739104740104741104742104743104744104745104746104747104748104749104750104751104752104753104754104755104756104757104758104759104760104761104762104763104764104765104766104767104768104769104770104771104772104773104774104775104776104777104778104779104780104781104782104783104784104785104786104787104788104789104790104791104792104793104794104795104796104797104798104799104800104801104802104803104804104805104806104807104808104809104810104811104812104813104814104815104816104817104818104819104820104821104822104823104824104825104826104827104828104829104830104831104832104833104834104835104836104837104838104839104840104841104842104843104844104845104846104847104848104849104850104851104852104853104854104855104856104857104858104859104860104861104862104863104864104865104866104867104868104869104870104871104872104873104874104875104876104877104878104879104880104881104882104883104884104885104886104887104888104889104890104891104892104893104894104895104896104897104898104899104900104901104902104903104904104905104906104907104908104909104910104911104912104913104914104915104916104917104918104919104920104921104922104923104924104925104926104927104928104929104930104931104932104933104934104935104936104937104938104939104940104941104942104943104944104945104946104947104948104949104950104951104952104953104954104955104956104957104958104959104960104961104962104963104964104965104966104967104968104969104970104971104972104973104974104975104976104977104978104979104980104981104982104983104984104985104986104987104988104989104990104991104992104993104994104995104996104997104998104999105000105001105002105003105004105005105006105007105008105009105010105011105012105013105014105015105016105017105018105019105020105021105022105023105024105025105026105027105028105029105030105031105032105033105034105035105036105037105038105039105040105041105042105043105044105045105046105047105048105049105050105051105052105053105054105055105056105057105058105059105060105061105062105063105064105065105066105067105068105069105070105071105072105073105074105075105076105077105078105079105080105081105082105083105084105085105086105087105088105089105090105091105092105093105094105095105096105097105098105099105100105101105102105103105104105105105106105107105108105109105110105111105112105113105114105115105116105117105118105119105120105121105122105123105124105125105126105127105128105129105130105131105132105133105134105135105136105137105138105139105140105141105142105143105144105145105146105147105148105149105150105151105152105153105154105155105156105157105158105159105160105161105162105163105164105165105166105167105168105169105170105171105172105173105174105175105176105177105178105179105180105181105182105183105184105185105186105187105188105189105190105191105192105193105194105195105196105197105198105199105200105201105202105203105204105205105206105207105208105209105210105211105212105213105214105215105216105217105218105219105220105221105222105223105224105225105226105227105228105229105230105231105232105233105234105235105236105237105238105239105240105241105242105243105244105245105246105247105248105249105250105251105252105253105254105255105256105257105258105259105260105261105262105263105264105265105266105267105268105269105270105271105272105273105274105275105276105277105278105279105280105281105282105283105284105285105286105287105288105289105290105291105292105293105294105295105296105297105298105299105300105301105302105303105304105305105306105307105308105309105310105311105312105313105314105315105316105317105318105319105320105321105322105323105324105325105326105327105328105329105330105331105332105333105334105335105336105337105338105339105340105341105342105343105344105345105346105347105348105349105350105351105352105353105354105355105356105357105358105359105360105361105362105363105364105365105366105367105368105369105370105371105372105373105374105375105376105377105378105379105380105381105382105383105384105385105386105387105388105389105390105391105392105393105394105395105396105397105398105399105400105401105402105403105404105405105406105407105408105409105410105411105412105413105414105415105416105417105418105419105420105421105422105423105424105425105426105427105428105429105430105431105432105433105434105435105436105437105438105439105440105441105442105443105444105445105446105447105448105449105450105451105452105453105454105455105456105457105458105459105460105461105462105463105464105465105466105467105468105469105470105471105472105473105474105475105476105477105478105479105480105481105482105483105484105485105486105487105488105489105490105491105492105493105494105495105496105497105498105499105500105501105502105503105504105505105506105507105508105509105510105511105512105513105514105515105516105517105518105519105520105521105522105523105524105525105526105527105528105529105530105531105532105533105534105535105536105537105538105539105540105541105542105543105544105545105546105547105548105549105550105551105552105553105554105555105556105557105558105559105560105561105562105563105564105565105566105567105568105569105570105571105572105573105574105575105576105577105578105579105580105581105582105583105584105585105586105587105588105589105590105591105592105593105594105595105596105597105598105599105600105601105602105603105604105605105606105607105608105609105610105611105612105613105614105615105616105617105618105619105620105621105622105623105624105625105626105627105628105629105630105631105632105633105634105635105636105637105638105639105640105641105642105643105644105645105646105647105648105649105650105651105652105653105654105655105656105657105658105659105660105661105662105663105664105665105666105667105668105669105670105671105672105673105674105675105676105677105678105679105680105681105682105683105684105685105686105687105688105689105690105691105692105693105694105695105696105697105698105699105700105701105702105703105704105705105706105707105708105709105710105711105712105713105714105715105716105717105718105719105720105721105722105723105724105725105726105727105728105729105730105731105732105733105734105735105736105737105738105739105740105741105742105743105744105745105746105747105748105749105750105751105752105753105754105755105756105757105758105759105760105761105762105763105764105765105766105767105768105769105770105771105772105773105774105775105776105777105778105779105780105781105782105783105784105785105786105787105788105789105790105791105792105793105794105795105796105797105798105799105800105801105802105803105804105805105806105807105808105809105810105811105812105813105814105815105816105817105818105819105820105821105822105823105824105825105826105827105828105829105830105831105832105833105834105835105836105837105838105839105840105841105842105843105844105845105846105847105848105849105850105851105852105853105854105855105856105857105858105859105860105861105862105863105864105865105866105867105868105869105870105871105872105873105874105875105876105877105878105879105880105881105882105883105884105885105886105887105888105889105890105891105892105893105894105895105896105897105898105899105900105901105902105903105904105905105906105907105908105909105910105911105912105913105914105915105916105917105918105919105920105921105922105923105924105925105926105927105928105929105930105931105932105933105934105935105936105937105938105939105940105941105942105943105944105945105946105947105948105949105950105951105952105953105954105955105956105957105958105959105960105961105962105963105964105965105966105967105968105969105970105971105972105973105974105975105976105977105978105979105980105981105982105983105984105985105986105987105988105989105990105991105992105993105994105995105996105997105998105999106000106001106002106003106004106005106006106007106008106009106010106011106012106013106014106015106016106017106018106019106020106021106022106023106024106025106026106027106028106029106030106031106032106033106034106035106036106037106038106039106040106041106042106043106044106045106046106047106048106049106050106051106052106053106054106055106056106057106058106059106060106061106062106063106064106065106066106067106068106069106070106071106072106073106074106075106076106077106078106079106080106081106082106083106084106085106086106087106088106089106090106091106092106093106094106095106096106097106098106099106100106101106102106103106104106105106106106107106108106109106110106111106112106113106114106115106116106117106118106119106120106121106122106123106124106125106126106127106128106129106130106131106132106133106134106135106136106137106138106139106140106141106142106143106144106145106146106147106148106149106150106151106152106153106154106155106156106157106158106159106160106161106162106163106164106165106166106167106168106169106170106171106172106173106174106175106176106177106178106179106180106181106182106183106184106185106186106187106188106189106190106191106192106193106194106195106196106197106198106199106200106201106202106203106204106205106206106207106208106209106210106211106212106213106214106215106216106217106218106219106220106221106222106223106224106225106226106227106228106229106230106231106232106233106234106235106236106237106238106239106240106241106242106243106244106245106246106247106248106249106250106251106252106253106254106255106256106257106258106259106260106261106262106263106264106265106266106267106268106269106270106271106272106273106274106275106276106277106278106279106280106281106282106283106284106285106286106287106288106289106290106291106292106293106294106295106296106297106298106299106300106301106302106303106304106305106306106307106308106309106310106311106312106313106314106315106316106317106318106319106320106321106322106323106324106325106326106327106328106329106330106331106332106333106334106335106336106337106338106339106340106341106342106343106344106345106346106347106348106349106350106351106352106353106354106355106356106357106358106359106360106361106362106363106364106365106366106367106368106369106370106371106372106373106374106375106376106377106378106379106380106381106382106383106384106385106386106387106388106389106390106391106392106393106394106395106396106397106398106399106400106401106402106403106404106405106406106407106408106409106410106411106412106413106414106415106416106417106418106419106420106421106422106423106424106425106426106427106428106429106430106431106432106433106434106435106436106437106438106439106440106441106442106443106444106445106446106447106448106449106450106451106452106453106454106455106456106457106458106459106460106461106462106463106464106465106466106467106468106469106470106471106472106473106474106475106476106477106478106479106480106481106482106483106484106485106486106487106488106489106490106491106492106493106494106495106496106497106498106499106500106501106502106503106504106505106506106507106508106509106510106511106512106513106514106515106516106517106518106519106520106521106522106523106524106525106526106527106528106529106530106531106532106533106534106535106536106537106538106539106540106541106542106543106544106545106546106547106548106549106550106551106552106553106554106555106556106557106558106559106560106561106562106563106564106565106566106567106568106569106570106571106572106573106574106575106576106577106578106579106580106581106582106583106584106585106586106587106588106589106590106591106592106593106594106595106596106597106598106599106600106601106602106603106604106605106606106607106608106609106610106611106612106613106614106615106616106617106618106619106620106621106622106623106624106625106626106627106628106629106630106631106632106633106634106635106636106637106638106639106640106641106642106643106644106645106646106647106648106649106650106651106652106653106654106655106656106657106658106659106660106661106662106663106664106665106666106667106668106669106670106671106672106673106674106675106676106677106678106679106680106681106682106683106684106685106686106687106688106689106690106691106692106693106694106695106696106697106698106699106700106701106702106703106704106705106706106707106708106709106710106711106712106713106714106715106716106717106718106719106720106721106722106723106724106725106726106727106728106729106730106731106732106733106734106735106736106737106738106739106740106741106742106743106744106745106746106747106748106749106750106751106752106753106754106755106756106757106758106759106760106761106762106763106764106765106766106767106768106769106770106771106772106773106774106775106776106777106778106779106780106781106782106783106784106785106786106787106788106789106790106791106792106793106794106795106796106797106798106799106800106801106802106803106804106805106806106807106808106809106810106811106812106813106814106815106816106817106818106819106820106821106822106823106824106825106826106827106828106829106830106831106832106833106834106835106836106837106838106839106840106841106842106843106844106845106846106847106848106849106850106851106852106853106854106855106856106857106858106859106860106861106862106863106864106865106866106867106868106869106870106871106872106873106874106875106876106877106878106879106880106881106882106883106884106885106886106887106888106889106890106891106892106893106894106895106896106897106898106899106900106901106902106903106904106905106906106907106908106909106910106911106912106913106914106915106916106917106918106919106920106921106922106923106924106925106926106927106928106929106930106931106932106933106934106935106936106937106938106939106940106941106942106943106944106945106946106947106948106949106950106951106952106953106954106955106956106957106958106959106960106961106962106963106964106965106966106967106968106969106970106971106972106973106974106975106976106977106978106979106980106981106982106983106984106985106986106987106988106989106990106991106992106993106994106995106996106997106998106999107000107001107002107003107004107005107006107007107008107009107010107011107012107013107014107015107016107017107018107019107020107021107022107023107024107025107026107027107028107029107030107031107032107033107034107035107036107037107038107039107040107041107042107043107044107045107046107047107048107049107050107051107052107053107054107055107056107057107058107059107060107061107062107063107064107065107066107067107068107069107070107071107072107073107074107075107076107077107078107079107080107081107082107083107084107085107086107087107088107089107090107091107092107093107094107095107096107097107098107099107100107101107102107103107104107105107106107107107108107109107110107111107112107113107114107115107116107117107118107119107120107121107122107123107124107125107126107127107128107129107130107131107132107133107134107135107136107137107138107139107140107141107142107143107144107145107146107147107148107149107150107151107152107153107154107155107156107157107158107159107160107161107162107163107164107165107166107167107168107169107170107171107172107173107174107175107176107177107178107179107180107181107182107183107184107185107186107187107188107189107190107191107192107193107194107195107196107197107198107199107200107201107202107203107204107205107206107207107208107209107210107211107212107213107214107215107216107217107218107219107220107221107222107223107224107225107226107227107228107229107230107231107232107233107234107235107236107237107238107239107240107241107242107243107244107245107246107247107248107249107250107251107252107253107254107255107256107257107258107259107260107261107262107263107264107265107266107267107268107269107270107271107272107273107274107275107276107277107278107279107280107281107282107283107284107285107286107287107288107289107290107291107292107293107294107295107296107297107298107299107300107301107302107303107304107305107306107307107308107309107310107311107312107313107314107315107316107317107318107319107320107321107322107323107324107325107326107327107328107329107330107331107332107333107334107335107336107337107338107339107340107341107342107343107344107345107346107347107348107349107350107351107352107353107354107355107356107357107358107359107360107361107362107363107364107365107366107367107368107369107370107371107372107373107374107375107376107377107378107379107380107381107382107383107384107385107386107387107388107389107390107391107392107393107394107395107396107397107398107399107400107401107402107403107404107405107406107407107408107409107410107411107412107413107414107415107416107417107418107419107420107421107422107423107424107425107426107427107428107429107430107431107432107433107434107435107436107437107438107439107440107441107442107443107444107445107446107447107448107449107450107451107452107453107454107455107456107457107458107459107460107461107462107463107464107465107466107467107468107469107470107471107472107473107474107475107476107477107478107479107480107481107482107483107484107485107486107487107488107489107490107491107492107493107494107495107496107497107498107499107500107501107502107503107504107505107506107507107508107509107510107511107512107513107514107515107516107517107518107519107520107521107522107523107524107525107526107527107528107529107530107531107532107533107534107535107536107537107538107539107540107541107542107543107544107545107546107547107548107549107550107551107552107553107554107555107556107557107558107559107560107561107562107563107564107565107566107567107568107569107570107571107572107573107574107575107576107577107578107579107580107581107582107583107584107585107586107587107588107589107590107591107592107593107594107595107596107597107598107599107600107601107602107603107604107605107606107607107608107609107610107611107612107613107614107615107616107617107618107619107620107621107622107623107624107625107626107627107628107629107630107631107632107633107634107635107636107637107638107639107640107641107642107643107644107645107646107647107648107649107650107651107652107653107654107655107656107657107658107659107660107661107662107663107664107665107666107667107668107669107670107671107672107673107674107675107676107677107678107679107680107681107682107683107684107685107686107687107688107689107690107691107692107693107694107695107696107697107698107699107700107701107702107703107704107705107706107707107708107709107710107711107712107713107714107715107716107717107718107719107720107721107722107723107724107725107726107727107728107729107730107731107732107733107734107735107736107737107738107739107740107741107742107743107744107745107746107747107748107749107750107751107752107753107754107755107756107757107758107759107760107761107762107763107764107765107766107767107768107769107770107771107772107773107774107775107776107777107778107779107780107781107782107783107784107785107786107787107788107789107790107791107792107793107794107795107796107797107798107799107800107801107802107803107804107805107806107807107808107809107810107811107812107813107814107815107816107817107818107819107820107821107822107823107824107825107826107827107828107829107830107831107832107833107834107835107836107837107838107839107840107841107842107843107844107845107846107847107848107849107850107851107852107853107854107855107856107857107858107859107860107861107862107863107864107865107866107867107868107869107870107871107872107873107874107875107876107877107878107879107880107881107882107883107884107885107886107887107888107889107890107891107892107893107894107895107896107897107898107899107900107901107902107903107904107905107906107907107908107909107910107911107912107913107914107915107916107917107918107919107920107921107922107923107924107925107926107927107928107929107930107931107932107933107934107935107936107937107938107939107940107941107942107943107944107945107946107947107948107949107950107951107952107953107954107955107956107957107958107959107960107961107962107963107964107965107966107967107968107969107970107971107972107973107974107975107976107977107978107979107980107981107982107983107984107985107986107987107988107989107990107991107992107993107994107995107996107997107998107999108000108001108002108003108004108005108006108007108008108009108010108011108012108013108014108015108016108017108018108019108020108021108022108023108024108025108026108027108028108029108030108031108032108033108034108035108036108037108038108039108040108041108042108043108044108045108046108047108048108049108050108051108052108053108054108055108056108057108058108059108060108061108062108063108064108065108066108067108068108069108070108071108072108073108074108075108076108077108078108079108080108081108082108083108084108085108086108087108088108089108090108091108092108093108094108095108096108097108098108099108100108101108102108103108104108105108106108107108108108109108110108111108112108113108114108115108116108117108118108119108120108121108122108123108124108125108126108127108128108129108130108131108132108133108134108135108136108137108138108139108140108141108142108143108144108145108146108147108148108149108150108151108152108153108154108155108156108157108158108159108160108161108162108163108164108165108166108167108168108169108170108171108172108173108174108175108176108177108178108179108180108181108182108183108184108185108186108187108188108189108190108191108192108193108194108195108196108197108198108199108200108201108202108203108204108205108206108207108208108209108210108211108212108213108214108215108216108217108218108219108220108221108222108223108224108225108226108227108228108229108230108231108232108233108234108235108236108237108238108239108240108241108242108243108244108245108246108247108248108249108250108251108252108253108254108255108256108257108258108259108260108261108262108263108264108265108266108267108268108269108270108271108272108273108274108275108276108277108278108279108280108281108282108283108284108285108286108287108288108289108290108291108292108293108294108295108296108297108298108299108300108301108302108303108304108305108306108307108308108309108310108311108312108313108314108315108316108317108318108319108320108321108322108323108324108325108326108327108328108329108330108331108332108333108334108335108336108337108338108339108340108341108342108343108344108345108346108347108348108349108350108351108352108353108354108355108356108357108358108359108360108361108362108363108364108365108366108367108368108369108370108371108372108373108374108375108376108377108378108379108380108381108382108383108384108385108386108387108388108389108390108391108392108393108394108395108396108397108398108399108400108401108402108403108404108405108406108407108408108409108410108411108412108413108414108415108416108417108418108419108420108421108422108423108424108425108426108427108428108429108430108431108432108433108434108435108436108437108438108439108440108441108442108443108444108445108446108447108448108449108450108451108452108453108454108455108456108457108458108459108460108461108462108463108464108465108466108467108468108469108470108471108472108473108474108475108476108477108478108479108480108481108482108483108484108485108486108487108488108489108490108491108492108493108494108495108496108497108498108499108500108501108502108503108504108505108506108507108508108509108510108511108512108513108514108515108516108517108518108519108520108521108522108523108524108525108526108527108528108529108530108531108532108533108534108535108536108537108538108539108540108541108542108543108544108545108546108547108548108549108550108551108552108553108554108555108556108557108558108559108560108561108562108563108564108565108566108567108568108569108570108571108572108573108574108575108576108577108578108579108580108581108582108583108584108585108586108587108588108589108590108591108592108593108594108595108596108597108598108599108600108601108602108603108604108605108606108607108608108609108610108611108612108613108614108615108616108617108618108619108620108621108622108623108624108625108626108627108628108629108630108631108632108633108634108635108636108637108638108639108640108641108642108643108644108645108646108647108648108649108650108651108652108653108654108655108656108657108658108659108660108661108662108663108664108665108666108667108668108669108670108671108672108673108674108675108676108677108678108679108680108681108682108683108684108685108686108687108688108689108690108691108692108693108694108695108696108697108698108699108700108701108702108703108704108705108706108707108708108709108710108711108712108713108714108715108716108717108718108719108720108721108722108723108724108725108726108727108728108729108730108731108732108733108734108735108736108737108738108739108740108741108742108743108744108745108746108747108748108749108750108751108752108753108754108755108756108757108758108759108760108761108762108763108764108765108766108767108768108769108770108771108772108773108774108775108776108777108778108779108780108781108782108783108784108785108786108787108788108789108790108791108792108793108794108795108796108797108798108799108800108801108802108803108804108805108806108807108808108809108810108811108812108813108814108815108816108817108818108819108820108821108822108823108824108825108826108827108828108829108830108831108832108833108834108835108836108837108838108839108840108841108842108843108844108845108846108847108848108849108850108851108852108853108854108855108856108857108858108859108860108861108862108863108864108865108866108867108868108869108870108871108872108873108874108875108876108877108878108879108880108881108882108883108884108885108886108887108888108889108890108891108892108893108894108895108896108897108898108899108900108901108902108903108904108905108906108907108908108909108910108911108912108913108914108915108916108917108918108919108920108921108922108923108924108925108926108927108928108929108930108931108932108933108934108935108936108937108938108939108940108941108942108943108944108945108946108947108948108949108950108951108952108953108954108955108956108957108958108959108960108961108962108963108964108965108966108967108968108969108970108971108972108973108974108975108976108977108978108979108980108981108982108983108984108985108986108987108988108989108990108991108992108993108994108995108996108997108998108999109000109001109002109003109004109005109006109007109008109009109010109011109012109013109014109015109016109017109018109019109020109021109022109023109024109025109026109027109028109029109030109031109032109033109034109035109036109037109038109039109040109041109042109043109044109045109046109047109048109049109050109051109052109053109054109055109056109057109058109059109060109061109062109063109064109065109066109067109068109069109070109071109072109073109074109075109076109077109078109079109080109081109082109083109084109085109086109087109088109089109090109091109092109093109094109095109096109097109098109099109100109101109102109103109104109105109106109107109108109109109110109111109112109113109114109115109116109117109118109119109120109121109122109123109124109125109126109127109128109129109130109131109132109133109134109135109136109137109138109139109140109141109142109143109144109145109146109147109148109149109150109151109152109153109154109155109156109157109158109159109160109161109162109163109164109165109166109167109168109169109170109171109172109173109174109175109176109177109178109179109180109181109182109183109184109185109186109187109188109189109190109191109192109193109194109195109196109197109198109199109200109201109202109203109204109205109206109207109208109209109210109211109212109213109214109215109216109217109218109219109220109221109222109223109224109225109226109227109228109229109230109231109232109233109234109235109236109237109238109239109240109241109242109243109244109245109246109247109248109249109250109251109252109253109254109255109256109257109258109259109260109261109262109263109264109265109266109267109268109269109270109271109272109273109274109275109276109277109278109279109280109281109282109283109284109285109286109287109288109289109290109291109292109293109294109295109296109297109298109299109300109301109302109303109304109305109306109307109308109309109310109311109312109313109314109315109316109317109318109319109320109321109322109323109324109325109326109327109328109329109330109331109332109333109334109335109336109337109338109339109340109341109342109343109344109345109346109347109348109349109350109351109352109353109354109355109356109357109358109359109360109361109362109363109364109365109366109367109368109369109370109371109372109373109374109375109376109377109378109379109380109381109382109383109384109385109386109387109388109389109390109391109392109393109394109395109396109397109398109399109400109401109402109403109404109405109406109407109408109409109410109411109412109413109414109415109416109417109418109419109420109421109422109423109424109425109426109427109428109429109430109431109432109433109434109435109436109437109438109439109440109441109442109443109444109445109446109447109448109449109450109451109452109453109454109455109456109457109458109459109460109461109462109463109464109465109466109467109468109469109470109471109472109473109474109475109476109477109478109479109480109481109482109483109484109485109486109487109488109489109490109491109492109493109494109495109496109497109498109499109500109501109502109503109504109505109506109507109508109509109510109511109512109513109514109515109516109517109518109519109520109521109522109523109524109525109526109527109528109529109530109531109532109533109534109535109536109537109538109539109540109541109542109543109544109545109546109547109548109549109550109551109552109553109554109555109556109557109558109559109560109561109562109563109564109565109566109567109568109569109570109571109572109573109574109575109576109577109578109579109580109581109582109583109584109585109586109587109588109589109590109591109592109593109594109595109596109597109598109599109600109601109602109603109604109605109606109607109608109609109610109611109612109613109614109615109616109617109618109619109620109621109622109623109624109625109626109627109628109629109630109631109632109633109634109635109636109637109638109639109640109641109642109643109644109645109646109647109648109649109650109651109652109653109654109655109656109657109658109659109660109661109662109663109664109665109666109667109668109669109670109671109672109673109674109675109676109677109678109679109680109681109682109683109684109685109686109687109688109689109690109691109692109693109694109695109696109697109698109699109700109701109702109703109704109705109706109707109708109709109710109711109712109713109714109715109716109717109718109719109720109721109722109723109724109725109726109727109728109729109730109731109732109733109734109735109736109737109738109739109740109741109742109743109744109745109746109747109748109749109750109751109752109753109754109755109756109757109758109759109760109761109762109763109764109765109766109767109768109769109770109771109772109773109774109775109776109777109778109779109780109781109782109783109784109785109786109787109788109789109790109791109792109793109794109795109796109797109798109799109800109801109802109803109804109805109806109807109808109809109810109811109812109813109814109815109816109817109818109819109820109821109822109823109824109825109826109827109828109829109830109831109832109833109834109835109836109837109838109839109840109841109842109843109844109845109846109847109848109849109850109851109852109853109854109855109856109857109858109859109860109861109862109863109864109865109866109867109868109869109870109871109872109873109874109875109876109877109878109879109880109881109882109883109884109885109886109887109888109889109890109891109892109893109894109895109896109897109898109899109900109901109902109903109904109905109906109907109908109909109910109911109912109913109914109915109916109917109918109919109920109921109922109923109924109925109926109927109928109929109930109931109932109933109934109935109936109937109938109939109940109941109942109943109944109945109946109947109948109949109950109951109952109953109954109955109956109957109958109959109960109961109962109963109964109965109966109967109968109969109970109971109972109973109974109975109976109977109978109979109980109981109982109983109984109985109986109987109988109989109990109991109992109993109994109995109996109997109998109999110000110001110002110003110004110005110006110007110008110009110010110011110012110013110014110015110016110017110018110019110020110021110022110023110024110025110026110027110028110029110030110031110032110033110034110035110036110037110038110039110040110041110042110043110044110045110046110047110048110049110050110051110052110053110054110055110056110057110058110059110060110061110062110063110064110065110066110067110068110069110070110071110072110073110074110075110076110077110078110079110080110081110082110083110084110085110086110087110088110089110090110091110092110093110094110095110096110097110098110099110100110101110102110103110104110105110106110107110108110109110110110111110112110113110114110115110116110117110118110119110120110121110122110123110124110125110126110127110128110129110130110131110132110133110134110135110136110137110138110139110140110141110142110143110144110145110146110147110148110149110150110151110152110153110154110155110156110157110158110159110160110161110162110163110164110165110166110167110168110169110170110171110172110173110174110175110176110177110178110179110180110181110182110183110184110185110186110187110188110189110190110191110192110193110194110195110196110197110198110199110200110201110202110203110204110205110206110207110208110209110210110211110212110213110214110215110216110217110218110219110220110221110222110223110224110225110226110227110228110229110230110231110232110233110234110235110236110237110238110239110240110241110242110243110244110245110246110247110248110249110250110251110252110253110254110255110256110257110258110259110260110261110262110263110264110265110266110267110268110269110270110271110272110273110274110275110276110277110278110279110280110281110282110283110284110285110286110287110288110289110290110291110292110293110294110295110296110297110298110299110300110301110302110303110304110305110306110307110308110309110310110311110312110313110314110315110316110317110318110319110320110321110322110323110324110325110326110327110328110329110330110331110332110333110334110335110336110337110338110339110340110341110342110343110344110345110346110347110348110349110350110351110352110353110354110355110356110357110358110359110360110361110362110363110364110365110366110367110368110369110370110371110372110373110374110375110376110377110378110379110380110381110382110383110384110385110386110387110388110389110390110391110392110393110394110395110396110397110398110399110400110401110402110403110404110405110406110407110408110409110410110411110412110413110414110415110416110417110418110419110420110421110422110423110424110425110426110427110428110429110430110431110432110433110434110435110436110437110438110439110440110441110442110443110444110445110446110447110448110449110450110451110452110453110454110455110456110457110458110459110460110461110462110463110464110465110466110467110468110469110470110471110472110473110474110475110476110477110478110479110480110481110482110483110484110485110486110487110488110489110490110491110492110493110494110495110496110497110498110499110500110501110502110503110504110505110506110507110508110509110510110511110512110513110514110515110516110517110518110519110520110521110522110523110524110525110526110527110528110529110530110531110532110533110534110535110536110537110538110539110540110541110542110543110544110545110546110547110548110549110550110551110552110553110554110555110556110557110558110559110560110561110562110563110564110565110566110567110568110569110570110571110572110573110574110575110576110577110578110579110580110581110582110583110584110585110586110587110588110589110590110591110592110593110594110595110596110597110598110599110600110601110602110603110604110605110606110607110608110609110610110611110612110613110614110615110616110617110618110619110620110621110622110623110624110625110626110627110628110629110630110631110632110633110634110635110636110637110638110639110640110641110642110643110644110645110646110647110648110649110650110651110652110653110654110655110656110657110658110659110660110661110662110663110664110665110666110667110668110669110670110671110672110673110674110675110676110677110678110679110680110681110682110683110684110685110686110687110688110689110690110691110692110693110694110695110696110697110698110699110700110701110702110703110704110705110706110707110708110709110710110711110712110713110714110715110716110717110718110719110720110721110722110723110724110725110726110727110728110729110730110731110732110733110734110735110736110737110738110739110740110741110742110743110744110745110746110747110748110749110750110751110752110753110754110755110756110757110758110759110760110761110762110763110764110765110766110767110768110769110770110771110772110773110774110775110776110777110778110779110780110781110782110783110784110785110786110787110788110789110790110791110792110793110794110795110796110797110798110799110800110801110802110803110804110805110806110807110808110809110810110811110812110813110814110815110816110817110818110819110820110821110822110823110824110825110826110827110828110829110830110831110832110833110834110835110836110837110838110839110840110841110842110843110844110845110846110847110848110849110850110851110852110853110854110855110856110857110858110859110860110861110862110863110864110865110866110867110868110869110870110871110872110873110874110875110876110877110878110879110880110881110882110883110884110885110886110887110888110889110890110891110892110893110894110895110896110897110898110899110900110901110902110903110904110905110906110907110908110909110910110911110912110913110914110915110916110917110918110919110920110921110922110923110924110925110926110927110928110929110930110931110932110933110934110935110936110937110938110939110940110941110942110943110944110945110946110947110948110949110950110951110952110953110954110955110956110957110958110959110960110961110962110963110964110965110966110967110968110969110970110971110972110973110974110975110976110977110978110979110980110981110982110983110984110985110986110987110988110989110990110991110992110993110994110995110996110997110998110999111000111001111002111003111004111005111006111007111008111009111010111011111012111013111014111015111016111017111018111019111020111021111022111023111024111025111026111027111028111029111030111031111032111033111034111035111036111037111038111039111040111041111042111043111044111045111046111047111048111049111050111051111052111053111054111055111056111057111058111059111060111061111062111063111064111065111066111067111068111069111070111071111072111073111074111075111076111077111078111079111080111081111082111083111084111085111086111087111088111089111090111091111092111093111094111095111096111097111098111099111100111101111102111103111104111105111106111107111108111109111110111111111112111113111114111115111116111117111118111119111120111121111122111123111124111125111126111127111128111129111130111131111132111133111134111135111136111137111138111139111140111141111142111143111144111145111146111147111148111149111150111151111152111153111154111155111156111157111158111159111160111161111162111163111164111165111166111167111168111169111170111171111172111173111174111175111176111177111178111179111180111181111182111183111184111185111186111187111188111189111190111191111192111193111194111195111196111197111198111199111200111201111202111203111204111205111206111207111208111209111210111211111212111213111214111215111216111217111218111219111220111221111222111223111224111225111226111227111228111229111230111231111232111233111234111235111236111237111238111239111240111241111242111243111244111245111246111247111248111249111250111251111252111253111254111255111256111257111258111259111260111261111262111263111264111265111266111267111268111269111270111271111272111273111274111275111276111277111278111279111280111281111282111283111284111285111286111287111288111289111290111291111292111293111294111295111296111297111298111299111300111301111302111303111304111305111306111307111308111309111310111311111312111313111314111315111316111317111318111319111320111321111322111323111324111325111326111327111328111329111330111331111332111333111334111335111336111337111338111339111340111341111342111343111344111345111346111347111348111349111350111351111352111353111354111355111356111357111358111359111360111361111362111363111364111365111366111367111368111369111370111371111372111373111374111375111376111377111378111379111380111381111382111383111384111385111386111387111388111389111390111391111392111393111394111395111396111397111398111399111400111401111402111403111404111405111406111407111408111409111410111411111412111413111414111415111416111417111418111419111420111421111422111423111424111425111426111427111428111429111430111431111432111433111434111435111436111437111438111439111440111441111442111443111444111445111446111447111448111449111450111451111452111453111454111455111456111457111458111459111460111461111462111463111464111465111466111467111468111469111470111471111472111473111474111475111476111477111478111479111480111481111482111483111484111485111486111487111488111489111490111491111492111493111494111495111496111497111498111499111500111501111502111503111504111505111506111507111508111509111510111511111512111513111514111515111516111517111518111519111520111521111522111523111524111525111526111527111528111529111530111531111532111533111534111535111536111537111538111539111540111541111542111543111544111545111546111547111548111549111550111551111552111553111554111555111556111557111558111559111560111561111562111563111564111565111566111567111568111569111570111571111572111573111574111575111576111577111578111579111580111581111582111583111584111585111586111587111588111589111590111591111592111593111594111595111596111597111598111599111600111601111602111603111604111605111606111607111608111609111610111611111612111613111614111615111616111617111618111619111620111621111622111623111624111625111626111627111628111629111630111631111632111633111634111635111636111637111638111639111640111641111642111643111644111645111646111647111648111649111650111651111652111653111654111655111656111657111658111659111660111661111662111663111664111665111666111667111668111669111670111671111672111673111674111675111676111677111678111679111680111681111682111683111684111685111686111687111688111689111690111691111692111693111694111695111696111697111698111699111700111701111702111703111704111705111706111707111708111709111710111711111712111713111714111715111716111717111718111719111720111721111722111723111724111725111726111727111728111729111730111731111732111733111734111735111736111737111738111739111740111741111742111743111744111745111746111747111748111749111750111751111752111753111754111755111756111757111758111759111760111761111762111763111764111765111766111767111768111769111770111771111772111773111774111775111776111777111778111779111780111781111782111783111784111785111786111787111788111789111790111791111792111793111794111795111796111797111798111799111800111801111802111803111804111805111806111807111808111809111810111811111812111813111814111815111816111817111818111819111820111821111822111823111824111825111826111827111828111829111830111831111832111833111834111835111836111837111838111839111840111841111842111843111844111845111846111847111848111849111850111851111852111853111854111855111856111857111858111859111860111861111862111863111864111865111866111867111868111869111870111871111872111873111874111875111876111877111878111879111880111881111882111883111884111885111886111887111888111889111890111891111892111893111894111895111896111897111898111899111900111901111902111903111904111905111906111907111908111909111910111911111912111913111914111915111916111917111918111919111920111921111922111923111924111925111926111927111928111929111930111931111932111933111934111935111936111937111938111939111940111941111942111943111944111945111946111947111948111949111950111951111952111953111954111955111956111957111958111959111960111961111962111963111964111965111966111967111968111969111970111971111972111973111974111975111976111977111978111979111980111981111982111983111984111985111986111987111988111989111990111991111992111993111994111995111996111997111998111999112000112001112002112003112004112005112006112007112008112009112010112011112012112013112014112015112016112017112018112019112020112021112022112023112024112025112026112027112028112029112030112031112032112033112034112035112036112037112038112039112040112041112042112043112044112045112046112047112048112049112050112051112052112053112054112055112056112057112058112059112060112061112062112063112064112065112066112067112068112069112070112071112072112073112074112075112076112077112078112079112080112081112082112083112084112085112086112087112088112089112090112091112092112093112094112095112096112097112098112099112100112101112102112103112104112105112106112107112108112109112110112111112112112113112114112115112116112117112118112119112120112121112122112123112124112125112126112127112128112129112130112131112132112133112134112135112136112137112138112139112140112141112142112143112144112145112146112147112148112149112150112151112152112153112154112155112156112157112158112159112160112161112162112163112164112165112166112167112168112169112170112171112172112173112174112175112176112177112178112179112180112181112182112183112184112185112186112187112188112189112190112191112192112193112194112195112196112197112198112199112200112201112202112203112204112205112206112207112208112209112210112211112212112213112214112215112216112217112218112219112220112221112222112223112224112225112226112227112228112229112230112231112232112233112234112235112236112237112238112239112240112241112242112243112244112245112246112247112248112249112250112251112252112253112254112255112256112257112258112259112260112261112262112263112264112265112266112267112268112269112270112271112272112273112274112275112276112277112278112279112280112281112282112283112284112285112286112287112288112289112290112291112292112293112294112295112296112297112298112299112300112301112302112303112304112305112306112307112308112309112310112311112312112313112314112315112316112317112318112319112320112321112322112323112324112325112326112327112328112329112330112331112332112333112334112335112336112337112338112339112340112341112342112343112344112345112346112347112348112349112350112351112352112353112354112355112356112357112358112359112360112361112362112363112364112365112366112367112368112369112370112371112372112373112374112375112376112377112378112379112380112381112382112383112384112385112386112387112388112389112390112391112392112393112394112395112396112397112398112399112400112401112402112403112404112405112406112407112408112409112410112411112412112413112414112415112416112417112418112419112420112421112422112423112424112425112426112427112428112429112430112431112432112433112434112435112436112437112438112439112440112441112442112443112444112445112446112447112448112449112450112451112452112453112454112455112456112457112458112459112460112461112462112463112464112465112466112467112468112469112470112471112472112473112474112475112476112477112478112479112480112481112482112483112484112485112486112487112488112489112490112491112492112493112494112495112496112497112498112499112500112501112502112503112504112505112506112507112508112509112510112511112512112513112514112515112516112517112518112519112520112521112522112523112524112525112526112527112528112529112530112531112532112533112534112535112536112537112538112539112540112541112542112543112544112545112546112547112548112549112550112551112552112553112554112555112556112557112558112559112560112561112562112563112564112565112566112567112568112569112570112571112572112573112574112575112576112577112578112579112580112581112582112583112584112585112586112587112588112589112590112591112592112593112594112595112596112597112598112599112600112601112602112603112604112605112606112607112608112609112610112611112612112613112614112615112616112617112618112619112620112621112622112623112624112625112626112627112628112629112630112631112632112633112634112635112636112637112638112639112640112641112642112643112644112645112646112647112648112649112650112651112652112653112654112655112656112657112658112659112660112661112662112663112664112665112666112667112668112669112670112671112672112673112674112675112676112677112678112679112680112681112682112683112684112685112686112687112688112689112690112691112692112693112694112695112696112697112698112699112700112701112702112703112704112705112706112707112708112709112710112711112712112713112714112715112716112717112718112719112720112721112722112723112724112725112726112727112728112729112730112731112732112733112734112735112736112737112738112739112740112741112742112743112744112745112746112747112748112749112750112751112752112753112754112755112756112757112758112759112760112761112762112763112764112765112766112767112768112769112770112771112772112773112774112775112776112777112778112779112780112781112782112783112784112785112786112787112788112789112790112791112792112793112794112795112796112797112798112799112800112801112802112803112804112805112806112807112808112809112810112811112812112813112814112815112816112817112818112819112820112821112822112823112824112825112826112827112828112829112830112831112832112833112834112835112836112837112838112839112840112841112842112843
  1. (function universalModuleDefinition(root, factory) {
  2. if(typeof exports === 'object' && typeof module === 'object')
  3. module.exports = factory();
  4. else if(typeof define === 'function' && define.amd)
  5. define("babylonjs-viewer", [], factory);
  6. else if(typeof exports === 'object')
  7. exports["babylonjs-viewer"] = factory();
  8. else {
  9. root["BabylonViewer"] = factory(root["BABYLON"]);
  10. }
  11. })(this, function() {
  12. var BabylonViewer =
  13. /******/ (function(modules) { // webpackBootstrap
  14. /******/ // The module cache
  15. /******/ var installedModules = {};
  16. /******/
  17. /******/ // The require function
  18. /******/ function __webpack_require__(moduleId) {
  19. /******/
  20. /******/ // Check if module is in cache
  21. /******/ if(installedModules[moduleId]) {
  22. /******/ return installedModules[moduleId].exports;
  23. /******/ }
  24. /******/ // Create a new module (and put it into the cache)
  25. /******/ var module = installedModules[moduleId] = {
  26. /******/ i: moduleId,
  27. /******/ l: false,
  28. /******/ exports: {}
  29. /******/ };
  30. /******/
  31. /******/ // Execute the module function
  32. /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
  33. /******/
  34. /******/ // Flag the module as loaded
  35. /******/ module.l = true;
  36. /******/
  37. /******/ // Return the exports of the module
  38. /******/ return module.exports;
  39. /******/ }
  40. /******/
  41. /******/
  42. /******/ // expose the modules object (__webpack_modules__)
  43. /******/ __webpack_require__.m = modules;
  44. /******/
  45. /******/ // expose the module cache
  46. /******/ __webpack_require__.c = installedModules;
  47. /******/
  48. /******/ // define getter function for harmony exports
  49. /******/ __webpack_require__.d = function(exports, name, getter) {
  50. /******/ if(!__webpack_require__.o(exports, name)) {
  51. /******/ Object.defineProperty(exports, name, {
  52. /******/ configurable: false,
  53. /******/ enumerable: true,
  54. /******/ get: getter
  55. /******/ });
  56. /******/ }
  57. /******/ };
  58. /******/
  59. /******/ // getDefaultExport function for compatibility with non-harmony modules
  60. /******/ __webpack_require__.n = function(module) {
  61. /******/ var getter = module && module.__esModule ?
  62. /******/ function getDefault() { return module['default']; } :
  63. /******/ function getModuleExports() { return module; };
  64. /******/ __webpack_require__.d(getter, 'a', getter);
  65. /******/ return getter;
  66. /******/ };
  67. /******/
  68. /******/ // Object.prototype.hasOwnProperty.call
  69. /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
  70. /******/
  71. /******/ // __webpack_public_path__
  72. /******/ __webpack_require__.p = "";
  73. /******/
  74. /******/ // Load entry module and return exports
  75. /******/ return __webpack_require__(__webpack_require__.s = 14);
  76. /******/ })
  77. /************************************************************************/
  78. /******/ ([
  79. /* 0 */
  80. /***/ (function(module, exports, __webpack_require__) {
  81. /* WEBPACK VAR INJECTION */(function(global) {var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  82. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  83. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  84. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  85. return c > 3 && r && Object.defineProperty(target, key, r), r;
  86. };
  87. var __extends = (this && this.__extends) || (function () {
  88. var extendStatics = Object.setPrototypeOf ||
  89. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  90. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  91. return function (d, b) {
  92. extendStatics(d, b);
  93. function __() { this.constructor = d; }
  94. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  95. };
  96. })();
  97. (function universalModuleDefinition(root, factory) {
  98. if(true)
  99. module.exports = factory();
  100. else if(typeof define === 'function' && define.amd)
  101. define("babylonjs", [], factory);
  102. else if(typeof exports === 'object')
  103. exports["babylonjs"] = factory();
  104. else {
  105. root["BABYLON"] = factory(root["BABYLON"]);
  106. }
  107. })(this, function() {
  108. var BABYLON;
  109. (function (BABYLON) {
  110. /**
  111. * EffectFallbacks can be used to add fallbacks (properties to disable) to certain properties when desired to improve performance.
  112. * (Eg. Start at high quality with reflection and fog, if fps is low, remove reflection, if still low remove fog)
  113. */
  114. var EffectFallbacks = /** @class */ (function () {
  115. function EffectFallbacks() {
  116. this._defines = {};
  117. this._currentRank = 32;
  118. this._maxRank = -1;
  119. }
  120. /**
  121. * Removes the fallback from the bound mesh.
  122. */
  123. EffectFallbacks.prototype.unBindMesh = function () {
  124. this._mesh = null;
  125. };
  126. /**
  127. * Adds a fallback on the specified property.
  128. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  129. * @param define The name of the define in the shader
  130. */
  131. EffectFallbacks.prototype.addFallback = function (rank, define) {
  132. if (!this._defines[rank]) {
  133. if (rank < this._currentRank) {
  134. this._currentRank = rank;
  135. }
  136. if (rank > this._maxRank) {
  137. this._maxRank = rank;
  138. }
  139. this._defines[rank] = new Array();
  140. }
  141. this._defines[rank].push(define);
  142. };
  143. /**
  144. * Sets the mesh to use CPU skinning when needing to fallback.
  145. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  146. * @param mesh The mesh to use the fallbacks.
  147. */
  148. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  149. this._mesh = mesh;
  150. if (rank < this._currentRank) {
  151. this._currentRank = rank;
  152. }
  153. if (rank > this._maxRank) {
  154. this._maxRank = rank;
  155. }
  156. };
  157. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  158. /**
  159. * Checks to see if more fallbacks are still availible.
  160. */
  161. get: function () {
  162. return this._currentRank <= this._maxRank;
  163. },
  164. enumerable: true,
  165. configurable: true
  166. });
  167. /**
  168. * Removes the defines that shoould be removed when falling back.
  169. * @param currentDefines defines the current define statements for the shader.
  170. * @param effect defines the current effect we try to compile
  171. * @returns The resulting defines with defines of the current rank removed.
  172. */
  173. EffectFallbacks.prototype.reduce = function (currentDefines, effect) {
  174. // First we try to switch to CPU skinning
  175. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0 && this._mesh.material) {
  176. this._mesh.computeBonesUsingShaders = false;
  177. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  178. var scene = this._mesh.getScene();
  179. for (var index = 0; index < scene.meshes.length; index++) {
  180. var otherMesh = scene.meshes[index];
  181. if (!otherMesh.material) {
  182. continue;
  183. }
  184. if (!otherMesh.computeBonesUsingShaders || otherMesh.numBoneInfluencers === 0) {
  185. continue;
  186. }
  187. if (otherMesh.material.getEffect() === effect) {
  188. otherMesh.computeBonesUsingShaders = false;
  189. }
  190. else {
  191. for (var _i = 0, _a = otherMesh.subMeshes; _i < _a.length; _i++) {
  192. var subMesh = _a[_i];
  193. var subMeshEffect = subMesh.effect;
  194. if (subMeshEffect === effect) {
  195. otherMesh.computeBonesUsingShaders = false;
  196. break;
  197. }
  198. }
  199. }
  200. }
  201. }
  202. else {
  203. var currentFallbacks = this._defines[this._currentRank];
  204. if (currentFallbacks) {
  205. for (var index = 0; index < currentFallbacks.length; index++) {
  206. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  207. }
  208. }
  209. this._currentRank++;
  210. }
  211. return currentDefines;
  212. };
  213. return EffectFallbacks;
  214. }());
  215. BABYLON.EffectFallbacks = EffectFallbacks;
  216. /**
  217. * Options to be used when creating an effect.
  218. */
  219. var EffectCreationOptions = /** @class */ (function () {
  220. function EffectCreationOptions() {
  221. }
  222. return EffectCreationOptions;
  223. }());
  224. BABYLON.EffectCreationOptions = EffectCreationOptions;
  225. /**
  226. * Effect containing vertex and fragment shader that can be executed on an object.
  227. */
  228. var Effect = /** @class */ (function () {
  229. /**
  230. * Instantiates an effect.
  231. * An effect can be used to create/manage/execute vertex and fragment shaders.
  232. * @param baseName Name of the effect.
  233. * @param attributesNamesOrOptions List of attribute names that will be passed to the shader or set of all options to create the effect.
  234. * @param uniformsNamesOrEngine List of uniform variable names that will be passed to the shader or the engine that will be used to render effect.
  235. * @param samplers List of sampler variables that will be passed to the shader.
  236. * @param engine Engine to be used to render the effect
  237. * @param defines Define statements to be added to the shader.
  238. * @param fallbacks Possible fallbacks for this effect to improve performance when needed.
  239. * @param onCompiled Callback that will be called when the shader is compiled.
  240. * @param onError Callback that will be called if an error occurs during shader compilation.
  241. * @param indexParameters Parameters to be used with Babylons include syntax to iterate over an array (eg. {lights: 10})
  242. */
  243. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  244. if (samplers === void 0) { samplers = null; }
  245. if (defines === void 0) { defines = null; }
  246. if (fallbacks === void 0) { fallbacks = null; }
  247. if (onCompiled === void 0) { onCompiled = null; }
  248. if (onError === void 0) { onError = null; }
  249. var _this = this;
  250. /**
  251. * Unique ID of the effect.
  252. */
  253. this.uniqueId = 0;
  254. /**
  255. * Observable that will be called when the shader is compiled.
  256. */
  257. this.onCompileObservable = new BABYLON.Observable();
  258. /**
  259. * Observable that will be called if an error occurs during shader compilation.
  260. */
  261. this.onErrorObservable = new BABYLON.Observable();
  262. /**
  263. * Observable that will be called when effect is bound.
  264. */
  265. this.onBindObservable = new BABYLON.Observable();
  266. this._uniformBuffersNames = {};
  267. this._isReady = false;
  268. this._compilationError = "";
  269. this.name = baseName;
  270. if (attributesNamesOrOptions.attributes) {
  271. var options = attributesNamesOrOptions;
  272. this._engine = uniformsNamesOrEngine;
  273. this._attributesNames = options.attributes;
  274. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  275. this._samplers = options.samplers;
  276. this.defines = options.defines;
  277. this.onError = options.onError;
  278. this.onCompiled = options.onCompiled;
  279. this._fallbacks = options.fallbacks;
  280. this._indexParameters = options.indexParameters;
  281. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  282. if (options.uniformBuffersNames) {
  283. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  284. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  285. }
  286. }
  287. }
  288. else {
  289. this._engine = engine;
  290. this.defines = defines;
  291. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  292. this._samplers = samplers;
  293. this._attributesNames = attributesNamesOrOptions;
  294. this.onError = onError;
  295. this.onCompiled = onCompiled;
  296. this._indexParameters = indexParameters;
  297. this._fallbacks = fallbacks;
  298. }
  299. this.uniqueId = Effect._uniqueIdSeed++;
  300. if (this._getFromCache(baseName)) {
  301. this._prepareEffect();
  302. return;
  303. }
  304. var vertexSource;
  305. var fragmentSource;
  306. if (baseName.vertexElement) {
  307. vertexSource = document.getElementById(baseName.vertexElement);
  308. if (!vertexSource) {
  309. vertexSource = baseName.vertexElement;
  310. }
  311. }
  312. else {
  313. vertexSource = baseName.vertex || baseName;
  314. }
  315. if (baseName.fragmentElement) {
  316. fragmentSource = document.getElementById(baseName.fragmentElement);
  317. if (!fragmentSource) {
  318. fragmentSource = baseName.fragmentElement;
  319. }
  320. }
  321. else {
  322. fragmentSource = baseName.fragment || baseName;
  323. }
  324. var finalVertexCode;
  325. this._loadVertexShaderAsync(vertexSource)
  326. .then(function (vertexCode) {
  327. return _this._processIncludesAsync(vertexCode);
  328. })
  329. .then(function (vertexCodeWithIncludes) {
  330. finalVertexCode = _this._processShaderConversion(vertexCodeWithIncludes, false);
  331. return _this._loadFragmentShaderAsync(fragmentSource);
  332. })
  333. .then(function (fragmentCode) {
  334. return _this._processIncludesAsync(fragmentCode);
  335. })
  336. .then(function (fragmentCodeWithIncludes) {
  337. var migratedFragmentCode = _this._processShaderConversion(fragmentCodeWithIncludes, true);
  338. if (baseName) {
  339. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  340. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  341. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + finalVertexCode;
  342. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  343. }
  344. else {
  345. _this._vertexSourceCode = finalVertexCode;
  346. _this._fragmentSourceCode = migratedFragmentCode;
  347. }
  348. _this._setInCache(baseName);
  349. _this._prepareEffect();
  350. });
  351. }
  352. Effect.prototype._getSourceCacheKey = function (baseName) {
  353. var cacheKey = baseName;
  354. if (this._indexParameters) {
  355. for (var key in this._indexParameters) {
  356. if (this._indexParameters.hasOwnProperty(key)) {
  357. cacheKey += "|";
  358. cacheKey += key;
  359. cacheKey += "_";
  360. cacheKey += this._indexParameters[key];
  361. }
  362. }
  363. }
  364. return cacheKey;
  365. };
  366. Effect.prototype._getFromCache = function (baseName) {
  367. if (typeof baseName !== "string") {
  368. return false;
  369. }
  370. var cacheKey = this._getSourceCacheKey(baseName);
  371. var sources = Effect._sourceCache[cacheKey];
  372. if (!sources) {
  373. return false;
  374. }
  375. this._vertexSourceCode = sources.vertex;
  376. this._fragmentSourceCode = sources.fragment;
  377. return true;
  378. };
  379. Effect.prototype._setInCache = function (baseName) {
  380. if (typeof baseName !== "string") {
  381. return;
  382. }
  383. var cacheKey = this._getSourceCacheKey(baseName);
  384. Effect._sourceCache[cacheKey] = {
  385. vertex: this._vertexSourceCode,
  386. fragment: this._fragmentSourceCode
  387. };
  388. };
  389. Object.defineProperty(Effect.prototype, "key", {
  390. /**
  391. * Unique key for this effect
  392. */
  393. get: function () {
  394. return this._key;
  395. },
  396. enumerable: true,
  397. configurable: true
  398. });
  399. /**
  400. * If the effect has been compiled and prepared.
  401. * @returns if the effect is compiled and prepared.
  402. */
  403. Effect.prototype.isReady = function () {
  404. return this._isReady;
  405. };
  406. /**
  407. * The engine the effect was initialized with.
  408. * @returns the engine.
  409. */
  410. Effect.prototype.getEngine = function () {
  411. return this._engine;
  412. };
  413. /**
  414. * The compiled webGL program for the effect
  415. * @returns the webGL program.
  416. */
  417. Effect.prototype.getProgram = function () {
  418. return this._program;
  419. };
  420. /**
  421. * The set of names of attribute variables for the shader.
  422. * @returns An array of attribute names.
  423. */
  424. Effect.prototype.getAttributesNames = function () {
  425. return this._attributesNames;
  426. };
  427. /**
  428. * Returns the attribute at the given index.
  429. * @param index The index of the attribute.
  430. * @returns The location of the attribute.
  431. */
  432. Effect.prototype.getAttributeLocation = function (index) {
  433. return this._attributes[index];
  434. };
  435. /**
  436. * Returns the attribute based on the name of the variable.
  437. * @param name of the attribute to look up.
  438. * @returns the attribute location.
  439. */
  440. Effect.prototype.getAttributeLocationByName = function (name) {
  441. var index = this._attributesNames.indexOf(name);
  442. return this._attributes[index];
  443. };
  444. /**
  445. * The number of attributes.
  446. * @returns the numnber of attributes.
  447. */
  448. Effect.prototype.getAttributesCount = function () {
  449. return this._attributes.length;
  450. };
  451. /**
  452. * Gets the index of a uniform variable.
  453. * @param uniformName of the uniform to look up.
  454. * @returns the index.
  455. */
  456. Effect.prototype.getUniformIndex = function (uniformName) {
  457. return this._uniformsNames.indexOf(uniformName);
  458. };
  459. /**
  460. * Returns the attribute based on the name of the variable.
  461. * @param uniformName of the uniform to look up.
  462. * @returns the location of the uniform.
  463. */
  464. Effect.prototype.getUniform = function (uniformName) {
  465. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  466. };
  467. /**
  468. * Returns an array of sampler variable names
  469. * @returns The array of sampler variable neames.
  470. */
  471. Effect.prototype.getSamplers = function () {
  472. return this._samplers;
  473. };
  474. /**
  475. * The error from the last compilation.
  476. * @returns the error string.
  477. */
  478. Effect.prototype.getCompilationError = function () {
  479. return this._compilationError;
  480. };
  481. /**
  482. * Adds a callback to the onCompiled observable and call the callback imediatly if already ready.
  483. * @param func The callback to be used.
  484. */
  485. Effect.prototype.executeWhenCompiled = function (func) {
  486. if (this.isReady()) {
  487. func(this);
  488. return;
  489. }
  490. this.onCompileObservable.add(function (effect) {
  491. func(effect);
  492. });
  493. };
  494. /** @ignore */
  495. Effect.prototype._loadVertexShaderAsync = function (vertex) {
  496. if (BABYLON.Tools.IsWindowObjectExist()) {
  497. // DOM element ?
  498. if (vertex instanceof HTMLElement) {
  499. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  500. return Promise.resolve(vertexCode);
  501. }
  502. }
  503. // Base64 encoded ?
  504. if (vertex.substr(0, 7) === "base64:") {
  505. var vertexBinary = window.atob(vertex.substr(7));
  506. return Promise.resolve(vertexBinary);
  507. }
  508. // Is in local store ?
  509. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  510. return Promise.resolve(Effect.ShadersStore[vertex + "VertexShader"]);
  511. }
  512. var vertexShaderUrl;
  513. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  514. vertexShaderUrl = vertex;
  515. }
  516. else {
  517. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  518. }
  519. // Vertex shader
  520. return this._engine._loadFileAsync(vertexShaderUrl + ".vertex.fx");
  521. };
  522. /** @ignore */
  523. Effect.prototype._loadFragmentShaderAsync = function (fragment) {
  524. if (BABYLON.Tools.IsWindowObjectExist()) {
  525. // DOM element ?
  526. if (fragment instanceof HTMLElement) {
  527. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  528. return Promise.resolve(fragmentCode);
  529. }
  530. }
  531. // Base64 encoded ?
  532. if (fragment.substr(0, 7) === "base64:") {
  533. var fragmentBinary = window.atob(fragment.substr(7));
  534. return Promise.resolve(fragmentBinary);
  535. }
  536. // Is in local store ?
  537. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  538. return Promise.resolve(Effect.ShadersStore[fragment + "PixelShader"]);
  539. }
  540. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  541. return Promise.resolve(Effect.ShadersStore[fragment + "FragmentShader"]);
  542. }
  543. var fragmentShaderUrl;
  544. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  545. fragmentShaderUrl = fragment;
  546. }
  547. else {
  548. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  549. }
  550. // Fragment shader
  551. return this._engine._loadFileAsync(fragmentShaderUrl + ".fragment.fx");
  552. };
  553. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  554. // Rebuild shaders source code
  555. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n" : "";
  556. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  557. vertexCode = prefix + vertexCode;
  558. fragmentCode = prefix + fragmentCode;
  559. // Number lines of shaders source code
  560. var i = 2;
  561. var regex = /\n/gm;
  562. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  563. i = 2;
  564. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  565. // Dump shaders name and formatted source code
  566. if (this.name.vertexElement) {
  567. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  568. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  569. }
  570. else if (this.name.vertex) {
  571. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  572. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  573. }
  574. else {
  575. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  576. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  577. }
  578. };
  579. ;
  580. Effect.prototype._processShaderConversion = function (sourceCode, isFragment) {
  581. var preparedSourceCode = this._processPrecision(sourceCode);
  582. if (this._engine.webGLVersion == 1) {
  583. return preparedSourceCode;
  584. }
  585. // Already converted
  586. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  587. return preparedSourceCode.replace("#version 300 es", "");
  588. }
  589. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  590. // Remove extensions
  591. // #extension GL_OES_standard_derivatives : enable
  592. // #extension GL_EXT_shader_texture_lod : enable
  593. // #extension GL_EXT_frag_depth : enable
  594. // #extension GL_EXT_draw_buffers : require
  595. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  596. var result = preparedSourceCode.replace(regex, "");
  597. // Migrate to GLSL v300
  598. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  599. result = result.replace(/attribute[ \t]/g, "in ");
  600. result = result.replace(/[ \t]attribute/g, " in");
  601. if (isFragment) {
  602. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  603. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  604. result = result.replace(/texture2D\s*\(/g, "texture(");
  605. result = result.replace(/textureCube\s*\(/g, "texture(");
  606. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  607. result = result.replace(/gl_FragColor/g, "glFragColor");
  608. result = result.replace(/gl_FragData/g, "glFragData");
  609. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  610. }
  611. return result;
  612. };
  613. Effect.prototype._processIncludesAsync = function (sourceCode) {
  614. var _this = this;
  615. return new Promise(function (resolve, reject) {
  616. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  617. var match = regex.exec(sourceCode);
  618. var returnValue = sourceCode;
  619. while (match != null) {
  620. var includeFile = match[1];
  621. // Uniform declaration
  622. if (includeFile.indexOf("__decl__") !== -1) {
  623. includeFile = includeFile.replace(/__decl__/, "");
  624. if (_this._engine.supportsUniformBuffers) {
  625. includeFile = includeFile.replace(/Vertex/, "Ubo");
  626. includeFile = includeFile.replace(/Fragment/, "Ubo");
  627. }
  628. includeFile = includeFile + "Declaration";
  629. }
  630. if (Effect.IncludesShadersStore[includeFile]) {
  631. // Substitution
  632. var includeContent = Effect.IncludesShadersStore[includeFile];
  633. if (match[2]) {
  634. var splits = match[3].split(",");
  635. for (var index = 0; index < splits.length; index += 2) {
  636. var source = new RegExp(splits[index], "g");
  637. var dest = splits[index + 1];
  638. includeContent = includeContent.replace(source, dest);
  639. }
  640. }
  641. if (match[4]) {
  642. var indexString = match[5];
  643. if (indexString.indexOf("..") !== -1) {
  644. var indexSplits = indexString.split("..");
  645. var minIndex = parseInt(indexSplits[0]);
  646. var maxIndex = parseInt(indexSplits[1]);
  647. var sourceIncludeContent = includeContent.slice(0);
  648. includeContent = "";
  649. if (isNaN(maxIndex)) {
  650. maxIndex = _this._indexParameters[indexSplits[1]];
  651. }
  652. for (var i = minIndex; i < maxIndex; i++) {
  653. if (!_this._engine.supportsUniformBuffers) {
  654. // Ubo replacement
  655. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  656. return p1 + "{X}";
  657. });
  658. }
  659. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  660. }
  661. }
  662. else {
  663. if (!_this._engine.supportsUniformBuffers) {
  664. // Ubo replacement
  665. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  666. return p1 + "{X}";
  667. });
  668. }
  669. includeContent = includeContent.replace(/\{X\}/g, indexString);
  670. }
  671. }
  672. // Replace
  673. returnValue = returnValue.replace(match[0], includeContent);
  674. }
  675. else {
  676. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  677. _this._engine._loadFileAsync(includeShaderUrl)
  678. .then(function (fileContent) {
  679. Effect.IncludesShadersStore[includeFile] = fileContent;
  680. return _this._processIncludesAsync(returnValue);
  681. })
  682. .then(function (returnValue) {
  683. resolve(returnValue);
  684. });
  685. return;
  686. }
  687. match = regex.exec(sourceCode);
  688. }
  689. resolve(returnValue);
  690. });
  691. };
  692. Effect.prototype._processPrecision = function (source) {
  693. if (source.indexOf("precision highp float") === -1) {
  694. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  695. source = "precision mediump float;\n" + source;
  696. }
  697. else {
  698. source = "precision highp float;\n" + source;
  699. }
  700. }
  701. else {
  702. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  703. source = source.replace("precision highp float", "precision mediump float");
  704. }
  705. }
  706. return source;
  707. };
  708. /**
  709. * Recompiles the webGL program
  710. * @param vertexSourceCode The source code for the vertex shader.
  711. * @param fragmentSourceCode The source code for the fragment shader.
  712. * @param onCompiled Callback called when completed.
  713. * @param onError Callback called on error.
  714. */
  715. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  716. var _this = this;
  717. this._isReady = false;
  718. this._vertexSourceCodeOverride = vertexSourceCode;
  719. this._fragmentSourceCodeOverride = fragmentSourceCode;
  720. this.onError = function (effect, error) {
  721. if (onError) {
  722. onError(error);
  723. }
  724. };
  725. this.onCompiled = function () {
  726. var scenes = _this.getEngine().scenes;
  727. for (var i = 0; i < scenes.length; i++) {
  728. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  729. }
  730. if (onCompiled) {
  731. onCompiled(_this._program);
  732. }
  733. };
  734. this._fallbacks = null;
  735. this._prepareEffect();
  736. };
  737. /**
  738. * Gets the uniform locations of the the specified variable names
  739. * @param names THe names of the variables to lookup.
  740. * @returns Array of locations in the same order as variable names.
  741. */
  742. Effect.prototype.getSpecificUniformLocations = function (names) {
  743. var engine = this._engine;
  744. return engine.getUniforms(this._program, names);
  745. };
  746. /**
  747. * Prepares the effect
  748. */
  749. Effect.prototype._prepareEffect = function () {
  750. var attributesNames = this._attributesNames;
  751. var defines = this.defines;
  752. var fallbacks = this._fallbacks;
  753. this._valueCache = {};
  754. var previousProgram = this._program;
  755. try {
  756. var engine = this._engine;
  757. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  758. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  759. }
  760. else {
  761. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  762. }
  763. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  764. if (engine.supportsUniformBuffers) {
  765. for (var name in this._uniformBuffersNames) {
  766. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  767. }
  768. }
  769. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  770. this._attributes = engine.getAttributes(this._program, attributesNames);
  771. var index;
  772. for (index = 0; index < this._samplers.length; index++) {
  773. var sampler = this.getUniform(this._samplers[index]);
  774. if (sampler == null) {
  775. this._samplers.splice(index, 1);
  776. index--;
  777. }
  778. }
  779. engine.bindSamplers(this);
  780. this._compilationError = "";
  781. this._isReady = true;
  782. if (this.onCompiled) {
  783. this.onCompiled(this);
  784. }
  785. this.onCompileObservable.notifyObservers(this);
  786. this.onCompileObservable.clear();
  787. // Unbind mesh reference in fallbacks
  788. if (this._fallbacks) {
  789. this._fallbacks.unBindMesh();
  790. }
  791. if (previousProgram) {
  792. this.getEngine()._deleteProgram(previousProgram);
  793. }
  794. }
  795. catch (e) {
  796. this._compilationError = e.message;
  797. // Let's go through fallbacks then
  798. BABYLON.Tools.Error("Unable to compile effect:");
  799. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  800. return " " + uniform;
  801. }));
  802. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  803. return " " + attribute;
  804. }));
  805. this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
  806. BABYLON.Tools.Error("Error: " + this._compilationError);
  807. if (previousProgram) {
  808. this._program = previousProgram;
  809. this._isReady = true;
  810. if (this.onError) {
  811. this.onError(this, this._compilationError);
  812. }
  813. this.onErrorObservable.notifyObservers(this);
  814. }
  815. if (fallbacks && fallbacks.isMoreFallbacks) {
  816. BABYLON.Tools.Error("Trying next fallback.");
  817. this.defines = fallbacks.reduce(this.defines, this);
  818. this._prepareEffect();
  819. }
  820. else {
  821. if (this.onError) {
  822. this.onError(this, this._compilationError);
  823. }
  824. this.onErrorObservable.notifyObservers(this);
  825. this.onErrorObservable.clear();
  826. // Unbind mesh reference in fallbacks
  827. if (this._fallbacks) {
  828. this._fallbacks.unBindMesh();
  829. }
  830. }
  831. }
  832. };
  833. Object.defineProperty(Effect.prototype, "isSupported", {
  834. /**
  835. * Checks if the effect is supported. (Must be called after compilation)
  836. */
  837. get: function () {
  838. return this._compilationError === "";
  839. },
  840. enumerable: true,
  841. configurable: true
  842. });
  843. /**
  844. * Binds a texture to the engine to be used as output of the shader.
  845. * @param channel Name of the output variable.
  846. * @param texture Texture to bind.
  847. */
  848. Effect.prototype._bindTexture = function (channel, texture) {
  849. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  850. };
  851. /**
  852. * Sets a texture on the engine to be used in the shader.
  853. * @param channel Name of the sampler variable.
  854. * @param texture Texture to set.
  855. */
  856. Effect.prototype.setTexture = function (channel, texture) {
  857. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  858. };
  859. /**
  860. * Sets an array of textures on the engine to be used in the shader.
  861. * @param channel Name of the variable.
  862. * @param textures Textures to set.
  863. */
  864. Effect.prototype.setTextureArray = function (channel, textures) {
  865. if (this._samplers.indexOf(channel + "Ex") === -1) {
  866. var initialPos = this._samplers.indexOf(channel);
  867. for (var index = 1; index < textures.length; index++) {
  868. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  869. }
  870. }
  871. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  872. };
  873. /**
  874. * Sets a texture to be the input of the specified post process. (To use the output, pass in the next post process in the pipeline)
  875. * @param channel Name of the sampler variable.
  876. * @param postProcess Post process to get the input texture from.
  877. */
  878. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  879. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  880. };
  881. /** @ignore */
  882. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  883. var cache = this._valueCache[uniformName];
  884. var flag = matrix.updateFlag;
  885. if (cache !== undefined && cache === flag) {
  886. return false;
  887. }
  888. this._valueCache[uniformName] = flag;
  889. return true;
  890. };
  891. /** @ignore */
  892. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  893. var cache = this._valueCache[uniformName];
  894. if (!cache) {
  895. cache = [x, y];
  896. this._valueCache[uniformName] = cache;
  897. return true;
  898. }
  899. var changed = false;
  900. if (cache[0] !== x) {
  901. cache[0] = x;
  902. changed = true;
  903. }
  904. if (cache[1] !== y) {
  905. cache[1] = y;
  906. changed = true;
  907. }
  908. return changed;
  909. };
  910. /** @ignore */
  911. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  912. var cache = this._valueCache[uniformName];
  913. if (!cache) {
  914. cache = [x, y, z];
  915. this._valueCache[uniformName] = cache;
  916. return true;
  917. }
  918. var changed = false;
  919. if (cache[0] !== x) {
  920. cache[0] = x;
  921. changed = true;
  922. }
  923. if (cache[1] !== y) {
  924. cache[1] = y;
  925. changed = true;
  926. }
  927. if (cache[2] !== z) {
  928. cache[2] = z;
  929. changed = true;
  930. }
  931. return changed;
  932. };
  933. /** @ignore */
  934. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  935. var cache = this._valueCache[uniformName];
  936. if (!cache) {
  937. cache = [x, y, z, w];
  938. this._valueCache[uniformName] = cache;
  939. return true;
  940. }
  941. var changed = false;
  942. if (cache[0] !== x) {
  943. cache[0] = x;
  944. changed = true;
  945. }
  946. if (cache[1] !== y) {
  947. cache[1] = y;
  948. changed = true;
  949. }
  950. if (cache[2] !== z) {
  951. cache[2] = z;
  952. changed = true;
  953. }
  954. if (cache[3] !== w) {
  955. cache[3] = w;
  956. changed = true;
  957. }
  958. return changed;
  959. };
  960. /**
  961. * Binds a buffer to a uniform.
  962. * @param buffer Buffer to bind.
  963. * @param name Name of the uniform variable to bind to.
  964. */
  965. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  966. var bufferName = this._uniformBuffersNames[name];
  967. if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {
  968. return;
  969. }
  970. Effect._baseCache[bufferName] = buffer;
  971. this._engine.bindUniformBufferBase(buffer, bufferName);
  972. };
  973. /**
  974. * Binds block to a uniform.
  975. * @param blockName Name of the block to bind.
  976. * @param index Index to bind.
  977. */
  978. Effect.prototype.bindUniformBlock = function (blockName, index) {
  979. this._engine.bindUniformBlock(this._program, blockName, index);
  980. };
  981. /**
  982. * Sets an interger value on a uniform variable.
  983. * @param uniformName Name of the variable.
  984. * @param value Value to be set.
  985. * @returns this effect.
  986. */
  987. Effect.prototype.setInt = function (uniformName, value) {
  988. var cache = this._valueCache[uniformName];
  989. if (cache !== undefined && cache === value)
  990. return this;
  991. this._valueCache[uniformName] = value;
  992. this._engine.setInt(this.getUniform(uniformName), value);
  993. return this;
  994. };
  995. /**
  996. * Sets an int array on a uniform variable.
  997. * @param uniformName Name of the variable.
  998. * @param array array to be set.
  999. * @returns this effect.
  1000. */
  1001. Effect.prototype.setIntArray = function (uniformName, array) {
  1002. this._valueCache[uniformName] = null;
  1003. this._engine.setIntArray(this.getUniform(uniformName), array);
  1004. return this;
  1005. };
  1006. /**
  1007. * Sets an int array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  1008. * @param uniformName Name of the variable.
  1009. * @param array array to be set.
  1010. * @returns this effect.
  1011. */
  1012. Effect.prototype.setIntArray2 = function (uniformName, array) {
  1013. this._valueCache[uniformName] = null;
  1014. this._engine.setIntArray2(this.getUniform(uniformName), array);
  1015. return this;
  1016. };
  1017. /**
  1018. * Sets an int array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  1019. * @param uniformName Name of the variable.
  1020. * @param array array to be set.
  1021. * @returns this effect.
  1022. */
  1023. Effect.prototype.setIntArray3 = function (uniformName, array) {
  1024. this._valueCache[uniformName] = null;
  1025. this._engine.setIntArray3(this.getUniform(uniformName), array);
  1026. return this;
  1027. };
  1028. /**
  1029. * Sets an int array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  1030. * @param uniformName Name of the variable.
  1031. * @param array array to be set.
  1032. * @returns this effect.
  1033. */
  1034. Effect.prototype.setIntArray4 = function (uniformName, array) {
  1035. this._valueCache[uniformName] = null;
  1036. this._engine.setIntArray4(this.getUniform(uniformName), array);
  1037. return this;
  1038. };
  1039. /**
  1040. * Sets an float array on a uniform variable.
  1041. * @param uniformName Name of the variable.
  1042. * @param array array to be set.
  1043. * @returns this effect.
  1044. */
  1045. Effect.prototype.setFloatArray = function (uniformName, array) {
  1046. this._valueCache[uniformName] = null;
  1047. this._engine.setFloatArray(this.getUniform(uniformName), array);
  1048. return this;
  1049. };
  1050. /**
  1051. * Sets an float array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  1052. * @param uniformName Name of the variable.
  1053. * @param array array to be set.
  1054. * @returns this effect.
  1055. */
  1056. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  1057. this._valueCache[uniformName] = null;
  1058. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  1059. return this;
  1060. };
  1061. /**
  1062. * Sets an float array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  1063. * @param uniformName Name of the variable.
  1064. * @param array array to be set.
  1065. * @returns this effect.
  1066. */
  1067. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  1068. this._valueCache[uniformName] = null;
  1069. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  1070. return this;
  1071. };
  1072. /**
  1073. * Sets an float array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  1074. * @param uniformName Name of the variable.
  1075. * @param array array to be set.
  1076. * @returns this effect.
  1077. */
  1078. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  1079. this._valueCache[uniformName] = null;
  1080. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  1081. return this;
  1082. };
  1083. /**
  1084. * Sets an array on a uniform variable.
  1085. * @param uniformName Name of the variable.
  1086. * @param array array to be set.
  1087. * @returns this effect.
  1088. */
  1089. Effect.prototype.setArray = function (uniformName, array) {
  1090. this._valueCache[uniformName] = null;
  1091. this._engine.setArray(this.getUniform(uniformName), array);
  1092. return this;
  1093. };
  1094. /**
  1095. * Sets an array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  1096. * @param uniformName Name of the variable.
  1097. * @param array array to be set.
  1098. * @returns this effect.
  1099. */
  1100. Effect.prototype.setArray2 = function (uniformName, array) {
  1101. this._valueCache[uniformName] = null;
  1102. this._engine.setArray2(this.getUniform(uniformName), array);
  1103. return this;
  1104. };
  1105. /**
  1106. * Sets an array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  1107. * @param uniformName Name of the variable.
  1108. * @param array array to be set.
  1109. * @returns this effect.
  1110. */
  1111. Effect.prototype.setArray3 = function (uniformName, array) {
  1112. this._valueCache[uniformName] = null;
  1113. this._engine.setArray3(this.getUniform(uniformName), array);
  1114. return this;
  1115. };
  1116. /**
  1117. * Sets an array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  1118. * @param uniformName Name of the variable.
  1119. * @param array array to be set.
  1120. * @returns this effect.
  1121. */
  1122. Effect.prototype.setArray4 = function (uniformName, array) {
  1123. this._valueCache[uniformName] = null;
  1124. this._engine.setArray4(this.getUniform(uniformName), array);
  1125. return this;
  1126. };
  1127. /**
  1128. * Sets matrices on a uniform variable.
  1129. * @param uniformName Name of the variable.
  1130. * @param matrices matrices to be set.
  1131. * @returns this effect.
  1132. */
  1133. Effect.prototype.setMatrices = function (uniformName, matrices) {
  1134. if (!matrices) {
  1135. return this;
  1136. }
  1137. this._valueCache[uniformName] = null;
  1138. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  1139. return this;
  1140. };
  1141. /**
  1142. * Sets matrix on a uniform variable.
  1143. * @param uniformName Name of the variable.
  1144. * @param matrix matrix to be set.
  1145. * @returns this effect.
  1146. */
  1147. Effect.prototype.setMatrix = function (uniformName, matrix) {
  1148. if (this._cacheMatrix(uniformName, matrix)) {
  1149. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  1150. }
  1151. return this;
  1152. };
  1153. /**
  1154. * Sets a 3x3 matrix on a uniform variable. (Speicified as [1,2,3,4,5,6,7,8,9] will result in [1,2,3][4,5,6][7,8,9] matrix)
  1155. * @param uniformName Name of the variable.
  1156. * @param matrix matrix to be set.
  1157. * @returns this effect.
  1158. */
  1159. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  1160. this._valueCache[uniformName] = null;
  1161. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  1162. return this;
  1163. };
  1164. /**
  1165. * Sets a 2x2 matrix on a uniform variable. (Speicified as [1,2,3,4] will result in [1,2][3,4] matrix)
  1166. * @param uniformName Name of the variable.
  1167. * @param matrix matrix to be set.
  1168. * @returns this effect.
  1169. */
  1170. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  1171. this._valueCache[uniformName] = null;
  1172. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  1173. return this;
  1174. };
  1175. /**
  1176. * Sets a float on a uniform variable.
  1177. * @param uniformName Name of the variable.
  1178. * @param value value to be set.
  1179. * @returns this effect.
  1180. */
  1181. Effect.prototype.setFloat = function (uniformName, value) {
  1182. var cache = this._valueCache[uniformName];
  1183. if (cache !== undefined && cache === value)
  1184. return this;
  1185. this._valueCache[uniformName] = value;
  1186. this._engine.setFloat(this.getUniform(uniformName), value);
  1187. return this;
  1188. };
  1189. /**
  1190. * Sets a boolean on a uniform variable.
  1191. * @param uniformName Name of the variable.
  1192. * @param bool value to be set.
  1193. * @returns this effect.
  1194. */
  1195. Effect.prototype.setBool = function (uniformName, bool) {
  1196. var cache = this._valueCache[uniformName];
  1197. if (cache !== undefined && cache === bool)
  1198. return this;
  1199. this._valueCache[uniformName] = bool;
  1200. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  1201. return this;
  1202. };
  1203. /**
  1204. * Sets a Vector2 on a uniform variable.
  1205. * @param uniformName Name of the variable.
  1206. * @param vector2 vector2 to be set.
  1207. * @returns this effect.
  1208. */
  1209. Effect.prototype.setVector2 = function (uniformName, vector2) {
  1210. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  1211. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  1212. }
  1213. return this;
  1214. };
  1215. /**
  1216. * Sets a float2 on a uniform variable.
  1217. * @param uniformName Name of the variable.
  1218. * @param x First float in float2.
  1219. * @param y Second float in float2.
  1220. * @returns this effect.
  1221. */
  1222. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  1223. if (this._cacheFloat2(uniformName, x, y)) {
  1224. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  1225. }
  1226. return this;
  1227. };
  1228. /**
  1229. * Sets a Vector3 on a uniform variable.
  1230. * @param uniformName Name of the variable.
  1231. * @param vector3 Value to be set.
  1232. * @returns this effect.
  1233. */
  1234. Effect.prototype.setVector3 = function (uniformName, vector3) {
  1235. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  1236. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  1237. }
  1238. return this;
  1239. };
  1240. /**
  1241. * Sets a float3 on a uniform variable.
  1242. * @param uniformName Name of the variable.
  1243. * @param x First float in float3.
  1244. * @param y Second float in float3.
  1245. * @param z Third float in float3.
  1246. * @returns this effect.
  1247. */
  1248. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  1249. if (this._cacheFloat3(uniformName, x, y, z)) {
  1250. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  1251. }
  1252. return this;
  1253. };
  1254. /**
  1255. * Sets a Vector4 on a uniform variable.
  1256. * @param uniformName Name of the variable.
  1257. * @param vector4 Value to be set.
  1258. * @returns this effect.
  1259. */
  1260. Effect.prototype.setVector4 = function (uniformName, vector4) {
  1261. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  1262. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  1263. }
  1264. return this;
  1265. };
  1266. /**
  1267. * Sets a float4 on a uniform variable.
  1268. * @param uniformName Name of the variable.
  1269. * @param x First float in float4.
  1270. * @param y Second float in float4.
  1271. * @param z Third float in float4.
  1272. * @param w Fourth float in float4.
  1273. * @returns this effect.
  1274. */
  1275. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  1276. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  1277. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  1278. }
  1279. return this;
  1280. };
  1281. /**
  1282. * Sets a Color3 on a uniform variable.
  1283. * @param uniformName Name of the variable.
  1284. * @param color3 Value to be set.
  1285. * @returns this effect.
  1286. */
  1287. Effect.prototype.setColor3 = function (uniformName, color3) {
  1288. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  1289. this._engine.setColor3(this.getUniform(uniformName), color3);
  1290. }
  1291. return this;
  1292. };
  1293. /**
  1294. * Sets a Color4 on a uniform variable.
  1295. * @param uniformName Name of the variable.
  1296. * @param color3 Value to be set.
  1297. * @param alpha Alpha value to be set.
  1298. * @returns this effect.
  1299. */
  1300. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  1301. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  1302. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  1303. }
  1304. return this;
  1305. };
  1306. /**
  1307. * Sets a Color4 on a uniform variable
  1308. * @param uniformName defines the name of the variable
  1309. * @param color4 defines the value to be set
  1310. * @returns this effect.
  1311. */
  1312. Effect.prototype.setDirectColor4 = function (uniformName, color4) {
  1313. if (this._cacheFloat4(uniformName, color4.r, color4.g, color4.b, color4.a)) {
  1314. this._engine.setDirectColor4(this.getUniform(uniformName), color4);
  1315. }
  1316. return this;
  1317. };
  1318. /**
  1319. * Resets the cache of effects.
  1320. */
  1321. Effect.ResetCache = function () {
  1322. Effect._baseCache = {};
  1323. };
  1324. Effect._uniqueIdSeed = 0;
  1325. Effect._baseCache = {};
  1326. Effect._sourceCache = {};
  1327. // Statics
  1328. /**
  1329. * Store of each shader (The can be looked up using effect.key)
  1330. */
  1331. Effect.ShadersStore = {};
  1332. /**
  1333. * Store of each included file for a shader (The can be looked up using effect.key)
  1334. */
  1335. Effect.IncludesShadersStore = {};
  1336. return Effect;
  1337. }());
  1338. BABYLON.Effect = Effect;
  1339. })(BABYLON || (BABYLON = {}));
  1340. //# sourceMappingURL=babylon.effect.js.map
  1341. //# sourceMappingURL=babylon.types.js.map
  1342. var BABYLON;
  1343. (function (BABYLON) {
  1344. var KeyboardEventTypes = /** @class */ (function () {
  1345. function KeyboardEventTypes() {
  1346. }
  1347. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  1348. get: function () {
  1349. return KeyboardEventTypes._KEYDOWN;
  1350. },
  1351. enumerable: true,
  1352. configurable: true
  1353. });
  1354. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  1355. get: function () {
  1356. return KeyboardEventTypes._KEYUP;
  1357. },
  1358. enumerable: true,
  1359. configurable: true
  1360. });
  1361. KeyboardEventTypes._KEYDOWN = 0x01;
  1362. KeyboardEventTypes._KEYUP = 0x02;
  1363. return KeyboardEventTypes;
  1364. }());
  1365. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  1366. var KeyboardInfo = /** @class */ (function () {
  1367. function KeyboardInfo(type, event) {
  1368. this.type = type;
  1369. this.event = event;
  1370. }
  1371. return KeyboardInfo;
  1372. }());
  1373. BABYLON.KeyboardInfo = KeyboardInfo;
  1374. /**
  1375. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  1376. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  1377. */
  1378. var KeyboardInfoPre = /** @class */ (function (_super) {
  1379. __extends(KeyboardInfoPre, _super);
  1380. function KeyboardInfoPre(type, event) {
  1381. var _this = _super.call(this, type, event) || this;
  1382. _this.skipOnPointerObservable = false;
  1383. return _this;
  1384. }
  1385. return KeyboardInfoPre;
  1386. }(KeyboardInfo));
  1387. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  1388. })(BABYLON || (BABYLON = {}));
  1389. //# sourceMappingURL=babylon.keyboardEvents.js.map
  1390. var BABYLON;
  1391. (function (BABYLON) {
  1392. var PointerEventTypes = /** @class */ (function () {
  1393. function PointerEventTypes() {
  1394. }
  1395. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  1396. get: function () {
  1397. return PointerEventTypes._POINTERDOWN;
  1398. },
  1399. enumerable: true,
  1400. configurable: true
  1401. });
  1402. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  1403. get: function () {
  1404. return PointerEventTypes._POINTERUP;
  1405. },
  1406. enumerable: true,
  1407. configurable: true
  1408. });
  1409. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  1410. get: function () {
  1411. return PointerEventTypes._POINTERMOVE;
  1412. },
  1413. enumerable: true,
  1414. configurable: true
  1415. });
  1416. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  1417. get: function () {
  1418. return PointerEventTypes._POINTERWHEEL;
  1419. },
  1420. enumerable: true,
  1421. configurable: true
  1422. });
  1423. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  1424. get: function () {
  1425. return PointerEventTypes._POINTERPICK;
  1426. },
  1427. enumerable: true,
  1428. configurable: true
  1429. });
  1430. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  1431. get: function () {
  1432. return PointerEventTypes._POINTERTAP;
  1433. },
  1434. enumerable: true,
  1435. configurable: true
  1436. });
  1437. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  1438. get: function () {
  1439. return PointerEventTypes._POINTERDOUBLETAP;
  1440. },
  1441. enumerable: true,
  1442. configurable: true
  1443. });
  1444. PointerEventTypes._POINTERDOWN = 0x01;
  1445. PointerEventTypes._POINTERUP = 0x02;
  1446. PointerEventTypes._POINTERMOVE = 0x04;
  1447. PointerEventTypes._POINTERWHEEL = 0x08;
  1448. PointerEventTypes._POINTERPICK = 0x10;
  1449. PointerEventTypes._POINTERTAP = 0x20;
  1450. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  1451. return PointerEventTypes;
  1452. }());
  1453. BABYLON.PointerEventTypes = PointerEventTypes;
  1454. var PointerInfoBase = /** @class */ (function () {
  1455. function PointerInfoBase(type, event) {
  1456. this.type = type;
  1457. this.event = event;
  1458. }
  1459. return PointerInfoBase;
  1460. }());
  1461. BABYLON.PointerInfoBase = PointerInfoBase;
  1462. /**
  1463. * This class is used to store pointer related info for the onPrePointerObservable event.
  1464. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  1465. */
  1466. var PointerInfoPre = /** @class */ (function (_super) {
  1467. __extends(PointerInfoPre, _super);
  1468. function PointerInfoPre(type, event, localX, localY) {
  1469. var _this = _super.call(this, type, event) || this;
  1470. _this.skipOnPointerObservable = false;
  1471. _this.localPosition = new BABYLON.Vector2(localX, localY);
  1472. return _this;
  1473. }
  1474. return PointerInfoPre;
  1475. }(PointerInfoBase));
  1476. BABYLON.PointerInfoPre = PointerInfoPre;
  1477. /**
  1478. * This type contains all the data related to a pointer event in Babylon.js.
  1479. * The event member is an instance of PointerEvent for all types except PointerWheel and is of type MouseWheelEvent when type equals PointerWheel. The different event types can be found in the PointerEventTypes class.
  1480. */
  1481. var PointerInfo = /** @class */ (function (_super) {
  1482. __extends(PointerInfo, _super);
  1483. function PointerInfo(type, event, pickInfo) {
  1484. var _this = _super.call(this, type, event) || this;
  1485. _this.pickInfo = pickInfo;
  1486. return _this;
  1487. }
  1488. return PointerInfo;
  1489. }(PointerInfoBase));
  1490. BABYLON.PointerInfo = PointerInfo;
  1491. })(BABYLON || (BABYLON = {}));
  1492. //# sourceMappingURL=babylon.pointerEvents.js.map
  1493. var BABYLON;
  1494. (function (BABYLON) {
  1495. BABYLON.ToGammaSpace = 1 / 2.2;
  1496. BABYLON.ToLinearSpace = 2.2;
  1497. BABYLON.Epsilon = 0.001;
  1498. /**
  1499. * Class used to hold a RBG color
  1500. */
  1501. var Color3 = /** @class */ (function () {
  1502. /**
  1503. * Creates a new Color3 object from red, green, blue values, all between 0 and 1
  1504. * @param r defines the red component (between 0 and 1, default is 0)
  1505. * @param g defines the green component (between 0 and 1, default is 0)
  1506. * @param b defines the blue component (between 0 and 1, default is 0)
  1507. */
  1508. function Color3(
  1509. /**
  1510. * Defines the red component (between 0 and 1, default is 0)
  1511. */
  1512. r,
  1513. /**
  1514. * Defines the green component (between 0 and 1, default is 0)
  1515. */
  1516. g,
  1517. /**
  1518. * Defines the blue component (between 0 and 1, default is 0)
  1519. */
  1520. b) {
  1521. if (r === void 0) { r = 0; }
  1522. if (g === void 0) { g = 0; }
  1523. if (b === void 0) { b = 0; }
  1524. this.r = r;
  1525. this.g = g;
  1526. this.b = b;
  1527. }
  1528. /**
  1529. * Creates a string with the Color3 current values
  1530. * @returns the string representation of the Color3 object
  1531. */
  1532. Color3.prototype.toString = function () {
  1533. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1534. };
  1535. /**
  1536. * Returns the string "Color3"
  1537. * @returns "Color3"
  1538. */
  1539. Color3.prototype.getClassName = function () {
  1540. return "Color3";
  1541. };
  1542. /**
  1543. * Compute the Color3 hash code
  1544. * @returns an unique number that can be used to hash Color3 objects
  1545. */
  1546. Color3.prototype.getHashCode = function () {
  1547. var hash = this.r || 0;
  1548. hash = (hash * 397) ^ (this.g || 0);
  1549. hash = (hash * 397) ^ (this.b || 0);
  1550. return hash;
  1551. };
  1552. // Operators
  1553. /**
  1554. * Stores in the passed array from the passed starting index the red, green, blue values as successive elements
  1555. * @param array defines the array where to store the r,g,b components
  1556. * @param index defines an optional index in the target array to define where to start storing values
  1557. * @returns the current Color3 object
  1558. */
  1559. Color3.prototype.toArray = function (array, index) {
  1560. if (index === undefined) {
  1561. index = 0;
  1562. }
  1563. array[index] = this.r;
  1564. array[index + 1] = this.g;
  1565. array[index + 2] = this.b;
  1566. return this;
  1567. };
  1568. /**
  1569. * Returns a new {BABYLON.Color4} object from the current Color3 and the passed alpha
  1570. * @param alpha defines the alpha component on the new {BABYLON.Color4} object (default is 1)
  1571. * @returns a new {BABYLON.Color4} object
  1572. */
  1573. Color3.prototype.toColor4 = function (alpha) {
  1574. if (alpha === void 0) { alpha = 1; }
  1575. return new Color4(this.r, this.g, this.b, alpha);
  1576. };
  1577. /**
  1578. * Returns a new array populated with 3 numeric elements : red, green and blue values
  1579. * @returns the new array
  1580. */
  1581. Color3.prototype.asArray = function () {
  1582. var result = new Array();
  1583. this.toArray(result, 0);
  1584. return result;
  1585. };
  1586. /**
  1587. * Returns the luminance value
  1588. * @returns a float value
  1589. */
  1590. Color3.prototype.toLuminance = function () {
  1591. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1592. };
  1593. /**
  1594. * Multiply each Color3 rgb values by the passed Color3 rgb values in a new Color3 object
  1595. * @param otherColor defines the second operand
  1596. * @returns the new Color3 object
  1597. */
  1598. Color3.prototype.multiply = function (otherColor) {
  1599. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1600. };
  1601. /**
  1602. * Multiply the rgb values of the Color3 and the passed Color3 and stores the result in the object "result"
  1603. * @param otherColor defines the second operand
  1604. * @param result defines the Color3 object where to store the result
  1605. * @returns the current Color3
  1606. */
  1607. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1608. result.r = this.r * otherColor.r;
  1609. result.g = this.g * otherColor.g;
  1610. result.b = this.b * otherColor.b;
  1611. return this;
  1612. };
  1613. /**
  1614. * Determines equality between Color3 objects
  1615. * @param otherColor defines the second operand
  1616. * @returns true if the rgb values are equal to the passed ones
  1617. */
  1618. Color3.prototype.equals = function (otherColor) {
  1619. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1620. };
  1621. /**
  1622. * Determines equality between the current Color3 object and a set of r,b,g values
  1623. * @param r defines the red component to check
  1624. * @param g defines the green component to check
  1625. * @param b defines the blue component to check
  1626. * @returns true if the rgb values are equal to the passed ones
  1627. */
  1628. Color3.prototype.equalsFloats = function (r, g, b) {
  1629. return this.r === r && this.g === g && this.b === b;
  1630. };
  1631. /**
  1632. * Multiplies in place each rgb value by scale
  1633. * @param scale defines the scaling factor
  1634. * @returns the updated Color3.
  1635. */
  1636. Color3.prototype.scale = function (scale) {
  1637. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1638. };
  1639. /**
  1640. * Multiplies the rgb values by scale and stores the result into "result"
  1641. * @param scale defines the scaling factor
  1642. * @param result defines the Color3 object where to store the result
  1643. * @returns the unmodified current Color3.
  1644. */
  1645. Color3.prototype.scaleToRef = function (scale, result) {
  1646. result.r = this.r * scale;
  1647. result.g = this.g * scale;
  1648. result.b = this.b * scale;
  1649. return this;
  1650. };
  1651. /**
  1652. * Clamps the rgb values by the min and max values and stores the result into "result"
  1653. * @param min defines minimum clamping value (default is 0)
  1654. * @param max defines maximum clamping value (default is 1)
  1655. * @param result defines color to store the result into
  1656. * @returns the original Color3
  1657. */
  1658. Color3.prototype.clampToRef = function (min, max, result) {
  1659. if (min === void 0) { min = 0; }
  1660. if (max === void 0) { max = 1; }
  1661. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1662. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1663. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1664. return this;
  1665. };
  1666. /**
  1667. * Creates a new Color3 set with the added values of the current Color3 and of the passed one
  1668. * @param otherColor defines the second operand
  1669. * @returns the new Color3
  1670. */
  1671. Color3.prototype.add = function (otherColor) {
  1672. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1673. };
  1674. /**
  1675. * Stores the result of the addition of the current Color3 and passed one rgb values into "result"
  1676. * @param otherColor defines the second operand
  1677. * @param result defines Color3 object to store the result into
  1678. * @returns the unmodified current Color3
  1679. */
  1680. Color3.prototype.addToRef = function (otherColor, result) {
  1681. result.r = this.r + otherColor.r;
  1682. result.g = this.g + otherColor.g;
  1683. result.b = this.b + otherColor.b;
  1684. return this;
  1685. };
  1686. /**
  1687. * Returns a new Color3 set with the subtracted values of the passed one from the current Color3
  1688. * @param otherColor defines the second operand
  1689. * @returns the new Color3
  1690. */
  1691. Color3.prototype.subtract = function (otherColor) {
  1692. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1693. };
  1694. /**
  1695. * Stores the result of the subtraction of passed one from the current Color3 rgb values into "result"
  1696. * @param otherColor defines the second operand
  1697. * @param result defines Color3 object to store the result into
  1698. * @returns the unmodified current Color3
  1699. */
  1700. Color3.prototype.subtractToRef = function (otherColor, result) {
  1701. result.r = this.r - otherColor.r;
  1702. result.g = this.g - otherColor.g;
  1703. result.b = this.b - otherColor.b;
  1704. return this;
  1705. };
  1706. /**
  1707. * Copy the current object
  1708. * @returns a new Color3 copied the current one
  1709. */
  1710. Color3.prototype.clone = function () {
  1711. return new Color3(this.r, this.g, this.b);
  1712. };
  1713. /**
  1714. * Copies the rgb values from the source in the current Color3
  1715. * @param source defines the source Color3 object
  1716. * @returns the updated Color3 object
  1717. */
  1718. Color3.prototype.copyFrom = function (source) {
  1719. this.r = source.r;
  1720. this.g = source.g;
  1721. this.b = source.b;
  1722. return this;
  1723. };
  1724. /**
  1725. * Updates the Color3 rgb values from the passed floats
  1726. * @param r defines the red component to read from
  1727. * @param g defines the green component to read from
  1728. * @param b defines the blue component to read from
  1729. * @returns the current Color3 object
  1730. */
  1731. Color3.prototype.copyFromFloats = function (r, g, b) {
  1732. this.r = r;
  1733. this.g = g;
  1734. this.b = b;
  1735. return this;
  1736. };
  1737. /**
  1738. * Updates the Color3 rgb values from the passed floats
  1739. * @param r defines the red component to read from
  1740. * @param g defines the green component to read from
  1741. * @param b defines the blue component to read from
  1742. * @returns the current Color3 object
  1743. */
  1744. Color3.prototype.set = function (r, g, b) {
  1745. return this.copyFromFloats(r, g, b);
  1746. };
  1747. /**
  1748. * Compute the Color3 hexadecimal code as a string
  1749. * @returns a string containing the hexadecimal representation of the Color3 object
  1750. */
  1751. Color3.prototype.toHexString = function () {
  1752. var intR = (this.r * 255) | 0;
  1753. var intG = (this.g * 255) | 0;
  1754. var intB = (this.b * 255) | 0;
  1755. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1756. };
  1757. /**
  1758. * Computes a new Color3 converted from the current one to linear space
  1759. * @returns a new Color3 object
  1760. */
  1761. Color3.prototype.toLinearSpace = function () {
  1762. var convertedColor = new Color3();
  1763. this.toLinearSpaceToRef(convertedColor);
  1764. return convertedColor;
  1765. };
  1766. /**
  1767. * Converts the Color3 values to linear space and stores the result in "convertedColor"
  1768. * @param convertedColor defines the Color3 object where to store the linear space version
  1769. * @returns the unmodified Color3
  1770. */
  1771. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1772. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1773. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1774. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1775. return this;
  1776. };
  1777. /**
  1778. * Computes a new Color3 converted from the current one to gamma space
  1779. * @returns a new Color3 object
  1780. */
  1781. Color3.prototype.toGammaSpace = function () {
  1782. var convertedColor = new Color3();
  1783. this.toGammaSpaceToRef(convertedColor);
  1784. return convertedColor;
  1785. };
  1786. /**
  1787. * Converts the Color3 values to gamma space and stores the result in "convertedColor"
  1788. * @param convertedColor defines the Color3 object where to store the gamma space version
  1789. * @returns the unmodified Color3
  1790. */
  1791. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1792. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1793. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1794. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1795. return this;
  1796. };
  1797. // Statics
  1798. /**
  1799. * Creates a new Color3 from the string containing valid hexadecimal values
  1800. * @param hex defines a string containing valid hexadecimal values
  1801. * @returns a new Color3 object
  1802. */
  1803. Color3.FromHexString = function (hex) {
  1804. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1805. return new Color3(0, 0, 0);
  1806. }
  1807. var r = parseInt(hex.substring(1, 3), 16);
  1808. var g = parseInt(hex.substring(3, 5), 16);
  1809. var b = parseInt(hex.substring(5, 7), 16);
  1810. return Color3.FromInts(r, g, b);
  1811. };
  1812. /**
  1813. * Creates a new Vector3 from the starting index of the passed array
  1814. * @param array defines the source array
  1815. * @param offset defines an offset in the source array
  1816. * @returns a new Color3 object
  1817. */
  1818. Color3.FromArray = function (array, offset) {
  1819. if (offset === void 0) { offset = 0; }
  1820. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1821. };
  1822. /**
  1823. * Creates a new Color3 from integer values (< 256)
  1824. * @param r defines the red component to read from (value between 0 and 255)
  1825. * @param g defines the green component to read from (value between 0 and 255)
  1826. * @param b defines the blue component to read from (value between 0 and 255)
  1827. * @returns a new Color3 object
  1828. */
  1829. Color3.FromInts = function (r, g, b) {
  1830. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1831. };
  1832. /**
  1833. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1834. * @param start defines the start Color3 value
  1835. * @param end defines the end Color3 value
  1836. * @param amount defines the gradient value between start and end
  1837. * @returns a new Color3 object
  1838. */
  1839. Color3.Lerp = function (start, end, amount) {
  1840. var r = start.r + ((end.r - start.r) * amount);
  1841. var g = start.g + ((end.g - start.g) * amount);
  1842. var b = start.b + ((end.b - start.b) * amount);
  1843. return new Color3(r, g, b);
  1844. };
  1845. /**
  1846. * Returns a Color3 value containing a red color
  1847. * @returns a new Color3 object
  1848. */
  1849. Color3.Red = function () { return new Color3(1, 0, 0); };
  1850. /**
  1851. * Returns a Color3 value containing a green color
  1852. * @returns a new Color3 object
  1853. */
  1854. Color3.Green = function () { return new Color3(0, 1, 0); };
  1855. /**
  1856. * Returns a Color3 value containing a blue color
  1857. * @returns a new Color3 object
  1858. */
  1859. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1860. /**
  1861. * Returns a Color3 value containing a black color
  1862. * @returns a new Color3 object
  1863. */
  1864. Color3.Black = function () { return new Color3(0, 0, 0); };
  1865. /**
  1866. * Returns a Color3 value containing a white color
  1867. * @returns a new Color3 object
  1868. */
  1869. Color3.White = function () { return new Color3(1, 1, 1); };
  1870. /**
  1871. * Returns a Color3 value containing a purple color
  1872. * @returns a new Color3 object
  1873. */
  1874. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1875. /**
  1876. * Returns a Color3 value containing a magenta color
  1877. * @returns a new Color3 object
  1878. */
  1879. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1880. /**
  1881. * Returns a Color3 value containing a yellow color
  1882. * @returns a new Color3 object
  1883. */
  1884. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1885. /**
  1886. * Returns a Color3 value containing a gray color
  1887. * @returns a new Color3 object
  1888. */
  1889. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1890. /**
  1891. * Returns a Color3 value containing a teal color
  1892. * @returns a new Color3 object
  1893. */
  1894. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1895. /**
  1896. * Returns a Color3 value containing a random color
  1897. * @returns a new Color3 object
  1898. */
  1899. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1900. return Color3;
  1901. }());
  1902. BABYLON.Color3 = Color3;
  1903. /**
  1904. * Class used to hold a RBGA color
  1905. */
  1906. var Color4 = /** @class */ (function () {
  1907. /**
  1908. * Creates a new Color4 object from red, green, blue values, all between 0 and 1
  1909. * @param r defines the red component (between 0 and 1, default is 0)
  1910. * @param g defines the green component (between 0 and 1, default is 0)
  1911. * @param b defines the blue component (between 0 and 1, default is 0)
  1912. * @param a defines the alpha component (between 0 and 1, default is 1)
  1913. */
  1914. function Color4(
  1915. /**
  1916. * Defines the red component (between 0 and 1, default is 0)
  1917. */
  1918. r,
  1919. /**
  1920. * Defines the green component (between 0 and 1, default is 0)
  1921. */
  1922. g,
  1923. /**
  1924. * Defines the blue component (between 0 and 1, default is 0)
  1925. */
  1926. b,
  1927. /**
  1928. * Defines the alpha component (between 0 and 1, default is 1)
  1929. */
  1930. a) {
  1931. if (r === void 0) { r = 0; }
  1932. if (g === void 0) { g = 0; }
  1933. if (b === void 0) { b = 0; }
  1934. if (a === void 0) { a = 1; }
  1935. this.r = r;
  1936. this.g = g;
  1937. this.b = b;
  1938. this.a = a;
  1939. }
  1940. // Operators
  1941. /**
  1942. * Adds in place the passed Color4 values to the current Color4 object
  1943. * @param right defines the second operand
  1944. * @returns the current updated Color4 object
  1945. */
  1946. Color4.prototype.addInPlace = function (right) {
  1947. this.r += right.r;
  1948. this.g += right.g;
  1949. this.b += right.b;
  1950. this.a += right.a;
  1951. return this;
  1952. };
  1953. /**
  1954. * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values
  1955. * @returns the new array
  1956. */
  1957. Color4.prototype.asArray = function () {
  1958. var result = new Array();
  1959. this.toArray(result, 0);
  1960. return result;
  1961. };
  1962. /**
  1963. * Stores from the starting index in the passed array the Color4 successive values
  1964. * @param array defines the array where to store the r,g,b components
  1965. * @param index defines an optional index in the target array to define where to start storing values
  1966. * @returns the current Color4 object
  1967. */
  1968. Color4.prototype.toArray = function (array, index) {
  1969. if (index === undefined) {
  1970. index = 0;
  1971. }
  1972. array[index] = this.r;
  1973. array[index + 1] = this.g;
  1974. array[index + 2] = this.b;
  1975. array[index + 3] = this.a;
  1976. return this;
  1977. };
  1978. /**
  1979. * Creates a new Color4 set with the added values of the current Color4 and of the passed one
  1980. * @param right defines the second operand
  1981. * @returns a new Color4 object
  1982. */
  1983. Color4.prototype.add = function (right) {
  1984. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  1985. };
  1986. /**
  1987. * Creates a new Color4 set with the subtracted values of the passed one from the current Color4
  1988. * @param right defines the second operand
  1989. * @returns a new Color4 object
  1990. */
  1991. Color4.prototype.subtract = function (right) {
  1992. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1993. };
  1994. /**
  1995. * Subtracts the passed ones from the current Color4 values and stores the results in "result"
  1996. * @param right defines the second operand
  1997. * @param result defines the Color4 object where to store the result
  1998. * @returns the current Color4 object
  1999. */
  2000. Color4.prototype.subtractToRef = function (right, result) {
  2001. result.r = this.r - right.r;
  2002. result.g = this.g - right.g;
  2003. result.b = this.b - right.b;
  2004. result.a = this.a - right.a;
  2005. return this;
  2006. };
  2007. /**
  2008. * Creates a new Color4 with the current Color4 values multiplied by scale
  2009. * @param scale defines the scaling factor to apply
  2010. * @returns a new Color4 object
  2011. */
  2012. Color4.prototype.scale = function (scale) {
  2013. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  2014. };
  2015. /**
  2016. * Multiplies the current Color4 values by scale and stores the result in "result"
  2017. * @param scale defines the scaling factor to apply
  2018. * @param result defines the Color4 object where to store the result
  2019. * @returns the current Color4.
  2020. */
  2021. Color4.prototype.scaleToRef = function (scale, result) {
  2022. result.r = this.r * scale;
  2023. result.g = this.g * scale;
  2024. result.b = this.b * scale;
  2025. result.a = this.a * scale;
  2026. return this;
  2027. };
  2028. /**
  2029. * Clamps the rgb values by the min and max values and stores the result into "result"
  2030. * @param min defines minimum clamping value (default is 0)
  2031. * @param max defines maximum clamping value (default is 1)
  2032. * @param result defines color to store the result into.
  2033. * @returns the cuurent Color4
  2034. */
  2035. Color4.prototype.clampToRef = function (min, max, result) {
  2036. if (min === void 0) { min = 0; }
  2037. if (max === void 0) { max = 1; }
  2038. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  2039. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  2040. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  2041. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  2042. return this;
  2043. };
  2044. /**
  2045. * Multipy an Color4 value by another and return a new Color4 object
  2046. * @param color defines the Color4 value to multiply by
  2047. * @returns a new Color4 object
  2048. */
  2049. Color4.prototype.multiply = function (color) {
  2050. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  2051. };
  2052. /**
  2053. * Multipy a Color4 value by another and push the result in a reference value
  2054. * @param color defines the Color4 value to multiply by
  2055. * @param result defines the Color4 to fill the result in
  2056. * @returns the result Color4
  2057. */
  2058. Color4.prototype.multiplyToRef = function (color, result) {
  2059. result.r = this.r * color.r;
  2060. result.g = this.g * color.g;
  2061. result.b = this.b * color.b;
  2062. result.a = this.a * color.a;
  2063. return result;
  2064. };
  2065. /**
  2066. * Creates a string with the Color4 current values
  2067. * @returns the string representation of the Color4 object
  2068. */
  2069. Color4.prototype.toString = function () {
  2070. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  2071. };
  2072. /**
  2073. * Returns the string "Color4"
  2074. * @returns "Color4"
  2075. */
  2076. Color4.prototype.getClassName = function () {
  2077. return "Color4";
  2078. };
  2079. /**
  2080. * Compute the Color4 hash code
  2081. * @returns an unique number that can be used to hash Color4 objects
  2082. */
  2083. Color4.prototype.getHashCode = function () {
  2084. var hash = this.r || 0;
  2085. hash = (hash * 397) ^ (this.g || 0);
  2086. hash = (hash * 397) ^ (this.b || 0);
  2087. hash = (hash * 397) ^ (this.a || 0);
  2088. return hash;
  2089. };
  2090. /**
  2091. * Creates a new Color4 copied from the current one
  2092. * @returns a new Color4 object
  2093. */
  2094. Color4.prototype.clone = function () {
  2095. return new Color4(this.r, this.g, this.b, this.a);
  2096. };
  2097. /**
  2098. * Copies the passed Color4 values into the current one
  2099. * @param source defines the source Color4 object
  2100. * @returns the current updated Color4 object
  2101. */
  2102. Color4.prototype.copyFrom = function (source) {
  2103. this.r = source.r;
  2104. this.g = source.g;
  2105. this.b = source.b;
  2106. this.a = source.a;
  2107. return this;
  2108. };
  2109. /**
  2110. * Copies the passed float values into the current one
  2111. * @param r defines the red component to read from
  2112. * @param g defines the green component to read from
  2113. * @param b defines the blue component to read from
  2114. * @param a defines the alpha component to read from
  2115. * @returns the current updated Color4 object
  2116. */
  2117. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  2118. this.r = r;
  2119. this.g = g;
  2120. this.b = b;
  2121. this.a = a;
  2122. return this;
  2123. };
  2124. /**
  2125. * Copies the passed float values into the current one
  2126. * @param r defines the red component to read from
  2127. * @param g defines the green component to read from
  2128. * @param b defines the blue component to read from
  2129. * @param a defines the alpha component to read from
  2130. * @returns the current updated Color4 object
  2131. */
  2132. Color4.prototype.set = function (r, g, b, a) {
  2133. return this.copyFromFloats(r, g, b, a);
  2134. };
  2135. /**
  2136. * Compute the Color4 hexadecimal code as a string
  2137. * @returns a string containing the hexadecimal representation of the Color4 object
  2138. */
  2139. Color4.prototype.toHexString = function () {
  2140. var intR = (this.r * 255) | 0;
  2141. var intG = (this.g * 255) | 0;
  2142. var intB = (this.b * 255) | 0;
  2143. var intA = (this.a * 255) | 0;
  2144. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  2145. };
  2146. /**
  2147. * Computes a new Color4 converted from the current one to linear space
  2148. * @returns a new Color4 object
  2149. */
  2150. Color4.prototype.toLinearSpace = function () {
  2151. var convertedColor = new Color4();
  2152. this.toLinearSpaceToRef(convertedColor);
  2153. return convertedColor;
  2154. };
  2155. /**
  2156. * Converts the Color4 values to linear space and stores the result in "convertedColor"
  2157. * @param convertedColor defines the Color4 object where to store the linear space version
  2158. * @returns the unmodified Color4
  2159. */
  2160. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  2161. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  2162. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  2163. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  2164. convertedColor.a = this.a;
  2165. return this;
  2166. };
  2167. /**
  2168. * Computes a new Color4 converted from the current one to gamma space
  2169. * @returns a new Color4 object
  2170. */
  2171. Color4.prototype.toGammaSpace = function () {
  2172. var convertedColor = new Color4();
  2173. this.toGammaSpaceToRef(convertedColor);
  2174. return convertedColor;
  2175. };
  2176. /**
  2177. * Converts the Color4 values to gamma space and stores the result in "convertedColor"
  2178. * @param convertedColor defines the Color4 object where to store the gamma space version
  2179. * @returns the unmodified Color4
  2180. */
  2181. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  2182. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  2183. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  2184. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  2185. convertedColor.a = this.a;
  2186. return this;
  2187. };
  2188. // Statics
  2189. /**
  2190. * Creates a new Color4 from the string containing valid hexadecimal values
  2191. * @param hex defines a string containing valid hexadecimal values
  2192. * @returns a new Color4 object
  2193. */
  2194. Color4.FromHexString = function (hex) {
  2195. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  2196. return new Color4(0.0, 0.0, 0.0, 0.0);
  2197. }
  2198. var r = parseInt(hex.substring(1, 3), 16);
  2199. var g = parseInt(hex.substring(3, 5), 16);
  2200. var b = parseInt(hex.substring(5, 7), 16);
  2201. var a = parseInt(hex.substring(7, 9), 16);
  2202. return Color4.FromInts(r, g, b, a);
  2203. };
  2204. /**
  2205. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2206. * @param left defines the start value
  2207. * @param right defines the end value
  2208. * @param amount defines the gradient factor
  2209. * @returns a new Color4 object
  2210. */
  2211. Color4.Lerp = function (left, right, amount) {
  2212. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  2213. Color4.LerpToRef(left, right, amount, result);
  2214. return result;
  2215. };
  2216. /**
  2217. * Set the passed "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2218. * @param left defines the start value
  2219. * @param right defines the end value
  2220. * @param amount defines the gradient factor
  2221. * @param result defines the Color4 object where to store data
  2222. */
  2223. Color4.LerpToRef = function (left, right, amount, result) {
  2224. result.r = left.r + (right.r - left.r) * amount;
  2225. result.g = left.g + (right.g - left.g) * amount;
  2226. result.b = left.b + (right.b - left.b) * amount;
  2227. result.a = left.a + (right.a - left.a) * amount;
  2228. };
  2229. /**
  2230. * Creates a new Color4 from the starting index element of the passed array
  2231. * @param array defines the source array to read from
  2232. * @param offset defines the offset in the source array
  2233. * @returns a new Color4 object
  2234. */
  2235. Color4.FromArray = function (array, offset) {
  2236. if (offset === void 0) { offset = 0; }
  2237. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2238. };
  2239. /**
  2240. * Creates a new Color3 from integer values (< 256)
  2241. * @param r defines the red component to read from (value between 0 and 255)
  2242. * @param g defines the green component to read from (value between 0 and 255)
  2243. * @param b defines the blue component to read from (value between 0 and 255)
  2244. * @param a defines the alpha component to read from (value between 0 and 255)
  2245. * @returns a new Color3 object
  2246. */
  2247. Color4.FromInts = function (r, g, b, a) {
  2248. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  2249. };
  2250. /**
  2251. * Check the content of a given array and convert it to an array containing RGBA data
  2252. * If the original array was already containing count * 4 values then it is returned directly
  2253. * @param colors defines the array to check
  2254. * @param count defines the number of RGBA data to expect
  2255. * @returns an array containing count * 4 values (RGBA)
  2256. */
  2257. Color4.CheckColors4 = function (colors, count) {
  2258. // Check if color3 was used
  2259. if (colors.length === count * 3) {
  2260. var colors4 = [];
  2261. for (var index = 0; index < colors.length; index += 3) {
  2262. var newIndex = (index / 3) * 4;
  2263. colors4[newIndex] = colors[index];
  2264. colors4[newIndex + 1] = colors[index + 1];
  2265. colors4[newIndex + 2] = colors[index + 2];
  2266. colors4[newIndex + 3] = 1.0;
  2267. }
  2268. return colors4;
  2269. }
  2270. return colors;
  2271. };
  2272. return Color4;
  2273. }());
  2274. BABYLON.Color4 = Color4;
  2275. var Vector2 = /** @class */ (function () {
  2276. /**
  2277. * Creates a new Vector2 from the passed x and y coordinates.
  2278. */
  2279. function Vector2(x, y) {
  2280. this.x = x;
  2281. this.y = y;
  2282. }
  2283. /**
  2284. * Returns a string with the Vector2 coordinates.
  2285. */
  2286. Vector2.prototype.toString = function () {
  2287. return "{X: " + this.x + " Y:" + this.y + "}";
  2288. };
  2289. /**
  2290. * Returns the string "Vector2"
  2291. */
  2292. Vector2.prototype.getClassName = function () {
  2293. return "Vector2";
  2294. };
  2295. /**
  2296. * Returns the Vector2 hash code as a number.
  2297. */
  2298. Vector2.prototype.getHashCode = function () {
  2299. var hash = this.x || 0;
  2300. hash = (hash * 397) ^ (this.y || 0);
  2301. return hash;
  2302. };
  2303. // Operators
  2304. /**
  2305. * Sets the Vector2 coordinates in the passed array or Float32Array from the passed index.
  2306. * Returns the Vector2.
  2307. */
  2308. Vector2.prototype.toArray = function (array, index) {
  2309. if (index === void 0) { index = 0; }
  2310. array[index] = this.x;
  2311. array[index + 1] = this.y;
  2312. return this;
  2313. };
  2314. /**
  2315. * Returns a new array with 2 elements : the Vector2 coordinates.
  2316. */
  2317. Vector2.prototype.asArray = function () {
  2318. var result = new Array();
  2319. this.toArray(result, 0);
  2320. return result;
  2321. };
  2322. /**
  2323. * Sets the Vector2 coordinates with the passed Vector2 coordinates.
  2324. * Returns the updated Vector2.
  2325. */
  2326. Vector2.prototype.copyFrom = function (source) {
  2327. this.x = source.x;
  2328. this.y = source.y;
  2329. return this;
  2330. };
  2331. /**
  2332. * Sets the Vector2 coordinates with the passed floats.
  2333. * Returns the updated Vector2.
  2334. */
  2335. Vector2.prototype.copyFromFloats = function (x, y) {
  2336. this.x = x;
  2337. this.y = y;
  2338. return this;
  2339. };
  2340. /**
  2341. * Sets the Vector2 coordinates with the passed floats.
  2342. * Returns the updated Vector2.
  2343. */
  2344. Vector2.prototype.set = function (x, y) {
  2345. return this.copyFromFloats(x, y);
  2346. };
  2347. /**
  2348. * Returns a new Vector2 set with the addition of the current Vector2 and the passed one coordinates.
  2349. */
  2350. Vector2.prototype.add = function (otherVector) {
  2351. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2352. };
  2353. /**
  2354. * Sets the "result" coordinates with the addition of the current Vector2 and the passed one coordinates.
  2355. * Returns the Vector2.
  2356. */
  2357. Vector2.prototype.addToRef = function (otherVector, result) {
  2358. result.x = this.x + otherVector.x;
  2359. result.y = this.y + otherVector.y;
  2360. return this;
  2361. };
  2362. /**
  2363. * Set the Vector2 coordinates by adding the passed Vector2 coordinates.
  2364. * Returns the updated Vector2.
  2365. */
  2366. Vector2.prototype.addInPlace = function (otherVector) {
  2367. this.x += otherVector.x;
  2368. this.y += otherVector.y;
  2369. return this;
  2370. };
  2371. /**
  2372. * Returns a new Vector2 by adding the current Vector2 coordinates to the passed Vector3 x, y coordinates.
  2373. */
  2374. Vector2.prototype.addVector3 = function (otherVector) {
  2375. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2376. };
  2377. /**
  2378. * Returns a new Vector2 set with the subtracted coordinates of the passed one from the current Vector2.
  2379. */
  2380. Vector2.prototype.subtract = function (otherVector) {
  2381. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  2382. };
  2383. /**
  2384. * Sets the "result" coordinates with the subtraction of the passed one from the current Vector2 coordinates.
  2385. * Returns the Vector2.
  2386. */
  2387. Vector2.prototype.subtractToRef = function (otherVector, result) {
  2388. result.x = this.x - otherVector.x;
  2389. result.y = this.y - otherVector.y;
  2390. return this;
  2391. };
  2392. /**
  2393. * Sets the current Vector2 coordinates by subtracting from it the passed one coordinates.
  2394. * Returns the updated Vector2.
  2395. */
  2396. Vector2.prototype.subtractInPlace = function (otherVector) {
  2397. this.x -= otherVector.x;
  2398. this.y -= otherVector.y;
  2399. return this;
  2400. };
  2401. /**
  2402. * Multiplies in place the current Vector2 coordinates by the passed ones.
  2403. * Returns the updated Vector2.
  2404. */
  2405. Vector2.prototype.multiplyInPlace = function (otherVector) {
  2406. this.x *= otherVector.x;
  2407. this.y *= otherVector.y;
  2408. return this;
  2409. };
  2410. /**
  2411. * Returns a new Vector2 set with the multiplication of the current Vector2 and the passed one coordinates.
  2412. */
  2413. Vector2.prototype.multiply = function (otherVector) {
  2414. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  2415. };
  2416. /**
  2417. * Sets "result" coordinates with the multiplication of the current Vector2 and the passed one coordinates.
  2418. * Returns the Vector2.
  2419. */
  2420. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  2421. result.x = this.x * otherVector.x;
  2422. result.y = this.y * otherVector.y;
  2423. return this;
  2424. };
  2425. /**
  2426. * Returns a new Vector2 set with the Vector2 coordinates multiplied by the passed floats.
  2427. */
  2428. Vector2.prototype.multiplyByFloats = function (x, y) {
  2429. return new Vector2(this.x * x, this.y * y);
  2430. };
  2431. /**
  2432. * Returns a new Vector2 set with the Vector2 coordinates divided by the passed one coordinates.
  2433. */
  2434. Vector2.prototype.divide = function (otherVector) {
  2435. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  2436. };
  2437. /**
  2438. * Sets the "result" coordinates with the Vector2 divided by the passed one coordinates.
  2439. * Returns the Vector2.
  2440. */
  2441. Vector2.prototype.divideToRef = function (otherVector, result) {
  2442. result.x = this.x / otherVector.x;
  2443. result.y = this.y / otherVector.y;
  2444. return this;
  2445. };
  2446. /**
  2447. * Divides the current Vector3 coordinates by the passed ones.
  2448. * Returns the updated Vector3.
  2449. */
  2450. Vector2.prototype.divideInPlace = function (otherVector) {
  2451. return this.divideToRef(otherVector, this);
  2452. };
  2453. /**
  2454. * Returns a new Vector2 with current Vector2 negated coordinates.
  2455. */
  2456. Vector2.prototype.negate = function () {
  2457. return new Vector2(-this.x, -this.y);
  2458. };
  2459. /**
  2460. * Multiply the Vector2 coordinates by scale.
  2461. * Returns the updated Vector2.
  2462. */
  2463. Vector2.prototype.scaleInPlace = function (scale) {
  2464. this.x *= scale;
  2465. this.y *= scale;
  2466. return this;
  2467. };
  2468. /**
  2469. * Returns a new Vector2 scaled by "scale" from the current Vector2.
  2470. */
  2471. Vector2.prototype.scale = function (scale) {
  2472. return new Vector2(this.x * scale, this.y * scale);
  2473. };
  2474. /**
  2475. * Boolean : True if the passed vector coordinates strictly equal the current Vector2 ones.
  2476. */
  2477. Vector2.prototype.equals = function (otherVector) {
  2478. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  2479. };
  2480. /**
  2481. * Boolean : True if the passed vector coordinates are close to the current ones by a distance of epsilon.
  2482. */
  2483. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2484. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2485. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  2486. };
  2487. // Properties
  2488. /**
  2489. * Returns the vector length (float).
  2490. */
  2491. Vector2.prototype.length = function () {
  2492. return Math.sqrt(this.x * this.x + this.y * this.y);
  2493. };
  2494. /**
  2495. * Returns the vector squared length (float);
  2496. */
  2497. Vector2.prototype.lengthSquared = function () {
  2498. return (this.x * this.x + this.y * this.y);
  2499. };
  2500. // Methods
  2501. /**
  2502. * Normalize the vector.
  2503. * Returns the updated Vector2.
  2504. */
  2505. Vector2.prototype.normalize = function () {
  2506. var len = this.length();
  2507. if (len === 0)
  2508. return this;
  2509. var num = 1.0 / len;
  2510. this.x *= num;
  2511. this.y *= num;
  2512. return this;
  2513. };
  2514. /**
  2515. * Returns a new Vector2 copied from the Vector2.
  2516. */
  2517. Vector2.prototype.clone = function () {
  2518. return new Vector2(this.x, this.y);
  2519. };
  2520. // Statics
  2521. /**
  2522. * Returns a new Vector2(0, 0)
  2523. */
  2524. Vector2.Zero = function () {
  2525. return new Vector2(0, 0);
  2526. };
  2527. /**
  2528. * Returns a new Vector2(1, 1)
  2529. */
  2530. Vector2.One = function () {
  2531. return new Vector2(1, 1);
  2532. };
  2533. /**
  2534. * Returns a new Vector2 set from the passed index element of the passed array.
  2535. */
  2536. Vector2.FromArray = function (array, offset) {
  2537. if (offset === void 0) { offset = 0; }
  2538. return new Vector2(array[offset], array[offset + 1]);
  2539. };
  2540. /**
  2541. * Sets "result" from the passed index element of the passed array.
  2542. */
  2543. Vector2.FromArrayToRef = function (array, offset, result) {
  2544. result.x = array[offset];
  2545. result.y = array[offset + 1];
  2546. };
  2547. /**
  2548. * Retuns a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the passed four Vector2.
  2549. */
  2550. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  2551. var squared = amount * amount;
  2552. var cubed = amount * squared;
  2553. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2554. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2555. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2556. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2557. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2558. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2559. return new Vector2(x, y);
  2560. };
  2561. /**
  2562. * Returns a new Vector2 set with same the coordinates than "value" ones if the vector "value" is in the square defined by "min" and "max".
  2563. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  2564. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate.
  2565. */
  2566. Vector2.Clamp = function (value, min, max) {
  2567. var x = value.x;
  2568. x = (x > max.x) ? max.x : x;
  2569. x = (x < min.x) ? min.x : x;
  2570. var y = value.y;
  2571. y = (y > max.y) ? max.y : y;
  2572. y = (y < min.y) ? min.y : y;
  2573. return new Vector2(x, y);
  2574. };
  2575. /**
  2576. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2".
  2577. */
  2578. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2579. var squared = amount * amount;
  2580. var cubed = amount * squared;
  2581. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2582. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2583. var part3 = (cubed - (2.0 * squared)) + amount;
  2584. var part4 = cubed - squared;
  2585. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2586. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2587. return new Vector2(x, y);
  2588. };
  2589. /**
  2590. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  2591. */
  2592. Vector2.Lerp = function (start, end, amount) {
  2593. var x = start.x + ((end.x - start.x) * amount);
  2594. var y = start.y + ((end.y - start.y) * amount);
  2595. return new Vector2(x, y);
  2596. };
  2597. /**
  2598. * Returns the dot product (float) of the vector "left" and the vector "right".
  2599. */
  2600. Vector2.Dot = function (left, right) {
  2601. return left.x * right.x + left.y * right.y;
  2602. };
  2603. /**
  2604. * Returns a new Vector2 equal to the normalized passed vector.
  2605. */
  2606. Vector2.Normalize = function (vector) {
  2607. var newVector = vector.clone();
  2608. newVector.normalize();
  2609. return newVector;
  2610. };
  2611. /**
  2612. * Returns a new Vecto2 set with the minimal coordinate values from the "left" and "right" vectors.
  2613. */
  2614. Vector2.Minimize = function (left, right) {
  2615. var x = (left.x < right.x) ? left.x : right.x;
  2616. var y = (left.y < right.y) ? left.y : right.y;
  2617. return new Vector2(x, y);
  2618. };
  2619. /**
  2620. * Returns a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors.
  2621. */
  2622. Vector2.Maximize = function (left, right) {
  2623. var x = (left.x > right.x) ? left.x : right.x;
  2624. var y = (left.y > right.y) ? left.y : right.y;
  2625. return new Vector2(x, y);
  2626. };
  2627. /**
  2628. * Returns a new Vecto2 set with the transformed coordinates of the passed vector by the passed transformation matrix.
  2629. */
  2630. Vector2.Transform = function (vector, transformation) {
  2631. var r = Vector2.Zero();
  2632. Vector2.TransformToRef(vector, transformation, r);
  2633. return r;
  2634. };
  2635. /**
  2636. * Transforms the passed vector coordinates by the passed transformation matrix and stores the result in the vector "result" coordinates.
  2637. */
  2638. Vector2.TransformToRef = function (vector, transformation, result) {
  2639. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  2640. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  2641. result.x = x;
  2642. result.y = y;
  2643. };
  2644. /**
  2645. * Boolean : True if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  2646. */
  2647. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  2648. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  2649. var sign = a < 0 ? -1 : 1;
  2650. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  2651. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  2652. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  2653. };
  2654. /**
  2655. * Returns the distance (float) between the vectors "value1" and "value2".
  2656. */
  2657. Vector2.Distance = function (value1, value2) {
  2658. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  2659. };
  2660. /**
  2661. * Returns the squared distance (float) between the vectors "value1" and "value2".
  2662. */
  2663. Vector2.DistanceSquared = function (value1, value2) {
  2664. var x = value1.x - value2.x;
  2665. var y = value1.y - value2.y;
  2666. return (x * x) + (y * y);
  2667. };
  2668. /**
  2669. * Returns a new Vecto2 located at the center of the vectors "value1" and "value2".
  2670. */
  2671. Vector2.Center = function (value1, value2) {
  2672. var center = value1.add(value2);
  2673. center.scaleInPlace(0.5);
  2674. return center;
  2675. };
  2676. /**
  2677. * Returns the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  2678. */
  2679. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  2680. var l2 = Vector2.DistanceSquared(segA, segB);
  2681. if (l2 === 0.0) {
  2682. return Vector2.Distance(p, segA);
  2683. }
  2684. var v = segB.subtract(segA);
  2685. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  2686. var proj = segA.add(v.multiplyByFloats(t, t));
  2687. return Vector2.Distance(p, proj);
  2688. };
  2689. return Vector2;
  2690. }());
  2691. BABYLON.Vector2 = Vector2;
  2692. /**
  2693. * Classed used to store (x,y,z) vector representation
  2694. * A Vector3 is the main object used in 3D geometry
  2695. * It can represent etiher the coordinates of a point the space, either a direction
  2696. * Reminder: Babylon.js uses a left handed forward facing system
  2697. */
  2698. var Vector3 = /** @class */ (function () {
  2699. /**
  2700. * Creates a new Vector3 object from the passed x, y, z (floats) coordinates.
  2701. * @param x defines the first coordinates (on X axis)
  2702. * @param y defines the second coordinates (on Y axis)
  2703. * @param z defines the third coordinates (on Z axis)
  2704. */
  2705. function Vector3(
  2706. /**
  2707. * Defines the first coordinates (on X axis)
  2708. */
  2709. x,
  2710. /**
  2711. * Defines the second coordinates (on Y axis)
  2712. */
  2713. y,
  2714. /**
  2715. * Defines the third coordinates (on Z axis)
  2716. */
  2717. z) {
  2718. this.x = x;
  2719. this.y = y;
  2720. this.z = z;
  2721. }
  2722. /**
  2723. * Creates a string representation of the Vector3
  2724. * @returns a string with the Vector3 coordinates.
  2725. */
  2726. Vector3.prototype.toString = function () {
  2727. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  2728. };
  2729. /**
  2730. * Gets the class name
  2731. * @returns the string "Vector3"
  2732. */
  2733. Vector3.prototype.getClassName = function () {
  2734. return "Vector3";
  2735. };
  2736. /**
  2737. * Creates the Vector3 hash code
  2738. * @returns a number which tends to be unique between Vector3 instances
  2739. */
  2740. Vector3.prototype.getHashCode = function () {
  2741. var hash = this.x || 0;
  2742. hash = (hash * 397) ^ (this.y || 0);
  2743. hash = (hash * 397) ^ (this.z || 0);
  2744. return hash;
  2745. };
  2746. // Operators
  2747. /**
  2748. * Creates an array containing three elements : the coordinates of the Vector3
  2749. * @returns a new array of numbers
  2750. */
  2751. Vector3.prototype.asArray = function () {
  2752. var result = [];
  2753. this.toArray(result, 0);
  2754. return result;
  2755. };
  2756. /**
  2757. * Populates the passed array or Float32Array from the passed index with the successive coordinates of the Vector3
  2758. * @param array defines the destination array
  2759. * @param index defines the offset in the destination array
  2760. * @returns the current Vector3
  2761. */
  2762. Vector3.prototype.toArray = function (array, index) {
  2763. if (index === void 0) { index = 0; }
  2764. array[index] = this.x;
  2765. array[index + 1] = this.y;
  2766. array[index + 2] = this.z;
  2767. return this;
  2768. };
  2769. /**
  2770. * Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation)
  2771. * @returns a new Quaternion object, computed from the Vector3 coordinates
  2772. */
  2773. Vector3.prototype.toQuaternion = function () {
  2774. var result = new Quaternion(0.0, 0.0, 0.0, 1.0);
  2775. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  2776. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  2777. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  2778. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  2779. var cosy = Math.cos(this.y * 0.5);
  2780. var siny = Math.sin(this.y * 0.5);
  2781. result.x = coszMinusx * siny;
  2782. result.y = -sinzMinusx * siny;
  2783. result.z = sinxPlusz * cosy;
  2784. result.w = cosxPlusz * cosy;
  2785. return result;
  2786. };
  2787. /**
  2788. * Adds the passed vector to the current Vector3
  2789. * @param otherVector defines the second operand
  2790. * @returns the current updated Vector3
  2791. */
  2792. Vector3.prototype.addInPlace = function (otherVector) {
  2793. this.x += otherVector.x;
  2794. this.y += otherVector.y;
  2795. this.z += otherVector.z;
  2796. return this;
  2797. };
  2798. /**
  2799. * Gets a new Vector3, result of the addition the current Vector3 and the passed vector
  2800. * @param otherVector defines the second operand
  2801. * @returns the resulting Vector3
  2802. */
  2803. Vector3.prototype.add = function (otherVector) {
  2804. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2805. };
  2806. /**
  2807. * Adds the current Vector3 to the passed one and stores the result in the vector "result"
  2808. * @param otherVector defines the second operand
  2809. * @param result defines the Vector3 object where to store the result
  2810. * @returns the current Vector3
  2811. */
  2812. Vector3.prototype.addToRef = function (otherVector, result) {
  2813. result.x = this.x + otherVector.x;
  2814. result.y = this.y + otherVector.y;
  2815. result.z = this.z + otherVector.z;
  2816. return this;
  2817. };
  2818. /**
  2819. * Subtract the passed vector from the current Vector3
  2820. * @param otherVector defines the second operand
  2821. * @returns the current updated Vector3
  2822. */
  2823. Vector3.prototype.subtractInPlace = function (otherVector) {
  2824. this.x -= otherVector.x;
  2825. this.y -= otherVector.y;
  2826. this.z -= otherVector.z;
  2827. return this;
  2828. };
  2829. /**
  2830. * Returns a new Vector3, result of the subtraction of the passed vector from the current Vector3
  2831. * @param otherVector defines the second operand
  2832. * @returns the resulting Vector3
  2833. */
  2834. Vector3.prototype.subtract = function (otherVector) {
  2835. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2836. };
  2837. /**
  2838. * Subtracts the passed vector from the current Vector3 and stores the result in the vector "result".
  2839. * @param otherVector defines the second operand
  2840. * @param result defines the Vector3 object where to store the result
  2841. * @returns the current Vector3
  2842. */
  2843. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2844. result.x = this.x - otherVector.x;
  2845. result.y = this.y - otherVector.y;
  2846. result.z = this.z - otherVector.z;
  2847. return this;
  2848. };
  2849. /**
  2850. * Returns a new Vector3 set with the subtraction of the passed floats from the current Vector3 coordinates
  2851. * @param x defines the x coordinate of the operand
  2852. * @param y defines the y coordinate of the operand
  2853. * @param z defines the z coordinate of the operand
  2854. * @returns the resulting Vector3
  2855. */
  2856. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  2857. return new Vector3(this.x - x, this.y - y, this.z - z);
  2858. };
  2859. /**
  2860. * Subtracts the passed floats from the current Vector3 coordinates and set the passed vector "result" with this result
  2861. * @param x defines the x coordinate of the operand
  2862. * @param y defines the y coordinate of the operand
  2863. * @param z defines the z coordinate of the operand
  2864. * @param result defines the Vector3 object where to store the result
  2865. * @returns the current Vector3
  2866. */
  2867. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  2868. result.x = this.x - x;
  2869. result.y = this.y - y;
  2870. result.z = this.z - z;
  2871. return this;
  2872. };
  2873. /**
  2874. * Gets a new Vector3 set with the current Vector3 negated coordinates
  2875. * @returns a new Vector3
  2876. */
  2877. Vector3.prototype.negate = function () {
  2878. return new Vector3(-this.x, -this.y, -this.z);
  2879. };
  2880. /**
  2881. * Multiplies the Vector3 coordinates by the float "scale"
  2882. * @param scale defines the multiplier factor
  2883. * @returns the current updated Vector3
  2884. */
  2885. Vector3.prototype.scaleInPlace = function (scale) {
  2886. this.x *= scale;
  2887. this.y *= scale;
  2888. this.z *= scale;
  2889. return this;
  2890. };
  2891. /**
  2892. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale"
  2893. * @param scale defines the multiplier factor
  2894. * @returns a new Vector3
  2895. */
  2896. Vector3.prototype.scale = function (scale) {
  2897. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  2898. };
  2899. /**
  2900. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the passed vector "result" coordinates
  2901. * @param scale defines the multiplier factor
  2902. * @param result defines the Vector3 object where to store the result
  2903. * @returns the current Vector3
  2904. */
  2905. Vector3.prototype.scaleToRef = function (scale, result) {
  2906. result.x = this.x * scale;
  2907. result.y = this.y * scale;
  2908. result.z = this.z * scale;
  2909. return this;
  2910. };
  2911. /**
  2912. * Returns true if the current Vector3 and the passed vector coordinates are strictly equal
  2913. * @param otherVector defines the second operand
  2914. * @returns true if both vectors are equals
  2915. */
  2916. Vector3.prototype.equals = function (otherVector) {
  2917. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  2918. };
  2919. /**
  2920. * Returns true if the current Vector3 and the passed vector coordinates are distant less than epsilon
  2921. * @param otherVector defines the second operand
  2922. * @param epsilon defines the minimal distance to define values as equals
  2923. * @returns true if both vectors are distant less than epsilon
  2924. */
  2925. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2926. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2927. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon) && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon);
  2928. };
  2929. /**
  2930. * Returns true if the current Vector3 coordinates equals the passed floats
  2931. * @param x defines the x coordinate of the operand
  2932. * @param y defines the y coordinate of the operand
  2933. * @param z defines the z coordinate of the operand
  2934. * @returns true if both vectors are equals
  2935. */
  2936. Vector3.prototype.equalsToFloats = function (x, y, z) {
  2937. return this.x === x && this.y === y && this.z === z;
  2938. };
  2939. /**
  2940. * Multiplies the current Vector3 coordinates by the passed ones
  2941. * @param otherVector defines the second operand
  2942. * @returns the current updated Vector3
  2943. */
  2944. Vector3.prototype.multiplyInPlace = function (otherVector) {
  2945. this.x *= otherVector.x;
  2946. this.y *= otherVector.y;
  2947. this.z *= otherVector.z;
  2948. return this;
  2949. };
  2950. /**
  2951. * Returns a new Vector3, result of the multiplication of the current Vector3 by the passed vector
  2952. * @param otherVector defines the second operand
  2953. * @returns the new Vector3
  2954. */
  2955. Vector3.prototype.multiply = function (otherVector) {
  2956. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  2957. };
  2958. /**
  2959. * Multiplies the current Vector3 by the passed one and stores the result in the passed vector "result"
  2960. * @param otherVector defines the second operand
  2961. * @param result defines the Vector3 object where to store the result
  2962. * @returns the current Vector3
  2963. */
  2964. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  2965. result.x = this.x * otherVector.x;
  2966. result.y = this.y * otherVector.y;
  2967. result.z = this.z * otherVector.z;
  2968. return this;
  2969. };
  2970. /**
  2971. * Returns a new Vector3 set with the result of the mulliplication of the current Vector3 coordinates by the passed floats
  2972. * @param x defines the x coordinate of the operand
  2973. * @param y defines the y coordinate of the operand
  2974. * @param z defines the z coordinate of the operand
  2975. * @returns the new Vector3
  2976. */
  2977. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  2978. return new Vector3(this.x * x, this.y * y, this.z * z);
  2979. };
  2980. /**
  2981. * Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the passed ones
  2982. * @param otherVector defines the second operand
  2983. * @returns the new Vector3
  2984. */
  2985. Vector3.prototype.divide = function (otherVector) {
  2986. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  2987. };
  2988. /**
  2989. * Divides the current Vector3 coordinates by the passed ones and stores the result in the passed vector "result"
  2990. * @param otherVector defines the second operand
  2991. * @param result defines the Vector3 object where to store the result
  2992. * @returns the current Vector3
  2993. */
  2994. Vector3.prototype.divideToRef = function (otherVector, result) {
  2995. result.x = this.x / otherVector.x;
  2996. result.y = this.y / otherVector.y;
  2997. result.z = this.z / otherVector.z;
  2998. return this;
  2999. };
  3000. /**
  3001. * Divides the current Vector3 coordinates by the passed ones.
  3002. * @param otherVector defines the second operand
  3003. * @returns the current updated Vector3
  3004. */
  3005. Vector3.prototype.divideInPlace = function (otherVector) {
  3006. return this.divideToRef(otherVector, this);
  3007. };
  3008. /**
  3009. * Updates the current Vector3 with the minimal coordinate values between its and the passed vector ones
  3010. * @param other defines the second operand
  3011. * @returns the current updated Vector3
  3012. */
  3013. Vector3.prototype.minimizeInPlace = function (other) {
  3014. if (other.x < this.x)
  3015. this.x = other.x;
  3016. if (other.y < this.y)
  3017. this.y = other.y;
  3018. if (other.z < this.z)
  3019. this.z = other.z;
  3020. return this;
  3021. };
  3022. /**
  3023. * Updates the current Vector3 with the maximal coordinate values between its and the passed vector ones.
  3024. * @param other defines the second operand
  3025. * @returns the current updated Vector3
  3026. */
  3027. Vector3.prototype.maximizeInPlace = function (other) {
  3028. if (other.x > this.x)
  3029. this.x = other.x;
  3030. if (other.y > this.y)
  3031. this.y = other.y;
  3032. if (other.z > this.z)
  3033. this.z = other.z;
  3034. return this;
  3035. };
  3036. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  3037. /**
  3038. * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same
  3039. */
  3040. get: function () {
  3041. var absX = Math.abs(this.x);
  3042. var absY = Math.abs(this.y);
  3043. if (absX !== absY) {
  3044. return true;
  3045. }
  3046. var absZ = Math.abs(this.z);
  3047. if (absX !== absZ) {
  3048. return true;
  3049. }
  3050. if (absY !== absZ) {
  3051. return true;
  3052. }
  3053. return false;
  3054. },
  3055. enumerable: true,
  3056. configurable: true
  3057. });
  3058. // Properties
  3059. /**
  3060. * Gets the length of the Vector3
  3061. * @returns the length of the Vecto3
  3062. */
  3063. Vector3.prototype.length = function () {
  3064. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  3065. };
  3066. /**
  3067. * Gets the squared length of the Vector3
  3068. * @returns squared length of the Vector3
  3069. */
  3070. Vector3.prototype.lengthSquared = function () {
  3071. return (this.x * this.x + this.y * this.y + this.z * this.z);
  3072. };
  3073. /**
  3074. * Normalize the current Vector3.
  3075. * Please note that this is an in place operation.
  3076. * @returns the current updated Vector3
  3077. */
  3078. Vector3.prototype.normalize = function () {
  3079. var len = this.length();
  3080. if (len === 0 || len === 1.0)
  3081. return this;
  3082. var num = 1.0 / len;
  3083. this.x *= num;
  3084. this.y *= num;
  3085. this.z *= num;
  3086. return this;
  3087. };
  3088. /**
  3089. * Normalize the current Vector3 to a new vector
  3090. * @returns the new Vector3
  3091. */
  3092. Vector3.prototype.normalizeToNew = function () {
  3093. var normalized = new Vector3(0, 0, 0);
  3094. this.normalizeToRef(normalized);
  3095. return normalized;
  3096. };
  3097. /**
  3098. * Normalize the current Vector3 to the reference
  3099. * @param reference define the Vector3 to update
  3100. * @returns the updated Vector3
  3101. */
  3102. Vector3.prototype.normalizeToRef = function (reference) {
  3103. var len = this.length();
  3104. if (len === 0 || len === 1.0) {
  3105. reference.set(this.x, this.y, this.z);
  3106. return reference;
  3107. }
  3108. var scale = 1.0 / len;
  3109. this.scaleToRef(scale, reference);
  3110. return reference;
  3111. };
  3112. /**
  3113. * Creates a new Vector3 copied from the current Vector3
  3114. * @returns the new Vector3
  3115. */
  3116. Vector3.prototype.clone = function () {
  3117. return new Vector3(this.x, this.y, this.z);
  3118. };
  3119. /**
  3120. * Copies the passed vector coordinates to the current Vector3 ones
  3121. * @param source defines the source Vector3
  3122. * @returns the current updated Vector3
  3123. */
  3124. Vector3.prototype.copyFrom = function (source) {
  3125. this.x = source.x;
  3126. this.y = source.y;
  3127. this.z = source.z;
  3128. return this;
  3129. };
  3130. /**
  3131. * Copies the passed floats to the current Vector3 coordinates
  3132. * @param x defines the x coordinate of the operand
  3133. * @param y defines the y coordinate of the operand
  3134. * @param z defines the z coordinate of the operand
  3135. * @returns the current updated Vector3
  3136. */
  3137. Vector3.prototype.copyFromFloats = function (x, y, z) {
  3138. this.x = x;
  3139. this.y = y;
  3140. this.z = z;
  3141. return this;
  3142. };
  3143. /**
  3144. * Copies the passed floats to the current Vector3 coordinates
  3145. * @param x defines the x coordinate of the operand
  3146. * @param y defines the y coordinate of the operand
  3147. * @param z defines the z coordinate of the operand
  3148. * @returns the current updated Vector3
  3149. */
  3150. Vector3.prototype.set = function (x, y, z) {
  3151. return this.copyFromFloats(x, y, z);
  3152. };
  3153. // Statics
  3154. /**
  3155. * Get the clip factor between two vectors
  3156. * @param vector0 defines the first operand
  3157. * @param vector1 defines the second operand
  3158. * @param axis defines the axis to use
  3159. * @param size defines the size along the axis
  3160. * @returns the clip factor
  3161. */
  3162. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  3163. var d0 = Vector3.Dot(vector0, axis) - size;
  3164. var d1 = Vector3.Dot(vector1, axis) - size;
  3165. var s = d0 / (d0 - d1);
  3166. return s;
  3167. };
  3168. /**
  3169. * Get angle between two vectors
  3170. * @param vector0 angle between vector0 and vector1
  3171. * @param vector1 angle between vector0 and vector1
  3172. * @param normal direction of the normal
  3173. * @return the angle between vector0 and vector1
  3174. */
  3175. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  3176. var v0 = vector0.clone().normalize();
  3177. var v1 = vector1.clone().normalize();
  3178. var dot = Vector3.Dot(v0, v1);
  3179. var n = Vector3.Cross(v0, v1);
  3180. if (Vector3.Dot(n, normal) > 0) {
  3181. return Math.acos(dot);
  3182. }
  3183. return -Math.acos(dot);
  3184. };
  3185. /**
  3186. * Returns a new Vector3 set from the index "offset" of the passed array
  3187. * @param array defines the source array
  3188. * @param offset defines the offset in the source array
  3189. * @returns the new Vector3
  3190. */
  3191. Vector3.FromArray = function (array, offset) {
  3192. if (!offset) {
  3193. offset = 0;
  3194. }
  3195. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  3196. };
  3197. /**
  3198. * Returns a new Vector3 set from the index "offset" of the passed Float32Array
  3199. * This function is deprecated. Use FromArray instead
  3200. * @param array defines the source array
  3201. * @param offset defines the offset in the source array
  3202. * @returns the new Vector3
  3203. */
  3204. Vector3.FromFloatArray = function (array, offset) {
  3205. return Vector3.FromArray(array, offset);
  3206. };
  3207. /**
  3208. * Sets the passed vector "result" with the element values from the index "offset" of the passed array
  3209. * @param array defines the source array
  3210. * @param offset defines the offset in the source array
  3211. * @param result defines the Vector3 where to store the result
  3212. */
  3213. Vector3.FromArrayToRef = function (array, offset, result) {
  3214. result.x = array[offset];
  3215. result.y = array[offset + 1];
  3216. result.z = array[offset + 2];
  3217. };
  3218. /**
  3219. * Sets the passed vector "result" with the element values from the index "offset" of the passed Float32Array
  3220. * This function is deprecated. Use FromArrayToRef instead.
  3221. * @param array defines the source array
  3222. * @param offset defines the offset in the source array
  3223. * @param result defines the Vector3 where to store the result
  3224. */
  3225. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  3226. return Vector3.FromArrayToRef(array, offset, result);
  3227. };
  3228. /**
  3229. * Sets the passed vector "result" with the passed floats.
  3230. * @param x defines the x coordinate of the source
  3231. * @param y defines the y coordinate of the source
  3232. * @param z defines the z coordinate of the source
  3233. * @param result defines the Vector3 where to store the result
  3234. */
  3235. Vector3.FromFloatsToRef = function (x, y, z, result) {
  3236. result.x = x;
  3237. result.y = y;
  3238. result.z = z;
  3239. };
  3240. /**
  3241. * Returns a new Vector3 set to (0.0, 0.0, 0.0)
  3242. * @returns a new empty Vector3
  3243. */
  3244. Vector3.Zero = function () {
  3245. return new Vector3(0.0, 0.0, 0.0);
  3246. };
  3247. /**
  3248. * Returns a new Vector3 set to (1.0, 1.0, 1.0)
  3249. * @returns a new unit Vector3
  3250. */
  3251. Vector3.One = function () {
  3252. return new Vector3(1.0, 1.0, 1.0);
  3253. };
  3254. /**
  3255. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  3256. * @returns a new up Vector3
  3257. */
  3258. Vector3.Up = function () {
  3259. return new Vector3(0.0, 1.0, 0.0);
  3260. };
  3261. /**
  3262. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  3263. * @returns a new forward Vector3
  3264. */
  3265. Vector3.Forward = function () {
  3266. return new Vector3(0.0, 0.0, 1.0);
  3267. };
  3268. /**
  3269. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  3270. * @returns a new right Vector3
  3271. */
  3272. Vector3.Right = function () {
  3273. return new Vector3(1.0, 0.0, 0.0);
  3274. };
  3275. /**
  3276. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  3277. * @returns a new left Vector3
  3278. */
  3279. Vector3.Left = function () {
  3280. return new Vector3(-1.0, 0.0, 0.0);
  3281. };
  3282. /**
  3283. * Returns a new Vector3 set with the result of the transformation by the passed matrix of the passed vector.
  3284. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3285. * @param vector defines the Vector3 to transform
  3286. * @param transformation defines the transformation matrix
  3287. * @returns the transformed Vector3
  3288. */
  3289. Vector3.TransformCoordinates = function (vector, transformation) {
  3290. var result = Vector3.Zero();
  3291. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  3292. return result;
  3293. };
  3294. /**
  3295. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed vector
  3296. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3297. * @param vector defines the Vector3 to transform
  3298. * @param transformation defines the transformation matrix
  3299. * @param result defines the Vector3 where to store the result
  3300. */
  3301. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  3302. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  3303. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  3304. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  3305. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  3306. result.x = x / w;
  3307. result.y = y / w;
  3308. result.z = z / w;
  3309. };
  3310. /**
  3311. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed floats (x, y, z)
  3312. * This method computes tranformed coordinates only, not transformed direction vectors
  3313. * @param x define the x coordinate of the source vector
  3314. * @param y define the y coordinate of the source vector
  3315. * @param z define the z coordinate of the source vector
  3316. * @param transformation defines the transformation matrix
  3317. * @param result defines the Vector3 where to store the result
  3318. */
  3319. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  3320. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  3321. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  3322. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  3323. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  3324. result.x = rx / rw;
  3325. result.y = ry / rw;
  3326. result.z = rz / rw;
  3327. };
  3328. /**
  3329. * Returns a new Vector3 set with the result of the normal transformation by the passed matrix of the passed vector
  3330. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3331. * @param vector defines the Vector3 to transform
  3332. * @param transformation defines the transformation matrix
  3333. * @returns the new Vector3
  3334. */
  3335. Vector3.TransformNormal = function (vector, transformation) {
  3336. var result = Vector3.Zero();
  3337. Vector3.TransformNormalToRef(vector, transformation, result);
  3338. return result;
  3339. };
  3340. /**
  3341. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector
  3342. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3343. * @param vector defines the Vector3 to transform
  3344. * @param transformation defines the transformation matrix
  3345. * @param result defines the Vector3 where to store the result
  3346. */
  3347. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  3348. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3349. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3350. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3351. result.x = x;
  3352. result.y = y;
  3353. result.z = z;
  3354. };
  3355. /**
  3356. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z)
  3357. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3358. * @param x define the x coordinate of the source vector
  3359. * @param y define the y coordinate of the source vector
  3360. * @param z define the z coordinate of the source vector
  3361. * @param transformation defines the transformation matrix
  3362. * @param result defines the Vector3 where to store the result
  3363. */
  3364. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  3365. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3366. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3367. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3368. };
  3369. /**
  3370. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4"
  3371. * @param value1 defines the first control point
  3372. * @param value2 defines the second control point
  3373. * @param value3 defines the third control point
  3374. * @param value4 defines the fourth control point
  3375. * @param amount defines the amount on the spline to use
  3376. * @returns the new Vector3
  3377. */
  3378. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  3379. var squared = amount * amount;
  3380. var cubed = amount * squared;
  3381. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  3382. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  3383. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  3384. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  3385. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  3386. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  3387. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  3388. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  3389. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  3390. return new Vector3(x, y, z);
  3391. };
  3392. /**
  3393. * Returns a new Vector3 set with the coordinates of "value", if the vector "value" is in the cube defined by the vectors "min" and "max"
  3394. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  3395. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  3396. * @param value defines the current value
  3397. * @param min defines the lower range value
  3398. * @param max defines the upper range value
  3399. * @returns the new Vector3
  3400. */
  3401. Vector3.Clamp = function (value, min, max) {
  3402. var x = value.x;
  3403. x = (x > max.x) ? max.x : x;
  3404. x = (x < min.x) ? min.x : x;
  3405. var y = value.y;
  3406. y = (y > max.y) ? max.y : y;
  3407. y = (y < min.y) ? min.y : y;
  3408. var z = value.z;
  3409. z = (z > max.z) ? max.z : z;
  3410. z = (z < min.z) ? min.z : z;
  3411. return new Vector3(x, y, z);
  3412. };
  3413. /**
  3414. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
  3415. * @param value1 defines the first control point
  3416. * @param tangent1 defines the first tangent vector
  3417. * @param value2 defines the second control point
  3418. * @param tangent2 defines the second tangent vector
  3419. * @param amount defines the amount on the interpolation spline (between 0 and 1)
  3420. * @returns the new Vector3
  3421. */
  3422. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3423. var squared = amount * amount;
  3424. var cubed = amount * squared;
  3425. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3426. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3427. var part3 = (cubed - (2.0 * squared)) + amount;
  3428. var part4 = cubed - squared;
  3429. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3430. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3431. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3432. return new Vector3(x, y, z);
  3433. };
  3434. /**
  3435. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end"
  3436. * @param start defines the start value
  3437. * @param end defines the end value
  3438. * @param amount max defines amount between both (between 0 and 1)
  3439. * @returns the new Vector3
  3440. */
  3441. Vector3.Lerp = function (start, end, amount) {
  3442. var result = new Vector3(0, 0, 0);
  3443. Vector3.LerpToRef(start, end, amount, result);
  3444. return result;
  3445. };
  3446. /**
  3447. * Sets the passed vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
  3448. * @param start defines the start value
  3449. * @param end defines the end value
  3450. * @param amount max defines amount between both (between 0 and 1)
  3451. * @param result defines the Vector3 where to store the result
  3452. */
  3453. Vector3.LerpToRef = function (start, end, amount, result) {
  3454. result.x = start.x + ((end.x - start.x) * amount);
  3455. result.y = start.y + ((end.y - start.y) * amount);
  3456. result.z = start.z + ((end.z - start.z) * amount);
  3457. };
  3458. /**
  3459. * Returns the dot product (float) between the vectors "left" and "right"
  3460. * @param left defines the left operand
  3461. * @param right defines the right operand
  3462. * @returns the dot product
  3463. */
  3464. Vector3.Dot = function (left, right) {
  3465. return (left.x * right.x + left.y * right.y + left.z * right.z);
  3466. };
  3467. /**
  3468. * Returns a new Vector3 as the cross product of the vectors "left" and "right"
  3469. * The cross product is then orthogonal to both "left" and "right"
  3470. * @param left defines the left operand
  3471. * @param right defines the right operand
  3472. * @returns the cross product
  3473. */
  3474. Vector3.Cross = function (left, right) {
  3475. var result = Vector3.Zero();
  3476. Vector3.CrossToRef(left, right, result);
  3477. return result;
  3478. };
  3479. /**
  3480. * Sets the passed vector "result" with the cross product of "left" and "right"
  3481. * The cross product is then orthogonal to both "left" and "right"
  3482. * @param left defines the left operand
  3483. * @param right defines the right operand
  3484. * @param result defines the Vector3 where to store the result
  3485. */
  3486. Vector3.CrossToRef = function (left, right, result) {
  3487. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  3488. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  3489. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  3490. result.copyFrom(MathTmp.Vector3[0]);
  3491. };
  3492. /**
  3493. * Returns a new Vector3 as the normalization of the passed vector
  3494. * @param vector defines the Vector3 to normalize
  3495. * @returns the new Vector3
  3496. */
  3497. Vector3.Normalize = function (vector) {
  3498. var result = Vector3.Zero();
  3499. Vector3.NormalizeToRef(vector, result);
  3500. return result;
  3501. };
  3502. /**
  3503. * Sets the passed vector "result" with the normalization of the passed first vector
  3504. * @param vector defines the Vector3 to normalize
  3505. * @param result defines the Vector3 where to store the result
  3506. */
  3507. Vector3.NormalizeToRef = function (vector, result) {
  3508. result.copyFrom(vector);
  3509. result.normalize();
  3510. };
  3511. /**
  3512. * Project a Vector3 onto screen space
  3513. * @param vector defines the Vector3 to project
  3514. * @param world defines the world matrix to use
  3515. * @param transform defines the transform (view x projection) matrix to use
  3516. * @param viewport defines the screen viewport to use
  3517. * @returns the new Vector3
  3518. */
  3519. Vector3.Project = function (vector, world, transform, viewport) {
  3520. var cw = viewport.width;
  3521. var ch = viewport.height;
  3522. var cx = viewport.x;
  3523. var cy = viewport.y;
  3524. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  3525. Matrix.FromValuesToRef(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, 0.5, 0, cx + cw / 2.0, ch / 2.0 + cy, 0.5, 1, viewportMatrix);
  3526. var matrix = MathTmp.Matrix[0];
  3527. world.multiplyToRef(transform, matrix);
  3528. matrix.multiplyToRef(viewportMatrix, matrix);
  3529. return Vector3.TransformCoordinates(vector, matrix);
  3530. };
  3531. /**
  3532. * Unproject from screen space to object space
  3533. * @param source defines the screen space Vector3 to use
  3534. * @param viewportWidth defines the current width of the viewport
  3535. * @param viewportHeight defines the current height of the viewport
  3536. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3537. * @param transform defines the transform (view x projection) matrix to use
  3538. * @returns the new Vector3
  3539. */
  3540. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  3541. var matrix = MathTmp.Matrix[0];
  3542. world.multiplyToRef(transform, matrix);
  3543. matrix.invert();
  3544. source.x = source.x / viewportWidth * 2 - 1;
  3545. source.y = -(source.y / viewportHeight * 2 - 1);
  3546. var vector = Vector3.TransformCoordinates(source, matrix);
  3547. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  3548. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3549. vector = vector.scale(1.0 / num);
  3550. }
  3551. return vector;
  3552. };
  3553. /**
  3554. * Unproject from screen space to object space
  3555. * @param source defines the screen space Vector3 to use
  3556. * @param viewportWidth defines the current width of the viewport
  3557. * @param viewportHeight defines the current height of the viewport
  3558. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3559. * @param view defines the view matrix to use
  3560. * @param projection defines the projection matrix to use
  3561. * @returns the new Vector3
  3562. */
  3563. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  3564. var result = Vector3.Zero();
  3565. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  3566. return result;
  3567. };
  3568. /**
  3569. * Unproject from screen space to object space
  3570. * @param source defines the screen space Vector3 to use
  3571. * @param viewportWidth defines the current width of the viewport
  3572. * @param viewportHeight defines the current height of the viewport
  3573. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3574. * @param view defines the view matrix to use
  3575. * @param projection defines the projection matrix to use
  3576. * @param result defines the Vector3 where to store the result
  3577. */
  3578. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  3579. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  3580. };
  3581. /**
  3582. * Unproject from screen space to object space
  3583. * @param sourceX defines the screen space x coordinate to use
  3584. * @param sourceY defines the screen space y coordinate to use
  3585. * @param sourceZ defines the screen space z coordinate to use
  3586. * @param viewportWidth defines the current width of the viewport
  3587. * @param viewportHeight defines the current height of the viewport
  3588. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3589. * @param view defines the view matrix to use
  3590. * @param projection defines the projection matrix to use
  3591. * @param result defines the Vector3 where to store the result
  3592. */
  3593. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  3594. var matrix = MathTmp.Matrix[0];
  3595. world.multiplyToRef(view, matrix);
  3596. matrix.multiplyToRef(projection, matrix);
  3597. matrix.invert();
  3598. var screenSource = MathTmp.Vector3[0];
  3599. screenSource.x = sourceX / viewportWidth * 2 - 1;
  3600. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  3601. screenSource.z = 2 * sourceZ - 1.0;
  3602. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  3603. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  3604. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3605. result.scaleInPlace(1.0 / num);
  3606. }
  3607. };
  3608. /**
  3609. * Gets the minimal coordinate values between two Vector3
  3610. * @param left defines the first operand
  3611. * @param right defines the second operand
  3612. * @returns the new Vector3
  3613. */
  3614. Vector3.Minimize = function (left, right) {
  3615. var min = left.clone();
  3616. min.minimizeInPlace(right);
  3617. return min;
  3618. };
  3619. /**
  3620. * Gets the maximal coordinate values between two Vector3
  3621. * @param left defines the first operand
  3622. * @param right defines the second operand
  3623. * @returns the new Vector3
  3624. */
  3625. Vector3.Maximize = function (left, right) {
  3626. var max = left.clone();
  3627. max.maximizeInPlace(right);
  3628. return max;
  3629. };
  3630. /**
  3631. * Returns the distance between the vectors "value1" and "value2"
  3632. * @param value1 defines the first operand
  3633. * @param value2 defines the second operand
  3634. * @returns the distance
  3635. */
  3636. Vector3.Distance = function (value1, value2) {
  3637. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  3638. };
  3639. /**
  3640. * Returns the squared distance between the vectors "value1" and "value2"
  3641. * @param value1 defines the first operand
  3642. * @param value2 defines the second operand
  3643. * @returns the squared distance
  3644. */
  3645. Vector3.DistanceSquared = function (value1, value2) {
  3646. var x = value1.x - value2.x;
  3647. var y = value1.y - value2.y;
  3648. var z = value1.z - value2.z;
  3649. return (x * x) + (y * y) + (z * z);
  3650. };
  3651. /**
  3652. * Returns a new Vector3 located at the center between "value1" and "value2"
  3653. * @param value1 defines the first operand
  3654. * @param value2 defines the second operand
  3655. * @returns the new Vector3
  3656. */
  3657. Vector3.Center = function (value1, value2) {
  3658. var center = value1.add(value2);
  3659. center.scaleInPlace(0.5);
  3660. return center;
  3661. };
  3662. /**
  3663. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  3664. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  3665. * to something in order to rotate it from its local system to the given target system
  3666. * Note: axis1, axis2 and axis3 are normalized during this operation
  3667. * @param axis1 defines the first axis
  3668. * @param axis2 defines the second axis
  3669. * @param axis3 defines the third axis
  3670. * @returns a new Vector3
  3671. */
  3672. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  3673. var rotation = Vector3.Zero();
  3674. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  3675. return rotation;
  3676. };
  3677. /**
  3678. * The same than RotationFromAxis but updates the passed ref Vector3 parameter instead of returning a new Vector3
  3679. * @param axis1 defines the first axis
  3680. * @param axis2 defines the second axis
  3681. * @param axis3 defines the third axis
  3682. * @param ref defines the Vector3 where to store the result
  3683. */
  3684. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3685. var quat = MathTmp.Quaternion[0];
  3686. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3687. quat.toEulerAnglesToRef(ref);
  3688. };
  3689. return Vector3;
  3690. }());
  3691. BABYLON.Vector3 = Vector3;
  3692. //Vector4 class created for EulerAngle class conversion to Quaternion
  3693. var Vector4 = /** @class */ (function () {
  3694. /**
  3695. * Creates a Vector4 object from the passed floats.
  3696. */
  3697. function Vector4(x, y, z, w) {
  3698. this.x = x;
  3699. this.y = y;
  3700. this.z = z;
  3701. this.w = w;
  3702. }
  3703. /**
  3704. * Returns the string with the Vector4 coordinates.
  3705. */
  3706. Vector4.prototype.toString = function () {
  3707. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3708. };
  3709. /**
  3710. * Returns the string "Vector4".
  3711. */
  3712. Vector4.prototype.getClassName = function () {
  3713. return "Vector4";
  3714. };
  3715. /**
  3716. * Returns the Vector4 hash code.
  3717. */
  3718. Vector4.prototype.getHashCode = function () {
  3719. var hash = this.x || 0;
  3720. hash = (hash * 397) ^ (this.y || 0);
  3721. hash = (hash * 397) ^ (this.z || 0);
  3722. hash = (hash * 397) ^ (this.w || 0);
  3723. return hash;
  3724. };
  3725. // Operators
  3726. /**
  3727. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  3728. */
  3729. Vector4.prototype.asArray = function () {
  3730. var result = new Array();
  3731. this.toArray(result, 0);
  3732. return result;
  3733. };
  3734. /**
  3735. * Populates the passed array from the passed index with the Vector4 coordinates.
  3736. * Returns the Vector4.
  3737. */
  3738. Vector4.prototype.toArray = function (array, index) {
  3739. if (index === undefined) {
  3740. index = 0;
  3741. }
  3742. array[index] = this.x;
  3743. array[index + 1] = this.y;
  3744. array[index + 2] = this.z;
  3745. array[index + 3] = this.w;
  3746. return this;
  3747. };
  3748. /**
  3749. * Adds the passed vector to the current Vector4.
  3750. * Returns the updated Vector4.
  3751. */
  3752. Vector4.prototype.addInPlace = function (otherVector) {
  3753. this.x += otherVector.x;
  3754. this.y += otherVector.y;
  3755. this.z += otherVector.z;
  3756. this.w += otherVector.w;
  3757. return this;
  3758. };
  3759. /**
  3760. * Returns a new Vector4 as the result of the addition of the current Vector4 and the passed one.
  3761. */
  3762. Vector4.prototype.add = function (otherVector) {
  3763. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  3764. };
  3765. /**
  3766. * Updates the passed vector "result" with the result of the addition of the current Vector4 and the passed one.
  3767. * Returns the current Vector4.
  3768. */
  3769. Vector4.prototype.addToRef = function (otherVector, result) {
  3770. result.x = this.x + otherVector.x;
  3771. result.y = this.y + otherVector.y;
  3772. result.z = this.z + otherVector.z;
  3773. result.w = this.w + otherVector.w;
  3774. return this;
  3775. };
  3776. /**
  3777. * Subtract in place the passed vector from the current Vector4.
  3778. * Returns the updated Vector4.
  3779. */
  3780. Vector4.prototype.subtractInPlace = function (otherVector) {
  3781. this.x -= otherVector.x;
  3782. this.y -= otherVector.y;
  3783. this.z -= otherVector.z;
  3784. this.w -= otherVector.w;
  3785. return this;
  3786. };
  3787. /**
  3788. * Returns a new Vector4 with the result of the subtraction of the passed vector from the current Vector4.
  3789. */
  3790. Vector4.prototype.subtract = function (otherVector) {
  3791. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  3792. };
  3793. /**
  3794. * Sets the passed vector "result" with the result of the subtraction of the passed vector from the current Vector4.
  3795. * Returns the current Vector4.
  3796. */
  3797. Vector4.prototype.subtractToRef = function (otherVector, result) {
  3798. result.x = this.x - otherVector.x;
  3799. result.y = this.y - otherVector.y;
  3800. result.z = this.z - otherVector.z;
  3801. result.w = this.w - otherVector.w;
  3802. return this;
  3803. };
  3804. /**
  3805. * Returns a new Vector4 set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  3806. */
  3807. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  3808. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  3809. };
  3810. /**
  3811. * Sets the passed vector "result" set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  3812. * Returns the current Vector4.
  3813. */
  3814. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  3815. result.x = this.x - x;
  3816. result.y = this.y - y;
  3817. result.z = this.z - z;
  3818. result.w = this.w - w;
  3819. return this;
  3820. };
  3821. /**
  3822. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  3823. */
  3824. Vector4.prototype.negate = function () {
  3825. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  3826. };
  3827. /**
  3828. * Multiplies the current Vector4 coordinates by scale (float).
  3829. * Returns the updated Vector4.
  3830. */
  3831. Vector4.prototype.scaleInPlace = function (scale) {
  3832. this.x *= scale;
  3833. this.y *= scale;
  3834. this.z *= scale;
  3835. this.w *= scale;
  3836. return this;
  3837. };
  3838. /**
  3839. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  3840. */
  3841. Vector4.prototype.scale = function (scale) {
  3842. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  3843. };
  3844. /**
  3845. * Sets the passed vector "result" with the current Vector4 coordinates multiplied by scale (float).
  3846. * Returns the current Vector4.
  3847. */
  3848. Vector4.prototype.scaleToRef = function (scale, result) {
  3849. result.x = this.x * scale;
  3850. result.y = this.y * scale;
  3851. result.z = this.z * scale;
  3852. result.w = this.w * scale;
  3853. return this;
  3854. };
  3855. /**
  3856. * Boolean : True if the current Vector4 coordinates are stricly equal to the passed ones.
  3857. */
  3858. Vector4.prototype.equals = function (otherVector) {
  3859. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  3860. };
  3861. /**
  3862. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the passed vector ones.
  3863. */
  3864. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3865. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3866. return otherVector
  3867. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  3868. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  3869. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  3870. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  3871. };
  3872. /**
  3873. * Boolean : True if the passed floats are strictly equal to the current Vector4 coordinates.
  3874. */
  3875. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  3876. return this.x === x && this.y === y && this.z === z && this.w === w;
  3877. };
  3878. /**
  3879. * Multiplies in place the current Vector4 by the passed one.
  3880. * Returns the updated Vector4.
  3881. */
  3882. Vector4.prototype.multiplyInPlace = function (otherVector) {
  3883. this.x *= otherVector.x;
  3884. this.y *= otherVector.y;
  3885. this.z *= otherVector.z;
  3886. this.w *= otherVector.w;
  3887. return this;
  3888. };
  3889. /**
  3890. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the passed one.
  3891. */
  3892. Vector4.prototype.multiply = function (otherVector) {
  3893. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  3894. };
  3895. /**
  3896. * Updates the passed vector "result" with the multiplication result of the current Vector4 and the passed one.
  3897. * Returns the current Vector4.
  3898. */
  3899. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  3900. result.x = this.x * otherVector.x;
  3901. result.y = this.y * otherVector.y;
  3902. result.z = this.z * otherVector.z;
  3903. result.w = this.w * otherVector.w;
  3904. return this;
  3905. };
  3906. /**
  3907. * Returns a new Vector4 set with the multiplication result of the passed floats and the current Vector4 coordinates.
  3908. */
  3909. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  3910. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  3911. };
  3912. /**
  3913. * Returns a new Vector4 set with the division result of the current Vector4 by the passed one.
  3914. */
  3915. Vector4.prototype.divide = function (otherVector) {
  3916. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  3917. };
  3918. /**
  3919. * Updates the passed vector "result" with the division result of the current Vector4 by the passed one.
  3920. * Returns the current Vector4.
  3921. */
  3922. Vector4.prototype.divideToRef = function (otherVector, result) {
  3923. result.x = this.x / otherVector.x;
  3924. result.y = this.y / otherVector.y;
  3925. result.z = this.z / otherVector.z;
  3926. result.w = this.w / otherVector.w;
  3927. return this;
  3928. };
  3929. /**
  3930. * Divides the current Vector3 coordinates by the passed ones.
  3931. * @returns the updated Vector3.
  3932. */
  3933. Vector4.prototype.divideInPlace = function (otherVector) {
  3934. return this.divideToRef(otherVector, this);
  3935. };
  3936. /**
  3937. * Updates the Vector4 coordinates with the minimum values between its own and the passed vector ones
  3938. * @param other defines the second operand
  3939. * @returns the current updated Vector4
  3940. */
  3941. Vector4.prototype.minimizeInPlace = function (other) {
  3942. if (other.x < this.x)
  3943. this.x = other.x;
  3944. if (other.y < this.y)
  3945. this.y = other.y;
  3946. if (other.z < this.z)
  3947. this.z = other.z;
  3948. if (other.w < this.w)
  3949. this.w = other.w;
  3950. return this;
  3951. };
  3952. /**
  3953. * Updates the Vector4 coordinates with the maximum values between its own and the passed vector ones
  3954. * @param other defines the second operand
  3955. * @returns the current updated Vector4
  3956. */
  3957. Vector4.prototype.maximizeInPlace = function (other) {
  3958. if (other.x > this.x)
  3959. this.x = other.x;
  3960. if (other.y > this.y)
  3961. this.y = other.y;
  3962. if (other.z > this.z)
  3963. this.z = other.z;
  3964. if (other.w > this.w)
  3965. this.w = other.w;
  3966. return this;
  3967. };
  3968. // Properties
  3969. /**
  3970. * Returns the Vector4 length (float).
  3971. */
  3972. Vector4.prototype.length = function () {
  3973. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  3974. };
  3975. /**
  3976. * Returns the Vector4 squared length (float).
  3977. */
  3978. Vector4.prototype.lengthSquared = function () {
  3979. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  3980. };
  3981. // Methods
  3982. /**
  3983. * Normalizes in place the Vector4.
  3984. * Returns the updated Vector4.
  3985. */
  3986. Vector4.prototype.normalize = function () {
  3987. var len = this.length();
  3988. if (len === 0)
  3989. return this;
  3990. var num = 1.0 / len;
  3991. this.x *= num;
  3992. this.y *= num;
  3993. this.z *= num;
  3994. this.w *= num;
  3995. return this;
  3996. };
  3997. /**
  3998. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  3999. */
  4000. Vector4.prototype.toVector3 = function () {
  4001. return new Vector3(this.x, this.y, this.z);
  4002. };
  4003. /**
  4004. * Returns a new Vector4 copied from the current one.
  4005. */
  4006. Vector4.prototype.clone = function () {
  4007. return new Vector4(this.x, this.y, this.z, this.w);
  4008. };
  4009. /**
  4010. * Updates the current Vector4 with the passed one coordinates.
  4011. * Returns the updated Vector4.
  4012. */
  4013. Vector4.prototype.copyFrom = function (source) {
  4014. this.x = source.x;
  4015. this.y = source.y;
  4016. this.z = source.z;
  4017. this.w = source.w;
  4018. return this;
  4019. };
  4020. /**
  4021. * Updates the current Vector4 coordinates with the passed floats.
  4022. * Returns the updated Vector4.
  4023. */
  4024. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  4025. this.x = x;
  4026. this.y = y;
  4027. this.z = z;
  4028. this.w = w;
  4029. return this;
  4030. };
  4031. /**
  4032. * Updates the current Vector4 coordinates with the passed floats.
  4033. * Returns the updated Vector4.
  4034. */
  4035. Vector4.prototype.set = function (x, y, z, w) {
  4036. return this.copyFromFloats(x, y, z, w);
  4037. };
  4038. // Statics
  4039. /**
  4040. * Returns a new Vector4 set from the starting index of the passed array.
  4041. */
  4042. Vector4.FromArray = function (array, offset) {
  4043. if (!offset) {
  4044. offset = 0;
  4045. }
  4046. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4047. };
  4048. /**
  4049. * Updates the passed vector "result" from the starting index of the passed array.
  4050. */
  4051. Vector4.FromArrayToRef = function (array, offset, result) {
  4052. result.x = array[offset];
  4053. result.y = array[offset + 1];
  4054. result.z = array[offset + 2];
  4055. result.w = array[offset + 3];
  4056. };
  4057. /**
  4058. * Updates the passed vector "result" from the starting index of the passed Float32Array.
  4059. */
  4060. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  4061. Vector4.FromArrayToRef(array, offset, result);
  4062. };
  4063. /**
  4064. * Updates the passed vector "result" coordinates from the passed floats.
  4065. */
  4066. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  4067. result.x = x;
  4068. result.y = y;
  4069. result.z = z;
  4070. result.w = w;
  4071. };
  4072. /**
  4073. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  4074. */
  4075. Vector4.Zero = function () {
  4076. return new Vector4(0.0, 0.0, 0.0, 0.0);
  4077. };
  4078. /**
  4079. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  4080. */
  4081. Vector4.One = function () {
  4082. return new Vector4(1.0, 1.0, 1.0, 1.0);
  4083. };
  4084. /**
  4085. * Returns a new normalized Vector4 from the passed one.
  4086. */
  4087. Vector4.Normalize = function (vector) {
  4088. var result = Vector4.Zero();
  4089. Vector4.NormalizeToRef(vector, result);
  4090. return result;
  4091. };
  4092. /**
  4093. * Updates the passed vector "result" from the normalization of the passed one.
  4094. */
  4095. Vector4.NormalizeToRef = function (vector, result) {
  4096. result.copyFrom(vector);
  4097. result.normalize();
  4098. };
  4099. Vector4.Minimize = function (left, right) {
  4100. var min = left.clone();
  4101. min.minimizeInPlace(right);
  4102. return min;
  4103. };
  4104. Vector4.Maximize = function (left, right) {
  4105. var max = left.clone();
  4106. max.maximizeInPlace(right);
  4107. return max;
  4108. };
  4109. /**
  4110. * Returns the distance (float) between the vectors "value1" and "value2".
  4111. */
  4112. Vector4.Distance = function (value1, value2) {
  4113. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  4114. };
  4115. /**
  4116. * Returns the squared distance (float) between the vectors "value1" and "value2".
  4117. */
  4118. Vector4.DistanceSquared = function (value1, value2) {
  4119. var x = value1.x - value2.x;
  4120. var y = value1.y - value2.y;
  4121. var z = value1.z - value2.z;
  4122. var w = value1.w - value2.w;
  4123. return (x * x) + (y * y) + (z * z) + (w * w);
  4124. };
  4125. /**
  4126. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  4127. */
  4128. Vector4.Center = function (value1, value2) {
  4129. var center = value1.add(value2);
  4130. center.scaleInPlace(0.5);
  4131. return center;
  4132. };
  4133. /**
  4134. * Returns a new Vector4 set with the result of the normal transformation by the passed matrix of the passed vector.
  4135. * This methods computes transformed normalized direction vectors only.
  4136. */
  4137. Vector4.TransformNormal = function (vector, transformation) {
  4138. var result = Vector4.Zero();
  4139. Vector4.TransformNormalToRef(vector, transformation, result);
  4140. return result;
  4141. };
  4142. /**
  4143. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  4144. * This methods computes transformed normalized direction vectors only.
  4145. */
  4146. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  4147. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  4148. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  4149. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  4150. result.x = x;
  4151. result.y = y;
  4152. result.z = z;
  4153. result.w = vector.w;
  4154. };
  4155. /**
  4156. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z, w).
  4157. * This methods computes transformed normalized direction vectors only.
  4158. */
  4159. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  4160. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  4161. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  4162. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  4163. result.w = w;
  4164. };
  4165. return Vector4;
  4166. }());
  4167. BABYLON.Vector4 = Vector4;
  4168. var Size = /** @class */ (function () {
  4169. /**
  4170. * Creates a Size object from the passed width and height (floats).
  4171. */
  4172. function Size(width, height) {
  4173. this.width = width;
  4174. this.height = height;
  4175. }
  4176. // Returns a string with the Size width and height.
  4177. Size.prototype.toString = function () {
  4178. return "{W: " + this.width + ", H: " + this.height + "}";
  4179. };
  4180. /**
  4181. * Returns the string "Size"
  4182. */
  4183. Size.prototype.getClassName = function () {
  4184. return "Size";
  4185. };
  4186. /**
  4187. * Returns the Size hash code.
  4188. */
  4189. Size.prototype.getHashCode = function () {
  4190. var hash = this.width || 0;
  4191. hash = (hash * 397) ^ (this.height || 0);
  4192. return hash;
  4193. };
  4194. /**
  4195. * Updates the current size from the passed one.
  4196. * Returns the updated Size.
  4197. */
  4198. Size.prototype.copyFrom = function (src) {
  4199. this.width = src.width;
  4200. this.height = src.height;
  4201. };
  4202. /**
  4203. * Updates in place the current Size from the passed floats.
  4204. * Returns the updated Size.
  4205. */
  4206. Size.prototype.copyFromFloats = function (width, height) {
  4207. this.width = width;
  4208. this.height = height;
  4209. return this;
  4210. };
  4211. /**
  4212. * Updates in place the current Size from the passed floats.
  4213. * Returns the updated Size.
  4214. */
  4215. Size.prototype.set = function (width, height) {
  4216. return this.copyFromFloats(width, height);
  4217. };
  4218. /**
  4219. * Returns a new Size set with the multiplication result of the current Size and the passed floats.
  4220. */
  4221. Size.prototype.multiplyByFloats = function (w, h) {
  4222. return new Size(this.width * w, this.height * h);
  4223. };
  4224. /**
  4225. * Returns a new Size copied from the passed one.
  4226. */
  4227. Size.prototype.clone = function () {
  4228. return new Size(this.width, this.height);
  4229. };
  4230. /**
  4231. * Boolean : True if the current Size and the passed one width and height are strictly equal.
  4232. */
  4233. Size.prototype.equals = function (other) {
  4234. if (!other) {
  4235. return false;
  4236. }
  4237. return (this.width === other.width) && (this.height === other.height);
  4238. };
  4239. Object.defineProperty(Size.prototype, "surface", {
  4240. /**
  4241. * Returns the surface of the Size : width * height (float).
  4242. */
  4243. get: function () {
  4244. return this.width * this.height;
  4245. },
  4246. enumerable: true,
  4247. configurable: true
  4248. });
  4249. /**
  4250. * Returns a new Size set to (0.0, 0.0)
  4251. */
  4252. Size.Zero = function () {
  4253. return new Size(0.0, 0.0);
  4254. };
  4255. /**
  4256. * Returns a new Size set as the addition result of the current Size and the passed one.
  4257. */
  4258. Size.prototype.add = function (otherSize) {
  4259. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  4260. return r;
  4261. };
  4262. /**
  4263. * Returns a new Size set as the subtraction result of the passed one from the current Size.
  4264. */
  4265. Size.prototype.subtract = function (otherSize) {
  4266. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  4267. return r;
  4268. };
  4269. /**
  4270. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  4271. */
  4272. Size.Lerp = function (start, end, amount) {
  4273. var w = start.width + ((end.width - start.width) * amount);
  4274. var h = start.height + ((end.height - start.height) * amount);
  4275. return new Size(w, h);
  4276. };
  4277. return Size;
  4278. }());
  4279. BABYLON.Size = Size;
  4280. var Quaternion = /** @class */ (function () {
  4281. /**
  4282. * Creates a new Quaternion from the passed floats.
  4283. */
  4284. function Quaternion(x, y, z, w) {
  4285. if (x === void 0) { x = 0.0; }
  4286. if (y === void 0) { y = 0.0; }
  4287. if (z === void 0) { z = 0.0; }
  4288. if (w === void 0) { w = 1.0; }
  4289. this.x = x;
  4290. this.y = y;
  4291. this.z = z;
  4292. this.w = w;
  4293. }
  4294. /**
  4295. * Returns a string with the Quaternion coordinates.
  4296. */
  4297. Quaternion.prototype.toString = function () {
  4298. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  4299. };
  4300. /**
  4301. * Returns the string "Quaternion".
  4302. */
  4303. Quaternion.prototype.getClassName = function () {
  4304. return "Quaternion";
  4305. };
  4306. /**
  4307. * Returns the Quaternion hash code.
  4308. */
  4309. Quaternion.prototype.getHashCode = function () {
  4310. var hash = this.x || 0;
  4311. hash = (hash * 397) ^ (this.y || 0);
  4312. hash = (hash * 397) ^ (this.z || 0);
  4313. hash = (hash * 397) ^ (this.w || 0);
  4314. return hash;
  4315. };
  4316. /**
  4317. * Returns a new array populated with 4 elements : the Quaternion coordinates.
  4318. */
  4319. Quaternion.prototype.asArray = function () {
  4320. return [this.x, this.y, this.z, this.w];
  4321. };
  4322. /**
  4323. * Boolean : True if the current Quaterion and the passed one coordinates are strictly equal.
  4324. */
  4325. Quaternion.prototype.equals = function (otherQuaternion) {
  4326. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  4327. };
  4328. /**
  4329. * Returns a new Quaternion copied from the current one.
  4330. */
  4331. Quaternion.prototype.clone = function () {
  4332. return new Quaternion(this.x, this.y, this.z, this.w);
  4333. };
  4334. /**
  4335. * Updates the current Quaternion from the passed one coordinates.
  4336. * Returns the updated Quaterion.
  4337. */
  4338. Quaternion.prototype.copyFrom = function (other) {
  4339. this.x = other.x;
  4340. this.y = other.y;
  4341. this.z = other.z;
  4342. this.w = other.w;
  4343. return this;
  4344. };
  4345. /**
  4346. * Updates the current Quaternion from the passed float coordinates.
  4347. * Returns the updated Quaterion.
  4348. */
  4349. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  4350. this.x = x;
  4351. this.y = y;
  4352. this.z = z;
  4353. this.w = w;
  4354. return this;
  4355. };
  4356. /**
  4357. * Updates the current Quaternion from the passed float coordinates.
  4358. * Returns the updated Quaterion.
  4359. */
  4360. Quaternion.prototype.set = function (x, y, z, w) {
  4361. return this.copyFromFloats(x, y, z, w);
  4362. };
  4363. /**
  4364. * Returns a new Quaternion as the addition result of the passed one and the current Quaternion.
  4365. */
  4366. Quaternion.prototype.add = function (other) {
  4367. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  4368. };
  4369. /**
  4370. * Returns a new Quaternion as the subtraction result of the passed one from the current Quaternion.
  4371. */
  4372. Quaternion.prototype.subtract = function (other) {
  4373. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  4374. };
  4375. /**
  4376. * Returns a new Quaternion set by multiplying the current Quaterion coordinates by the float "scale".
  4377. */
  4378. Quaternion.prototype.scale = function (value) {
  4379. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  4380. };
  4381. /**
  4382. * Returns a new Quaternion set as the quaternion mulplication result of the current one with the passed one "q1".
  4383. */
  4384. Quaternion.prototype.multiply = function (q1) {
  4385. var result = new Quaternion(0, 0, 0, 1.0);
  4386. this.multiplyToRef(q1, result);
  4387. return result;
  4388. };
  4389. /**
  4390. * Sets the passed "result" as the quaternion mulplication result of the current one with the passed one "q1".
  4391. * Returns the current Quaternion.
  4392. */
  4393. Quaternion.prototype.multiplyToRef = function (q1, result) {
  4394. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  4395. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  4396. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  4397. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  4398. result.copyFromFloats(x, y, z, w);
  4399. return this;
  4400. };
  4401. /**
  4402. * Updates the current Quaternion with the quaternion mulplication result of itself with the passed one "q1".
  4403. * Returns the updated Quaternion.
  4404. */
  4405. Quaternion.prototype.multiplyInPlace = function (q1) {
  4406. this.multiplyToRef(q1, this);
  4407. return this;
  4408. };
  4409. /**
  4410. * Sets the passed "ref" with the conjugation of the current Quaternion.
  4411. * Returns the current Quaternion.
  4412. */
  4413. Quaternion.prototype.conjugateToRef = function (ref) {
  4414. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  4415. return this;
  4416. };
  4417. /**
  4418. * Conjugates in place the current Quaternion.
  4419. * Returns the updated Quaternion.
  4420. */
  4421. Quaternion.prototype.conjugateInPlace = function () {
  4422. this.x *= -1;
  4423. this.y *= -1;
  4424. this.z *= -1;
  4425. return this;
  4426. };
  4427. /**
  4428. * Returns a new Quaternion as the conjugate of the current Quaternion.
  4429. */
  4430. Quaternion.prototype.conjugate = function () {
  4431. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  4432. return result;
  4433. };
  4434. /**
  4435. * Returns the Quaternion length (float).
  4436. */
  4437. Quaternion.prototype.length = function () {
  4438. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  4439. };
  4440. /**
  4441. * Normalize in place the current Quaternion.
  4442. * Returns the updated Quaternion.
  4443. */
  4444. Quaternion.prototype.normalize = function () {
  4445. var length = 1.0 / this.length();
  4446. this.x *= length;
  4447. this.y *= length;
  4448. this.z *= length;
  4449. this.w *= length;
  4450. return this;
  4451. };
  4452. /**
  4453. * Returns a new Vector3 set with the Euler angles translated from the current Quaternion.
  4454. */
  4455. Quaternion.prototype.toEulerAngles = function (order) {
  4456. if (order === void 0) { order = "YZX"; }
  4457. var result = Vector3.Zero();
  4458. this.toEulerAnglesToRef(result, order);
  4459. return result;
  4460. };
  4461. /**
  4462. * Sets the passed vector3 "result" with the Euler angles translated from the current Quaternion.
  4463. * Returns the current Quaternion.
  4464. */
  4465. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  4466. if (order === void 0) { order = "YZX"; }
  4467. var qz = this.z;
  4468. var qx = this.x;
  4469. var qy = this.y;
  4470. var qw = this.w;
  4471. var sqw = qw * qw;
  4472. var sqz = qz * qz;
  4473. var sqx = qx * qx;
  4474. var sqy = qy * qy;
  4475. var zAxisY = qy * qz - qx * qw;
  4476. var limit = .4999999;
  4477. if (zAxisY < -limit) {
  4478. result.y = 2 * Math.atan2(qy, qw);
  4479. result.x = Math.PI / 2;
  4480. result.z = 0;
  4481. }
  4482. else if (zAxisY > limit) {
  4483. result.y = 2 * Math.atan2(qy, qw);
  4484. result.x = -Math.PI / 2;
  4485. result.z = 0;
  4486. }
  4487. else {
  4488. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  4489. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  4490. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  4491. }
  4492. return this;
  4493. };
  4494. /**
  4495. * Updates the passed rotation matrix with the current Quaternion values.
  4496. * Returns the current Quaternion.
  4497. */
  4498. Quaternion.prototype.toRotationMatrix = function (result) {
  4499. var xx = this.x * this.x;
  4500. var yy = this.y * this.y;
  4501. var zz = this.z * this.z;
  4502. var xy = this.x * this.y;
  4503. var zw = this.z * this.w;
  4504. var zx = this.z * this.x;
  4505. var yw = this.y * this.w;
  4506. var yz = this.y * this.z;
  4507. var xw = this.x * this.w;
  4508. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4509. result.m[1] = 2.0 * (xy + zw);
  4510. result.m[2] = 2.0 * (zx - yw);
  4511. result.m[3] = 0;
  4512. result.m[4] = 2.0 * (xy - zw);
  4513. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4514. result.m[6] = 2.0 * (yz + xw);
  4515. result.m[7] = 0;
  4516. result.m[8] = 2.0 * (zx + yw);
  4517. result.m[9] = 2.0 * (yz - xw);
  4518. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4519. result.m[11] = 0;
  4520. result.m[12] = 0;
  4521. result.m[13] = 0;
  4522. result.m[14] = 0;
  4523. result.m[15] = 1.0;
  4524. result._markAsUpdated();
  4525. return this;
  4526. };
  4527. /**
  4528. * Updates the current Quaternion from the passed rotation matrix values.
  4529. * Returns the updated Quaternion.
  4530. */
  4531. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  4532. Quaternion.FromRotationMatrixToRef(matrix, this);
  4533. return this;
  4534. };
  4535. // Statics
  4536. /**
  4537. * Returns a new Quaternion set from the passed rotation matrix values.
  4538. */
  4539. Quaternion.FromRotationMatrix = function (matrix) {
  4540. var result = new Quaternion();
  4541. Quaternion.FromRotationMatrixToRef(matrix, result);
  4542. return result;
  4543. };
  4544. /**
  4545. * Updates the passed quaternion "result" with the passed rotation matrix values.
  4546. */
  4547. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  4548. var data = matrix.m;
  4549. var m11 = data[0], m12 = data[4], m13 = data[8];
  4550. var m21 = data[1], m22 = data[5], m23 = data[9];
  4551. var m31 = data[2], m32 = data[6], m33 = data[10];
  4552. var trace = m11 + m22 + m33;
  4553. var s;
  4554. if (trace > 0) {
  4555. s = 0.5 / Math.sqrt(trace + 1.0);
  4556. result.w = 0.25 / s;
  4557. result.x = (m32 - m23) * s;
  4558. result.y = (m13 - m31) * s;
  4559. result.z = (m21 - m12) * s;
  4560. }
  4561. else if (m11 > m22 && m11 > m33) {
  4562. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  4563. result.w = (m32 - m23) / s;
  4564. result.x = 0.25 * s;
  4565. result.y = (m12 + m21) / s;
  4566. result.z = (m13 + m31) / s;
  4567. }
  4568. else if (m22 > m33) {
  4569. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  4570. result.w = (m13 - m31) / s;
  4571. result.x = (m12 + m21) / s;
  4572. result.y = 0.25 * s;
  4573. result.z = (m23 + m32) / s;
  4574. }
  4575. else {
  4576. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  4577. result.w = (m21 - m12) / s;
  4578. result.x = (m13 + m31) / s;
  4579. result.y = (m23 + m32) / s;
  4580. result.z = 0.25 * s;
  4581. }
  4582. };
  4583. /**
  4584. * Returns a new Quaternion set to (0.0, 0.0, 0.0).
  4585. */
  4586. Quaternion.Zero = function () {
  4587. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  4588. };
  4589. /**
  4590. * Returns a new Quaternion as the inverted current Quaternion.
  4591. */
  4592. Quaternion.Inverse = function (q) {
  4593. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  4594. };
  4595. /**
  4596. * Returns the identity Quaternion.
  4597. */
  4598. Quaternion.Identity = function () {
  4599. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  4600. };
  4601. Quaternion.IsIdentity = function (quaternion) {
  4602. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  4603. };
  4604. /**
  4605. * Returns a new Quaternion set from the passed axis (Vector3) and angle in radians (float).
  4606. */
  4607. Quaternion.RotationAxis = function (axis, angle) {
  4608. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  4609. };
  4610. /**
  4611. * Sets the passed quaternion "result" from the passed axis (Vector3) and angle in radians (float).
  4612. */
  4613. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  4614. var sin = Math.sin(angle / 2);
  4615. axis.normalize();
  4616. result.w = Math.cos(angle / 2);
  4617. result.x = axis.x * sin;
  4618. result.y = axis.y * sin;
  4619. result.z = axis.z * sin;
  4620. return result;
  4621. };
  4622. /**
  4623. * Retuns a new Quaternion set from the starting index of the passed array.
  4624. */
  4625. Quaternion.FromArray = function (array, offset) {
  4626. if (!offset) {
  4627. offset = 0;
  4628. }
  4629. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4630. };
  4631. /**
  4632. * Returns a new Quaternion set from the passed Euler float angles (y, x, z).
  4633. */
  4634. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  4635. var q = new Quaternion();
  4636. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  4637. return q;
  4638. };
  4639. /**
  4640. * Sets the passed quaternion "result" from the passed float Euler angles (y, x, z).
  4641. */
  4642. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  4643. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  4644. var halfRoll = roll * 0.5;
  4645. var halfPitch = pitch * 0.5;
  4646. var halfYaw = yaw * 0.5;
  4647. var sinRoll = Math.sin(halfRoll);
  4648. var cosRoll = Math.cos(halfRoll);
  4649. var sinPitch = Math.sin(halfPitch);
  4650. var cosPitch = Math.cos(halfPitch);
  4651. var sinYaw = Math.sin(halfYaw);
  4652. var cosYaw = Math.cos(halfYaw);
  4653. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  4654. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  4655. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  4656. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  4657. };
  4658. /**
  4659. * Returns a new Quaternion from the passed float Euler angles expressed in z-x-z orientation
  4660. */
  4661. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  4662. var result = new Quaternion();
  4663. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  4664. return result;
  4665. };
  4666. /**
  4667. * Sets the passed quaternion "result" from the passed float Euler angles expressed in z-x-z orientation
  4668. */
  4669. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  4670. // Produces a quaternion from Euler angles in the z-x-z orientation
  4671. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  4672. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  4673. var halfBeta = beta * 0.5;
  4674. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4675. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4676. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4677. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4678. };
  4679. /**
  4680. * Returns a new Quaternion as the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  4681. * cf to Vector3.RotationFromAxis() documentation.
  4682. * Note : axis1, axis2 and axis3 are normalized during this operation.
  4683. */
  4684. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3, ref) {
  4685. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  4686. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  4687. return quat;
  4688. };
  4689. /**
  4690. * Sets the passed quaternion "ref" with the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  4691. * cf to Vector3.RotationFromAxis() documentation.
  4692. * Note : axis1, axis2 and axis3 are normalized during this operation.
  4693. */
  4694. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  4695. var rotMat = MathTmp.Matrix[0];
  4696. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  4697. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  4698. };
  4699. Quaternion.Slerp = function (left, right, amount) {
  4700. var result = Quaternion.Identity();
  4701. Quaternion.SlerpToRef(left, right, amount, result);
  4702. return result;
  4703. };
  4704. Quaternion.SlerpToRef = function (left, right, amount, result) {
  4705. var num2;
  4706. var num3;
  4707. var num = amount;
  4708. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  4709. var flag = false;
  4710. if (num4 < 0) {
  4711. flag = true;
  4712. num4 = -num4;
  4713. }
  4714. if (num4 > 0.999999) {
  4715. num3 = 1 - num;
  4716. num2 = flag ? -num : num;
  4717. }
  4718. else {
  4719. var num5 = Math.acos(num4);
  4720. var num6 = (1.0 / Math.sin(num5));
  4721. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  4722. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  4723. }
  4724. result.x = (num3 * left.x) + (num2 * right.x);
  4725. result.y = (num3 * left.y) + (num2 * right.y);
  4726. result.z = (num3 * left.z) + (num2 * right.z);
  4727. result.w = (num3 * left.w) + (num2 * right.w);
  4728. };
  4729. /**
  4730. * Returns a new Quaternion located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  4731. */
  4732. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  4733. var squared = amount * amount;
  4734. var cubed = amount * squared;
  4735. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  4736. var part2 = (-2.0 * cubed) + (3.0 * squared);
  4737. var part3 = (cubed - (2.0 * squared)) + amount;
  4738. var part4 = cubed - squared;
  4739. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  4740. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  4741. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  4742. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  4743. return new Quaternion(x, y, z, w);
  4744. };
  4745. return Quaternion;
  4746. }());
  4747. BABYLON.Quaternion = Quaternion;
  4748. var Matrix = /** @class */ (function () {
  4749. function Matrix() {
  4750. this._isIdentity = false;
  4751. this._isIdentityDirty = true;
  4752. this.m = new Float32Array(16);
  4753. this._markAsUpdated();
  4754. }
  4755. Matrix.prototype._markAsUpdated = function () {
  4756. this.updateFlag = Matrix._updateFlagSeed++;
  4757. this._isIdentityDirty = true;
  4758. };
  4759. // Properties
  4760. /**
  4761. * Boolean : True is the matrix is the identity matrix
  4762. */
  4763. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  4764. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  4765. if (this._isIdentityDirty) {
  4766. this._isIdentityDirty = false;
  4767. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  4768. this._isIdentity = false;
  4769. }
  4770. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  4771. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  4772. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  4773. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  4774. this._isIdentity = false;
  4775. }
  4776. else {
  4777. this._isIdentity = true;
  4778. }
  4779. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  4780. this._isIdentity = false;
  4781. }
  4782. }
  4783. return this._isIdentity;
  4784. };
  4785. /**
  4786. * Returns the matrix determinant (float).
  4787. */
  4788. Matrix.prototype.determinant = function () {
  4789. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  4790. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  4791. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  4792. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  4793. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  4794. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  4795. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  4796. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  4797. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  4798. };
  4799. // Methods
  4800. /**
  4801. * Returns the matrix underlying array.
  4802. */
  4803. Matrix.prototype.toArray = function () {
  4804. return this.m;
  4805. };
  4806. /**
  4807. * Returns the matrix underlying array.
  4808. */
  4809. Matrix.prototype.asArray = function () {
  4810. return this.toArray();
  4811. };
  4812. /**
  4813. * Inverts in place the Matrix.
  4814. * Returns the Matrix inverted.
  4815. */
  4816. Matrix.prototype.invert = function () {
  4817. this.invertToRef(this);
  4818. return this;
  4819. };
  4820. /**
  4821. * Sets all the matrix elements to zero.
  4822. * Returns the Matrix.
  4823. */
  4824. Matrix.prototype.reset = function () {
  4825. for (var index = 0; index < 16; index++) {
  4826. this.m[index] = 0.0;
  4827. }
  4828. this._markAsUpdated();
  4829. return this;
  4830. };
  4831. /**
  4832. * Returns a new Matrix as the addition result of the current Matrix and the passed one.
  4833. */
  4834. Matrix.prototype.add = function (other) {
  4835. var result = new Matrix();
  4836. this.addToRef(other, result);
  4837. return result;
  4838. };
  4839. /**
  4840. * Sets the passed matrix "result" with the ddition result of the current Matrix and the passed one.
  4841. * Returns the Matrix.
  4842. */
  4843. Matrix.prototype.addToRef = function (other, result) {
  4844. for (var index = 0; index < 16; index++) {
  4845. result.m[index] = this.m[index] + other.m[index];
  4846. }
  4847. result._markAsUpdated();
  4848. return this;
  4849. };
  4850. /**
  4851. * Adds in place the passed matrix to the current Matrix.
  4852. * Returns the updated Matrix.
  4853. */
  4854. Matrix.prototype.addToSelf = function (other) {
  4855. for (var index = 0; index < 16; index++) {
  4856. this.m[index] += other.m[index];
  4857. }
  4858. this._markAsUpdated();
  4859. return this;
  4860. };
  4861. /**
  4862. * Sets the passed matrix with the current inverted Matrix.
  4863. * Returns the unmodified current Matrix.
  4864. */
  4865. Matrix.prototype.invertToRef = function (other) {
  4866. var l1 = this.m[0];
  4867. var l2 = this.m[1];
  4868. var l3 = this.m[2];
  4869. var l4 = this.m[3];
  4870. var l5 = this.m[4];
  4871. var l6 = this.m[5];
  4872. var l7 = this.m[6];
  4873. var l8 = this.m[7];
  4874. var l9 = this.m[8];
  4875. var l10 = this.m[9];
  4876. var l11 = this.m[10];
  4877. var l12 = this.m[11];
  4878. var l13 = this.m[12];
  4879. var l14 = this.m[13];
  4880. var l15 = this.m[14];
  4881. var l16 = this.m[15];
  4882. var l17 = (l11 * l16) - (l12 * l15);
  4883. var l18 = (l10 * l16) - (l12 * l14);
  4884. var l19 = (l10 * l15) - (l11 * l14);
  4885. var l20 = (l9 * l16) - (l12 * l13);
  4886. var l21 = (l9 * l15) - (l11 * l13);
  4887. var l22 = (l9 * l14) - (l10 * l13);
  4888. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  4889. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  4890. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  4891. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  4892. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  4893. var l28 = (l7 * l16) - (l8 * l15);
  4894. var l29 = (l6 * l16) - (l8 * l14);
  4895. var l30 = (l6 * l15) - (l7 * l14);
  4896. var l31 = (l5 * l16) - (l8 * l13);
  4897. var l32 = (l5 * l15) - (l7 * l13);
  4898. var l33 = (l5 * l14) - (l6 * l13);
  4899. var l34 = (l7 * l12) - (l8 * l11);
  4900. var l35 = (l6 * l12) - (l8 * l10);
  4901. var l36 = (l6 * l11) - (l7 * l10);
  4902. var l37 = (l5 * l12) - (l8 * l9);
  4903. var l38 = (l5 * l11) - (l7 * l9);
  4904. var l39 = (l5 * l10) - (l6 * l9);
  4905. other.m[0] = l23 * l27;
  4906. other.m[4] = l24 * l27;
  4907. other.m[8] = l25 * l27;
  4908. other.m[12] = l26 * l27;
  4909. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  4910. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  4911. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  4912. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  4913. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  4914. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  4915. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  4916. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  4917. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  4918. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  4919. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  4920. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  4921. other._markAsUpdated();
  4922. return this;
  4923. };
  4924. /**
  4925. * Inserts the translation vector (using 3 x floats) in the current Matrix.
  4926. * Returns the updated Matrix.
  4927. */
  4928. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  4929. this.m[12] = x;
  4930. this.m[13] = y;
  4931. this.m[14] = z;
  4932. this._markAsUpdated();
  4933. return this;
  4934. };
  4935. /**
  4936. * Inserts the translation vector in the current Matrix.
  4937. * Returns the updated Matrix.
  4938. */
  4939. Matrix.prototype.setTranslation = function (vector3) {
  4940. this.m[12] = vector3.x;
  4941. this.m[13] = vector3.y;
  4942. this.m[14] = vector3.z;
  4943. this._markAsUpdated();
  4944. return this;
  4945. };
  4946. /**
  4947. * Returns a new Vector3 as the extracted translation from the Matrix.
  4948. */
  4949. Matrix.prototype.getTranslation = function () {
  4950. return new Vector3(this.m[12], this.m[13], this.m[14]);
  4951. };
  4952. /**
  4953. * Fill a Vector3 with the extracted translation from the Matrix.
  4954. */
  4955. Matrix.prototype.getTranslationToRef = function (result) {
  4956. result.x = this.m[12];
  4957. result.y = this.m[13];
  4958. result.z = this.m[14];
  4959. return this;
  4960. };
  4961. /**
  4962. * Remove rotation and scaling part from the Matrix.
  4963. * Returns the updated Matrix.
  4964. */
  4965. Matrix.prototype.removeRotationAndScaling = function () {
  4966. this.setRowFromFloats(0, 1, 0, 0, 0);
  4967. this.setRowFromFloats(1, 0, 1, 0, 0);
  4968. this.setRowFromFloats(2, 0, 0, 1, 0);
  4969. return this;
  4970. };
  4971. /**
  4972. * Returns a new Matrix set with the multiplication result of the current Matrix and the passed one.
  4973. */
  4974. Matrix.prototype.multiply = function (other) {
  4975. var result = new Matrix();
  4976. this.multiplyToRef(other, result);
  4977. return result;
  4978. };
  4979. /**
  4980. * Updates the current Matrix from the passed one values.
  4981. * Returns the updated Matrix.
  4982. */
  4983. Matrix.prototype.copyFrom = function (other) {
  4984. for (var index = 0; index < 16; index++) {
  4985. this.m[index] = other.m[index];
  4986. }
  4987. this._markAsUpdated();
  4988. return this;
  4989. };
  4990. /**
  4991. * Populates the passed array from the starting index with the Matrix values.
  4992. * Returns the Matrix.
  4993. */
  4994. Matrix.prototype.copyToArray = function (array, offset) {
  4995. if (offset === void 0) { offset = 0; }
  4996. for (var index = 0; index < 16; index++) {
  4997. array[offset + index] = this.m[index];
  4998. }
  4999. return this;
  5000. };
  5001. /**
  5002. * Sets the passed matrix "result" with the multiplication result of the current Matrix and the passed one.
  5003. */
  5004. Matrix.prototype.multiplyToRef = function (other, result) {
  5005. this.multiplyToArray(other, result.m, 0);
  5006. result._markAsUpdated();
  5007. return this;
  5008. };
  5009. /**
  5010. * Sets the Float32Array "result" from the passed index "offset" with the multiplication result of the current Matrix and the passed one.
  5011. */
  5012. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  5013. var tm0 = this.m[0];
  5014. var tm1 = this.m[1];
  5015. var tm2 = this.m[2];
  5016. var tm3 = this.m[3];
  5017. var tm4 = this.m[4];
  5018. var tm5 = this.m[5];
  5019. var tm6 = this.m[6];
  5020. var tm7 = this.m[7];
  5021. var tm8 = this.m[8];
  5022. var tm9 = this.m[9];
  5023. var tm10 = this.m[10];
  5024. var tm11 = this.m[11];
  5025. var tm12 = this.m[12];
  5026. var tm13 = this.m[13];
  5027. var tm14 = this.m[14];
  5028. var tm15 = this.m[15];
  5029. var om0 = other.m[0];
  5030. var om1 = other.m[1];
  5031. var om2 = other.m[2];
  5032. var om3 = other.m[3];
  5033. var om4 = other.m[4];
  5034. var om5 = other.m[5];
  5035. var om6 = other.m[6];
  5036. var om7 = other.m[7];
  5037. var om8 = other.m[8];
  5038. var om9 = other.m[9];
  5039. var om10 = other.m[10];
  5040. var om11 = other.m[11];
  5041. var om12 = other.m[12];
  5042. var om13 = other.m[13];
  5043. var om14 = other.m[14];
  5044. var om15 = other.m[15];
  5045. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  5046. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  5047. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  5048. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  5049. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  5050. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  5051. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  5052. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  5053. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  5054. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  5055. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  5056. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  5057. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  5058. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  5059. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  5060. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  5061. return this;
  5062. };
  5063. /**
  5064. * Boolean : True is the current Matrix and the passed one values are strictly equal.
  5065. */
  5066. Matrix.prototype.equals = function (value) {
  5067. return value &&
  5068. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  5069. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  5070. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  5071. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  5072. };
  5073. /**
  5074. * Returns a new Matrix from the current Matrix.
  5075. */
  5076. Matrix.prototype.clone = function () {
  5077. return Matrix.FromValues(this.m[0], this.m[1], this.m[2], this.m[3], this.m[4], this.m[5], this.m[6], this.m[7], this.m[8], this.m[9], this.m[10], this.m[11], this.m[12], this.m[13], this.m[14], this.m[15]);
  5078. };
  5079. /**
  5080. * Returns the string "Matrix"
  5081. */
  5082. Matrix.prototype.getClassName = function () {
  5083. return "Matrix";
  5084. };
  5085. /**
  5086. * Returns the Matrix hash code.
  5087. */
  5088. Matrix.prototype.getHashCode = function () {
  5089. var hash = this.m[0] || 0;
  5090. for (var i = 1; i < 16; i++) {
  5091. hash = (hash * 397) ^ (this.m[i] || 0);
  5092. }
  5093. return hash;
  5094. };
  5095. /**
  5096. * Decomposes the current Matrix into :
  5097. * - a scale vector3 passed as a reference to update,
  5098. * - a rotation quaternion passed as a reference to update,
  5099. * - a translation vector3 passed as a reference to update.
  5100. * Returns the true if operation was successful.
  5101. */
  5102. Matrix.prototype.decompose = function (scale, rotation, translation) {
  5103. translation.x = this.m[12];
  5104. translation.y = this.m[13];
  5105. translation.z = this.m[14];
  5106. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  5107. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  5108. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  5109. if (this.determinant() <= 0) {
  5110. scale.y *= -1;
  5111. }
  5112. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  5113. rotation.x = 0;
  5114. rotation.y = 0;
  5115. rotation.z = 0;
  5116. rotation.w = 1;
  5117. return false;
  5118. }
  5119. Matrix.FromValuesToRef(this.m[0] / scale.x, this.m[1] / scale.x, this.m[2] / scale.x, 0, this.m[4] / scale.y, this.m[5] / scale.y, this.m[6] / scale.y, 0, this.m[8] / scale.z, this.m[9] / scale.z, this.m[10] / scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[0]);
  5120. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  5121. return true;
  5122. };
  5123. /**
  5124. * Writes to the given matrix a normal matrix, computed from this one (using values from identity matrix for fourth row and column).
  5125. * @param ref matrix to store the result
  5126. */
  5127. Matrix.prototype.toNormalMatrix = function (ref) {
  5128. this.invertToRef(ref);
  5129. ref.transpose();
  5130. var m = ref.m;
  5131. Matrix.FromValuesToRef(m[0], m[1], m[2], 0, m[4], m[5], m[6], 0, m[8], m[9], m[10], 0, 0, 0, 0, 1, ref);
  5132. };
  5133. /**
  5134. * Returns a new Matrix as the extracted rotation matrix from the current one.
  5135. */
  5136. Matrix.prototype.getRotationMatrix = function () {
  5137. var result = Matrix.Identity();
  5138. this.getRotationMatrixToRef(result);
  5139. return result;
  5140. };
  5141. /**
  5142. * Extracts the rotation matrix from the current one and sets it as the passed "result".
  5143. * Returns the current Matrix.
  5144. */
  5145. Matrix.prototype.getRotationMatrixToRef = function (result) {
  5146. var m = this.m;
  5147. var xs = m[0] * m[1] * m[2] * m[3] < 0 ? -1 : 1;
  5148. var ys = m[4] * m[5] * m[6] * m[7] < 0 ? -1 : 1;
  5149. var zs = m[8] * m[9] * m[10] * m[11] < 0 ? -1 : 1;
  5150. var sx = xs * Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  5151. var sy = ys * Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  5152. var sz = zs * Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  5153. Matrix.FromValuesToRef(m[0] / sx, m[1] / sx, m[2] / sx, 0, m[4] / sy, m[5] / sy, m[6] / sy, 0, m[8] / sz, m[9] / sz, m[10] / sz, 0, 0, 0, 0, 1, result);
  5154. return this;
  5155. };
  5156. // Statics
  5157. /**
  5158. * Returns a new Matrix set from the starting index of the passed array.
  5159. */
  5160. Matrix.FromArray = function (array, offset) {
  5161. var result = new Matrix();
  5162. if (!offset) {
  5163. offset = 0;
  5164. }
  5165. Matrix.FromArrayToRef(array, offset, result);
  5166. return result;
  5167. };
  5168. /**
  5169. * Sets the passed "result" matrix from the starting index of the passed array.
  5170. */
  5171. Matrix.FromArrayToRef = function (array, offset, result) {
  5172. for (var index = 0; index < 16; index++) {
  5173. result.m[index] = array[index + offset];
  5174. }
  5175. result._markAsUpdated();
  5176. };
  5177. /**
  5178. * Sets the passed "result" matrix from the starting index of the passed Float32Array by multiplying each element by the float "scale".
  5179. */
  5180. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  5181. for (var index = 0; index < 16; index++) {
  5182. result.m[index] = array[index + offset] * scale;
  5183. }
  5184. result._markAsUpdated();
  5185. };
  5186. /**
  5187. * Sets the passed matrix "result" with the 16 passed floats.
  5188. */
  5189. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  5190. result.m[0] = initialM11;
  5191. result.m[1] = initialM12;
  5192. result.m[2] = initialM13;
  5193. result.m[3] = initialM14;
  5194. result.m[4] = initialM21;
  5195. result.m[5] = initialM22;
  5196. result.m[6] = initialM23;
  5197. result.m[7] = initialM24;
  5198. result.m[8] = initialM31;
  5199. result.m[9] = initialM32;
  5200. result.m[10] = initialM33;
  5201. result.m[11] = initialM34;
  5202. result.m[12] = initialM41;
  5203. result.m[13] = initialM42;
  5204. result.m[14] = initialM43;
  5205. result.m[15] = initialM44;
  5206. result._markAsUpdated();
  5207. };
  5208. /**
  5209. * Returns the index-th row of the current matrix as a new Vector4.
  5210. */
  5211. Matrix.prototype.getRow = function (index) {
  5212. if (index < 0 || index > 3) {
  5213. return null;
  5214. }
  5215. var i = index * 4;
  5216. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  5217. };
  5218. /**
  5219. * Sets the index-th row of the current matrix with the passed Vector4 values.
  5220. * Returns the updated Matrix.
  5221. */
  5222. Matrix.prototype.setRow = function (index, row) {
  5223. if (index < 0 || index > 3) {
  5224. return this;
  5225. }
  5226. var i = index * 4;
  5227. this.m[i + 0] = row.x;
  5228. this.m[i + 1] = row.y;
  5229. this.m[i + 2] = row.z;
  5230. this.m[i + 3] = row.w;
  5231. this._markAsUpdated();
  5232. return this;
  5233. };
  5234. /**
  5235. * Compute the transpose of the matrix.
  5236. * Returns a new Matrix.
  5237. */
  5238. Matrix.prototype.transpose = function () {
  5239. return Matrix.Transpose(this);
  5240. };
  5241. /**
  5242. * Compute the transpose of the matrix.
  5243. * Returns the current matrix.
  5244. */
  5245. Matrix.prototype.transposeToRef = function (result) {
  5246. Matrix.TransposeToRef(this, result);
  5247. return this;
  5248. };
  5249. /**
  5250. * Sets the index-th row of the current matrix with the passed 4 x float values.
  5251. * Returns the updated Matrix.
  5252. */
  5253. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  5254. if (index < 0 || index > 3) {
  5255. return this;
  5256. }
  5257. var i = index * 4;
  5258. this.m[i + 0] = x;
  5259. this.m[i + 1] = y;
  5260. this.m[i + 2] = z;
  5261. this.m[i + 3] = w;
  5262. this._markAsUpdated();
  5263. return this;
  5264. };
  5265. Object.defineProperty(Matrix, "IdentityReadOnly", {
  5266. /**
  5267. * Static identity matrix to be used as readonly matrix
  5268. * Must not be updated.
  5269. */
  5270. get: function () {
  5271. return Matrix._identityReadOnly;
  5272. },
  5273. enumerable: true,
  5274. configurable: true
  5275. });
  5276. /**
  5277. * Returns a new Matrix set from the 16 passed floats.
  5278. */
  5279. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  5280. var result = new Matrix();
  5281. result.m[0] = initialM11;
  5282. result.m[1] = initialM12;
  5283. result.m[2] = initialM13;
  5284. result.m[3] = initialM14;
  5285. result.m[4] = initialM21;
  5286. result.m[5] = initialM22;
  5287. result.m[6] = initialM23;
  5288. result.m[7] = initialM24;
  5289. result.m[8] = initialM31;
  5290. result.m[9] = initialM32;
  5291. result.m[10] = initialM33;
  5292. result.m[11] = initialM34;
  5293. result.m[12] = initialM41;
  5294. result.m[13] = initialM42;
  5295. result.m[14] = initialM43;
  5296. result.m[15] = initialM44;
  5297. return result;
  5298. };
  5299. /**
  5300. * Returns a new Matrix composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  5301. */
  5302. Matrix.Compose = function (scale, rotation, translation) {
  5303. var result = Matrix.Identity();
  5304. Matrix.ComposeToRef(scale, rotation, translation, result);
  5305. return result;
  5306. };
  5307. /**
  5308. * Update a Matrix with values composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  5309. */
  5310. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  5311. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  5312. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  5313. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  5314. result.setTranslation(translation);
  5315. };
  5316. /**
  5317. * Returns a new indentity Matrix.
  5318. */
  5319. Matrix.Identity = function () {
  5320. return Matrix.FromValues(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0);
  5321. };
  5322. /**
  5323. * Sets the passed "result" as an identity matrix.
  5324. */
  5325. Matrix.IdentityToRef = function (result) {
  5326. Matrix.FromValuesToRef(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, result);
  5327. };
  5328. /**
  5329. * Returns a new zero Matrix.
  5330. */
  5331. Matrix.Zero = function () {
  5332. return Matrix.FromValues(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0);
  5333. };
  5334. /**
  5335. * Returns a new rotation matrix for "angle" radians around the X axis.
  5336. */
  5337. Matrix.RotationX = function (angle) {
  5338. var result = new Matrix();
  5339. Matrix.RotationXToRef(angle, result);
  5340. return result;
  5341. };
  5342. /**
  5343. * Returns a new Matrix as the passed inverted one.
  5344. */
  5345. Matrix.Invert = function (source) {
  5346. var result = new Matrix();
  5347. source.invertToRef(result);
  5348. return result;
  5349. };
  5350. /**
  5351. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the X axis.
  5352. */
  5353. Matrix.RotationXToRef = function (angle, result) {
  5354. var s = Math.sin(angle);
  5355. var c = Math.cos(angle);
  5356. result.m[0] = 1.0;
  5357. result.m[15] = 1.0;
  5358. result.m[5] = c;
  5359. result.m[10] = c;
  5360. result.m[9] = -s;
  5361. result.m[6] = s;
  5362. result.m[1] = 0.0;
  5363. result.m[2] = 0.0;
  5364. result.m[3] = 0.0;
  5365. result.m[4] = 0.0;
  5366. result.m[7] = 0.0;
  5367. result.m[8] = 0.0;
  5368. result.m[11] = 0.0;
  5369. result.m[12] = 0.0;
  5370. result.m[13] = 0.0;
  5371. result.m[14] = 0.0;
  5372. result._markAsUpdated();
  5373. };
  5374. /**
  5375. * Returns a new rotation matrix for "angle" radians around the Y axis.
  5376. */
  5377. Matrix.RotationY = function (angle) {
  5378. var result = new Matrix();
  5379. Matrix.RotationYToRef(angle, result);
  5380. return result;
  5381. };
  5382. /**
  5383. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Y axis.
  5384. */
  5385. Matrix.RotationYToRef = function (angle, result) {
  5386. var s = Math.sin(angle);
  5387. var c = Math.cos(angle);
  5388. result.m[5] = 1.0;
  5389. result.m[15] = 1.0;
  5390. result.m[0] = c;
  5391. result.m[2] = -s;
  5392. result.m[8] = s;
  5393. result.m[10] = c;
  5394. result.m[1] = 0.0;
  5395. result.m[3] = 0.0;
  5396. result.m[4] = 0.0;
  5397. result.m[6] = 0.0;
  5398. result.m[7] = 0.0;
  5399. result.m[9] = 0.0;
  5400. result.m[11] = 0.0;
  5401. result.m[12] = 0.0;
  5402. result.m[13] = 0.0;
  5403. result.m[14] = 0.0;
  5404. result._markAsUpdated();
  5405. };
  5406. /**
  5407. * Returns a new rotation matrix for "angle" radians around the Z axis.
  5408. */
  5409. Matrix.RotationZ = function (angle) {
  5410. var result = new Matrix();
  5411. Matrix.RotationZToRef(angle, result);
  5412. return result;
  5413. };
  5414. /**
  5415. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Z axis.
  5416. */
  5417. Matrix.RotationZToRef = function (angle, result) {
  5418. var s = Math.sin(angle);
  5419. var c = Math.cos(angle);
  5420. result.m[10] = 1.0;
  5421. result.m[15] = 1.0;
  5422. result.m[0] = c;
  5423. result.m[1] = s;
  5424. result.m[4] = -s;
  5425. result.m[5] = c;
  5426. result.m[2] = 0.0;
  5427. result.m[3] = 0.0;
  5428. result.m[6] = 0.0;
  5429. result.m[7] = 0.0;
  5430. result.m[8] = 0.0;
  5431. result.m[9] = 0.0;
  5432. result.m[11] = 0.0;
  5433. result.m[12] = 0.0;
  5434. result.m[13] = 0.0;
  5435. result.m[14] = 0.0;
  5436. result._markAsUpdated();
  5437. };
  5438. /**
  5439. * Returns a new rotation matrix for "angle" radians around the passed axis.
  5440. */
  5441. Matrix.RotationAxis = function (axis, angle) {
  5442. var result = Matrix.Zero();
  5443. Matrix.RotationAxisToRef(axis, angle, result);
  5444. return result;
  5445. };
  5446. /**
  5447. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the passed axis.
  5448. */
  5449. Matrix.RotationAxisToRef = function (axis, angle, result) {
  5450. var s = Math.sin(-angle);
  5451. var c = Math.cos(-angle);
  5452. var c1 = 1 - c;
  5453. axis.normalize();
  5454. result.m[0] = (axis.x * axis.x) * c1 + c;
  5455. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  5456. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  5457. result.m[3] = 0.0;
  5458. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  5459. result.m[5] = (axis.y * axis.y) * c1 + c;
  5460. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  5461. result.m[7] = 0.0;
  5462. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  5463. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  5464. result.m[10] = (axis.z * axis.z) * c1 + c;
  5465. result.m[11] = 0.0;
  5466. result.m[15] = 1.0;
  5467. result._markAsUpdated();
  5468. };
  5469. /**
  5470. * Returns a new Matrix as a rotation matrix from the Euler angles (y, x, z).
  5471. */
  5472. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  5473. var result = new Matrix();
  5474. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  5475. return result;
  5476. };
  5477. /**
  5478. * Sets the passed matrix "result" as a rotation matrix from the Euler angles (y, x, z).
  5479. */
  5480. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  5481. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  5482. this._tempQuaternion.toRotationMatrix(result);
  5483. };
  5484. /**
  5485. * Returns a new Matrix as a scaling matrix from the passed floats (x, y, z).
  5486. */
  5487. Matrix.Scaling = function (x, y, z) {
  5488. var result = Matrix.Zero();
  5489. Matrix.ScalingToRef(x, y, z, result);
  5490. return result;
  5491. };
  5492. /**
  5493. * Sets the passed matrix "result" as a scaling matrix from the passed floats (x, y, z).
  5494. */
  5495. Matrix.ScalingToRef = function (x, y, z, result) {
  5496. result.m[0] = x;
  5497. result.m[1] = 0.0;
  5498. result.m[2] = 0.0;
  5499. result.m[3] = 0.0;
  5500. result.m[4] = 0.0;
  5501. result.m[5] = y;
  5502. result.m[6] = 0.0;
  5503. result.m[7] = 0.0;
  5504. result.m[8] = 0.0;
  5505. result.m[9] = 0.0;
  5506. result.m[10] = z;
  5507. result.m[11] = 0.0;
  5508. result.m[12] = 0.0;
  5509. result.m[13] = 0.0;
  5510. result.m[14] = 0.0;
  5511. result.m[15] = 1.0;
  5512. result._markAsUpdated();
  5513. };
  5514. /**
  5515. * Returns a new Matrix as a translation matrix from the passed floats (x, y, z).
  5516. */
  5517. Matrix.Translation = function (x, y, z) {
  5518. var result = Matrix.Identity();
  5519. Matrix.TranslationToRef(x, y, z, result);
  5520. return result;
  5521. };
  5522. /**
  5523. * Sets the passed matrix "result" as a translation matrix from the passed floats (x, y, z).
  5524. */
  5525. Matrix.TranslationToRef = function (x, y, z, result) {
  5526. Matrix.FromValuesToRef(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, x, y, z, 1.0, result);
  5527. };
  5528. /**
  5529. * Returns a new Matrix whose values are the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  5530. * @param startValue defines the start value
  5531. * @param endValue defines the end value
  5532. * @param gradient defines the gradient factor
  5533. * @returns the new matrix
  5534. */
  5535. Matrix.Lerp = function (startValue, endValue, gradient) {
  5536. var result = Matrix.Zero();
  5537. Matrix.LerpToRef(startValue, endValue, gradient, result);
  5538. return result;
  5539. };
  5540. /**
  5541. * Set the passed matrix "result" as the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  5542. * @param startValue defines the start value
  5543. * @param endValue defines the end value
  5544. * @param gradient defines the gradient factor
  5545. * @param result defines the Matrix object where to store data
  5546. */
  5547. Matrix.LerpToRef = function (startValue, endValue, gradient, result) {
  5548. for (var index = 0; index < 16; index++) {
  5549. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  5550. }
  5551. result._markAsUpdated();
  5552. };
  5553. /**
  5554. * Returns a new Matrix whose values are computed by :
  5555. * - decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices,
  5556. * - interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end,
  5557. * - recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices.
  5558. */
  5559. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  5560. var startScale = new Vector3(0, 0, 0);
  5561. var startRotation = new Quaternion();
  5562. var startTranslation = new Vector3(0, 0, 0);
  5563. startValue.decompose(startScale, startRotation, startTranslation);
  5564. var endScale = new Vector3(0, 0, 0);
  5565. var endRotation = new Quaternion();
  5566. var endTranslation = new Vector3(0, 0, 0);
  5567. endValue.decompose(endScale, endRotation, endTranslation);
  5568. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  5569. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  5570. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  5571. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  5572. };
  5573. /**
  5574. * Returns a new rotation Matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  5575. * This methods works for a Left-Handed system.
  5576. */
  5577. Matrix.LookAtLH = function (eye, target, up) {
  5578. var result = Matrix.Zero();
  5579. Matrix.LookAtLHToRef(eye, target, up, result);
  5580. return result;
  5581. };
  5582. /**
  5583. * Sets the passed "result" Matrix as a rotation matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  5584. * This methods works for a Left-Handed system.
  5585. */
  5586. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  5587. // Z axis
  5588. target.subtractToRef(eye, this._zAxis);
  5589. this._zAxis.normalize();
  5590. // X axis
  5591. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  5592. if (this._xAxis.lengthSquared() === 0) {
  5593. this._xAxis.x = 1.0;
  5594. }
  5595. else {
  5596. this._xAxis.normalize();
  5597. }
  5598. // Y axis
  5599. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  5600. this._yAxis.normalize();
  5601. // Eye angles
  5602. var ex = -Vector3.Dot(this._xAxis, eye);
  5603. var ey = -Vector3.Dot(this._yAxis, eye);
  5604. var ez = -Vector3.Dot(this._zAxis, eye);
  5605. return Matrix.FromValuesToRef(this._xAxis.x, this._yAxis.x, this._zAxis.x, 0, this._xAxis.y, this._yAxis.y, this._zAxis.y, 0, this._xAxis.z, this._yAxis.z, this._zAxis.z, 0, ex, ey, ez, 1, result);
  5606. };
  5607. /**
  5608. * Returns a new rotation Matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  5609. * This methods works for a Right-Handed system.
  5610. */
  5611. Matrix.LookAtRH = function (eye, target, up) {
  5612. var result = Matrix.Zero();
  5613. Matrix.LookAtRHToRef(eye, target, up, result);
  5614. return result;
  5615. };
  5616. /**
  5617. * Sets the passed "result" Matrix as a rotation matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  5618. * This methods works for a Left-Handed system.
  5619. */
  5620. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  5621. // Z axis
  5622. eye.subtractToRef(target, this._zAxis);
  5623. this._zAxis.normalize();
  5624. // X axis
  5625. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  5626. if (this._xAxis.lengthSquared() === 0) {
  5627. this._xAxis.x = 1.0;
  5628. }
  5629. else {
  5630. this._xAxis.normalize();
  5631. }
  5632. // Y axis
  5633. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  5634. this._yAxis.normalize();
  5635. // Eye angles
  5636. var ex = -Vector3.Dot(this._xAxis, eye);
  5637. var ey = -Vector3.Dot(this._yAxis, eye);
  5638. var ez = -Vector3.Dot(this._zAxis, eye);
  5639. return Matrix.FromValuesToRef(this._xAxis.x, this._yAxis.x, this._zAxis.x, 0, this._xAxis.y, this._yAxis.y, this._zAxis.y, 0, this._xAxis.z, this._yAxis.z, this._zAxis.z, 0, ex, ey, ez, 1, result);
  5640. };
  5641. /**
  5642. * Returns a new Matrix as a left-handed orthographic projection matrix computed from the passed floats : width and height of the projection plane, z near and far limits.
  5643. */
  5644. Matrix.OrthoLH = function (width, height, znear, zfar) {
  5645. var matrix = Matrix.Zero();
  5646. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  5647. return matrix;
  5648. };
  5649. /**
  5650. * Sets the passed matrix "result" as a left-handed orthographic projection matrix computed from the passed floats : width and height of the projection plane, z near and far limits.
  5651. */
  5652. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  5653. var n = znear;
  5654. var f = zfar;
  5655. var a = 2.0 / width;
  5656. var b = 2.0 / height;
  5657. var c = 2.0 / (f - n);
  5658. var d = -(f + n) / (f - n);
  5659. Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 0.0, 0.0, 0.0, d, 1.0, result);
  5660. };
  5661. /**
  5662. * Returns a new Matrix as a left-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  5663. */
  5664. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  5665. var matrix = Matrix.Zero();
  5666. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  5667. return matrix;
  5668. };
  5669. /**
  5670. * Sets the passed matrix "result" as a left-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  5671. */
  5672. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  5673. var n = znear;
  5674. var f = zfar;
  5675. var a = 2.0 / (right - left);
  5676. var b = 2.0 / (top - bottom);
  5677. var c = 2.0 / (f - n);
  5678. var d = -(f + n) / (f - n);
  5679. var i0 = (left + right) / (left - right);
  5680. var i1 = (top + bottom) / (bottom - top);
  5681. Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 0.0, i0, i1, d, 1.0, result);
  5682. };
  5683. /**
  5684. * Returns a new Matrix as a right-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  5685. */
  5686. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  5687. var matrix = Matrix.Zero();
  5688. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  5689. return matrix;
  5690. };
  5691. /**
  5692. * Sets the passed matrix "result" as a right-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  5693. */
  5694. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  5695. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  5696. result.m[10] *= -1.0;
  5697. };
  5698. /**
  5699. * Returns a new Matrix as a left-handed perspective projection matrix computed from the passed floats : width and height of the projection plane, z near and far limits.
  5700. */
  5701. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  5702. var matrix = Matrix.Zero();
  5703. var n = znear;
  5704. var f = zfar;
  5705. var a = 2.0 * n / width;
  5706. var b = 2.0 * n / height;
  5707. var c = (f + n) / (f - n);
  5708. var d = -2.0 * f * n / (f - n);
  5709. Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 1.0, 0.0, 0.0, d, 0.0, matrix);
  5710. return matrix;
  5711. };
  5712. /**
  5713. * Returns a new Matrix as a left-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  5714. */
  5715. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  5716. var matrix = Matrix.Zero();
  5717. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  5718. return matrix;
  5719. };
  5720. /**
  5721. * Sets the passed matrix "result" as a left-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  5722. */
  5723. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  5724. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  5725. var n = znear;
  5726. var f = zfar;
  5727. var t = 1.0 / (Math.tan(fov * 0.5));
  5728. var a = isVerticalFovFixed ? (t / aspect) : t;
  5729. var b = isVerticalFovFixed ? t : (t * aspect);
  5730. var c = (f + n) / (f - n);
  5731. var d = -2.0 * f * n / (f - n);
  5732. Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 1.0, 0.0, 0.0, d, 0.0, result);
  5733. };
  5734. /**
  5735. * Returns a new Matrix as a right-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  5736. */
  5737. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  5738. var matrix = Matrix.Zero();
  5739. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  5740. return matrix;
  5741. };
  5742. /**
  5743. * Sets the passed matrix "result" as a right-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  5744. */
  5745. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  5746. //alternatively this could be expressed as:
  5747. // m = PerspectiveFovLHToRef
  5748. // m[10] *= -1.0;
  5749. // m[11] *= -1.0;
  5750. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  5751. var n = znear;
  5752. var f = zfar;
  5753. var t = 1.0 / (Math.tan(fov * 0.5));
  5754. var a = isVerticalFovFixed ? (t / aspect) : t;
  5755. var b = isVerticalFovFixed ? t : (t * aspect);
  5756. var c = -(f + n) / (f - n);
  5757. var d = -2 * f * n / (f - n);
  5758. Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, -1.0, 0.0, 0.0, d, 0.0, result);
  5759. };
  5760. /**
  5761. * Sets the passed matrix "result" as a left-handed perspective projection matrix for WebVR computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  5762. */
  5763. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  5764. if (rightHanded === void 0) { rightHanded = false; }
  5765. var rightHandedFactor = rightHanded ? -1 : 1;
  5766. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  5767. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  5768. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  5769. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  5770. var xScale = 2.0 / (leftTan + rightTan);
  5771. var yScale = 2.0 / (upTan + downTan);
  5772. result.m[0] = xScale;
  5773. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  5774. result.m[5] = yScale;
  5775. result.m[6] = result.m[7] = 0.0;
  5776. result.m[8] = ((leftTan - rightTan) * xScale * 0.5); // * rightHandedFactor;
  5777. result.m[9] = -((upTan - downTan) * yScale * 0.5); // * rightHandedFactor;
  5778. //result.m[10] = -(znear + zfar) / (zfar - znear) * rightHandedFactor;
  5779. result.m[10] = -zfar / (znear - zfar);
  5780. result.m[11] = 1.0 * rightHandedFactor;
  5781. result.m[12] = result.m[13] = result.m[15] = 0.0;
  5782. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  5783. // result.m[14] = (znear * zfar) / (znear - zfar);
  5784. result._markAsUpdated();
  5785. };
  5786. /**
  5787. * Returns the final transformation matrix : world * view * projection * viewport
  5788. */
  5789. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  5790. var cw = viewport.width;
  5791. var ch = viewport.height;
  5792. var cx = viewport.x;
  5793. var cy = viewport.y;
  5794. var viewportMatrix = Matrix.FromValues(cw / 2.0, 0.0, 0.0, 0.0, 0.0, -ch / 2.0, 0.0, 0.0, 0.0, 0.0, zmax - zmin, 0.0, cx + cw / 2.0, ch / 2.0 + cy, zmin, 1);
  5795. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  5796. };
  5797. /**
  5798. * Returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the passed Matrix.
  5799. */
  5800. Matrix.GetAsMatrix2x2 = function (matrix) {
  5801. return new Float32Array([
  5802. matrix.m[0], matrix.m[1],
  5803. matrix.m[4], matrix.m[5]
  5804. ]);
  5805. };
  5806. /**
  5807. * Returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the passed Matrix.
  5808. */
  5809. Matrix.GetAsMatrix3x3 = function (matrix) {
  5810. return new Float32Array([
  5811. matrix.m[0], matrix.m[1], matrix.m[2],
  5812. matrix.m[4], matrix.m[5], matrix.m[6],
  5813. matrix.m[8], matrix.m[9], matrix.m[10]
  5814. ]);
  5815. };
  5816. /**
  5817. * Compute the transpose of the passed Matrix.
  5818. * Returns a new Matrix.
  5819. */
  5820. Matrix.Transpose = function (matrix) {
  5821. var result = new Matrix();
  5822. Matrix.TransposeToRef(matrix, result);
  5823. return result;
  5824. };
  5825. /**
  5826. * Compute the transpose of the passed Matrix and store it in the result matrix.
  5827. */
  5828. Matrix.TransposeToRef = function (matrix, result) {
  5829. result.m[0] = matrix.m[0];
  5830. result.m[1] = matrix.m[4];
  5831. result.m[2] = matrix.m[8];
  5832. result.m[3] = matrix.m[12];
  5833. result.m[4] = matrix.m[1];
  5834. result.m[5] = matrix.m[5];
  5835. result.m[6] = matrix.m[9];
  5836. result.m[7] = matrix.m[13];
  5837. result.m[8] = matrix.m[2];
  5838. result.m[9] = matrix.m[6];
  5839. result.m[10] = matrix.m[10];
  5840. result.m[11] = matrix.m[14];
  5841. result.m[12] = matrix.m[3];
  5842. result.m[13] = matrix.m[7];
  5843. result.m[14] = matrix.m[11];
  5844. result.m[15] = matrix.m[15];
  5845. };
  5846. /**
  5847. * Returns a new Matrix as the reflection matrix across the passed plane.
  5848. */
  5849. Matrix.Reflection = function (plane) {
  5850. var matrix = new Matrix();
  5851. Matrix.ReflectionToRef(plane, matrix);
  5852. return matrix;
  5853. };
  5854. /**
  5855. * Sets the passed matrix "result" as the reflection matrix across the passed plane.
  5856. */
  5857. Matrix.ReflectionToRef = function (plane, result) {
  5858. plane.normalize();
  5859. var x = plane.normal.x;
  5860. var y = plane.normal.y;
  5861. var z = plane.normal.z;
  5862. var temp = -2 * x;
  5863. var temp2 = -2 * y;
  5864. var temp3 = -2 * z;
  5865. result.m[0] = (temp * x) + 1;
  5866. result.m[1] = temp2 * x;
  5867. result.m[2] = temp3 * x;
  5868. result.m[3] = 0.0;
  5869. result.m[4] = temp * y;
  5870. result.m[5] = (temp2 * y) + 1;
  5871. result.m[6] = temp3 * y;
  5872. result.m[7] = 0.0;
  5873. result.m[8] = temp * z;
  5874. result.m[9] = temp2 * z;
  5875. result.m[10] = (temp3 * z) + 1;
  5876. result.m[11] = 0.0;
  5877. result.m[12] = temp * plane.d;
  5878. result.m[13] = temp2 * plane.d;
  5879. result.m[14] = temp3 * plane.d;
  5880. result.m[15] = 1.0;
  5881. result._markAsUpdated();
  5882. };
  5883. /**
  5884. * Sets the passed matrix "mat" as a rotation matrix composed from the 3 passed left handed axis.
  5885. */
  5886. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  5887. result.m[0] = xaxis.x;
  5888. result.m[1] = xaxis.y;
  5889. result.m[2] = xaxis.z;
  5890. result.m[3] = 0.0;
  5891. result.m[4] = yaxis.x;
  5892. result.m[5] = yaxis.y;
  5893. result.m[6] = yaxis.z;
  5894. result.m[7] = 0.0;
  5895. result.m[8] = zaxis.x;
  5896. result.m[9] = zaxis.y;
  5897. result.m[10] = zaxis.z;
  5898. result.m[11] = 0.0;
  5899. result.m[12] = 0.0;
  5900. result.m[13] = 0.0;
  5901. result.m[14] = 0.0;
  5902. result.m[15] = 1.0;
  5903. result._markAsUpdated();
  5904. };
  5905. /**
  5906. * Sets the passed matrix "result" as a rotation matrix according to the passed quaternion.
  5907. */
  5908. Matrix.FromQuaternionToRef = function (quat, result) {
  5909. var xx = quat.x * quat.x;
  5910. var yy = quat.y * quat.y;
  5911. var zz = quat.z * quat.z;
  5912. var xy = quat.x * quat.y;
  5913. var zw = quat.z * quat.w;
  5914. var zx = quat.z * quat.x;
  5915. var yw = quat.y * quat.w;
  5916. var yz = quat.y * quat.z;
  5917. var xw = quat.x * quat.w;
  5918. result.m[0] = 1.0 - (2.0 * (yy + zz));
  5919. result.m[1] = 2.0 * (xy + zw);
  5920. result.m[2] = 2.0 * (zx - yw);
  5921. result.m[3] = 0.0;
  5922. result.m[4] = 2.0 * (xy - zw);
  5923. result.m[5] = 1.0 - (2.0 * (zz + xx));
  5924. result.m[6] = 2.0 * (yz + xw);
  5925. result.m[7] = 0.0;
  5926. result.m[8] = 2.0 * (zx + yw);
  5927. result.m[9] = 2.0 * (yz - xw);
  5928. result.m[10] = 1.0 - (2.0 * (yy + xx));
  5929. result.m[11] = 0.0;
  5930. result.m[12] = 0.0;
  5931. result.m[13] = 0.0;
  5932. result.m[14] = 0.0;
  5933. result.m[15] = 1.0;
  5934. result._markAsUpdated();
  5935. };
  5936. Matrix._tempQuaternion = new Quaternion();
  5937. Matrix._xAxis = Vector3.Zero();
  5938. Matrix._yAxis = Vector3.Zero();
  5939. Matrix._zAxis = Vector3.Zero();
  5940. Matrix._updateFlagSeed = 0;
  5941. Matrix._identityReadOnly = Matrix.Identity();
  5942. return Matrix;
  5943. }());
  5944. BABYLON.Matrix = Matrix;
  5945. var Plane = /** @class */ (function () {
  5946. /**
  5947. * Creates a Plane object according to the passed floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  5948. */
  5949. function Plane(a, b, c, d) {
  5950. this.normal = new Vector3(a, b, c);
  5951. this.d = d;
  5952. }
  5953. /**
  5954. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  5955. */
  5956. Plane.prototype.asArray = function () {
  5957. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  5958. };
  5959. // Methods
  5960. /**
  5961. * Returns a new plane copied from the current Plane.
  5962. */
  5963. Plane.prototype.clone = function () {
  5964. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  5965. };
  5966. /**
  5967. * Returns the string "Plane".
  5968. */
  5969. Plane.prototype.getClassName = function () {
  5970. return "Plane";
  5971. };
  5972. /**
  5973. * Returns the Plane hash code.
  5974. */
  5975. Plane.prototype.getHashCode = function () {
  5976. var hash = this.normal.getHashCode();
  5977. hash = (hash * 397) ^ (this.d || 0);
  5978. return hash;
  5979. };
  5980. /**
  5981. * Normalize the current Plane in place.
  5982. * Returns the updated Plane.
  5983. */
  5984. Plane.prototype.normalize = function () {
  5985. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  5986. var magnitude = 0.0;
  5987. if (norm !== 0) {
  5988. magnitude = 1.0 / norm;
  5989. }
  5990. this.normal.x *= magnitude;
  5991. this.normal.y *= magnitude;
  5992. this.normal.z *= magnitude;
  5993. this.d *= magnitude;
  5994. return this;
  5995. };
  5996. /**
  5997. * Returns a new Plane as the result of the transformation of the current Plane by the passed matrix.
  5998. */
  5999. Plane.prototype.transform = function (transformation) {
  6000. var transposedMatrix = Matrix.Transpose(transformation);
  6001. var x = this.normal.x;
  6002. var y = this.normal.y;
  6003. var z = this.normal.z;
  6004. var d = this.d;
  6005. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  6006. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  6007. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  6008. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  6009. return new Plane(normalX, normalY, normalZ, finalD);
  6010. };
  6011. /**
  6012. * Returns the dot product (float) of the point coordinates and the plane normal.
  6013. */
  6014. Plane.prototype.dotCoordinate = function (point) {
  6015. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  6016. };
  6017. /**
  6018. * Updates the current Plane from the plane defined by the three passed points.
  6019. * Returns the updated Plane.
  6020. */
  6021. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  6022. var x1 = point2.x - point1.x;
  6023. var y1 = point2.y - point1.y;
  6024. var z1 = point2.z - point1.z;
  6025. var x2 = point3.x - point1.x;
  6026. var y2 = point3.y - point1.y;
  6027. var z2 = point3.z - point1.z;
  6028. var yz = (y1 * z2) - (z1 * y2);
  6029. var xz = (z1 * x2) - (x1 * z2);
  6030. var xy = (x1 * y2) - (y1 * x2);
  6031. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  6032. var invPyth;
  6033. if (pyth !== 0) {
  6034. invPyth = 1.0 / pyth;
  6035. }
  6036. else {
  6037. invPyth = 0.0;
  6038. }
  6039. this.normal.x = yz * invPyth;
  6040. this.normal.y = xz * invPyth;
  6041. this.normal.z = xy * invPyth;
  6042. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  6043. return this;
  6044. };
  6045. /**
  6046. * Boolean : True is the vector "direction" is the same side than the plane normal.
  6047. */
  6048. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  6049. var dot = Vector3.Dot(this.normal, direction);
  6050. return (dot <= epsilon);
  6051. };
  6052. /**
  6053. * Returns the signed distance (float) from the passed point to the Plane.
  6054. */
  6055. Plane.prototype.signedDistanceTo = function (point) {
  6056. return Vector3.Dot(point, this.normal) + this.d;
  6057. };
  6058. // Statics
  6059. /**
  6060. * Returns a new Plane from the passed array.
  6061. */
  6062. Plane.FromArray = function (array) {
  6063. return new Plane(array[0], array[1], array[2], array[3]);
  6064. };
  6065. /**
  6066. * Returns a new Plane defined by the three passed points.
  6067. */
  6068. Plane.FromPoints = function (point1, point2, point3) {
  6069. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6070. result.copyFromPoints(point1, point2, point3);
  6071. return result;
  6072. };
  6073. /**
  6074. * Returns a new Plane the normal vector to this plane at the passed origin point.
  6075. * Note : the vector "normal" is updated because normalized.
  6076. */
  6077. Plane.FromPositionAndNormal = function (origin, normal) {
  6078. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6079. normal.normalize();
  6080. result.normal = normal;
  6081. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6082. return result;
  6083. };
  6084. /**
  6085. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the passed other point.
  6086. */
  6087. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  6088. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6089. return Vector3.Dot(point, normal) + d;
  6090. };
  6091. return Plane;
  6092. }());
  6093. BABYLON.Plane = Plane;
  6094. var Viewport = /** @class */ (function () {
  6095. /**
  6096. * Creates a Viewport object located at (x, y) and sized (width, height).
  6097. */
  6098. function Viewport(x, y, width, height) {
  6099. this.x = x;
  6100. this.y = y;
  6101. this.width = width;
  6102. this.height = height;
  6103. }
  6104. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  6105. if (renderWidthOrEngine.getRenderWidth) {
  6106. var engine = renderWidthOrEngine;
  6107. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  6108. }
  6109. var renderWidth = renderWidthOrEngine;
  6110. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  6111. };
  6112. /**
  6113. * Returns a new Viewport copied from the current one.
  6114. */
  6115. Viewport.prototype.clone = function () {
  6116. return new Viewport(this.x, this.y, this.width, this.height);
  6117. };
  6118. return Viewport;
  6119. }());
  6120. BABYLON.Viewport = Viewport;
  6121. var Frustum = /** @class */ (function () {
  6122. function Frustum() {
  6123. }
  6124. /**
  6125. * Returns a new array of 6 Frustum planes computed by the passed transformation matrix.
  6126. */
  6127. Frustum.GetPlanes = function (transform) {
  6128. var frustumPlanes = [];
  6129. for (var index = 0; index < 6; index++) {
  6130. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  6131. }
  6132. Frustum.GetPlanesToRef(transform, frustumPlanes);
  6133. return frustumPlanes;
  6134. };
  6135. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  6136. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  6137. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  6138. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  6139. frustumPlane.d = transform.m[15] + transform.m[14];
  6140. frustumPlane.normalize();
  6141. };
  6142. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  6143. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  6144. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  6145. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  6146. frustumPlane.d = transform.m[15] - transform.m[14];
  6147. frustumPlane.normalize();
  6148. };
  6149. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  6150. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  6151. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  6152. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  6153. frustumPlane.d = transform.m[15] + transform.m[12];
  6154. frustumPlane.normalize();
  6155. };
  6156. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  6157. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  6158. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  6159. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  6160. frustumPlane.d = transform.m[15] - transform.m[12];
  6161. frustumPlane.normalize();
  6162. };
  6163. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  6164. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  6165. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  6166. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  6167. frustumPlane.d = transform.m[15] - transform.m[13];
  6168. frustumPlane.normalize();
  6169. };
  6170. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  6171. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  6172. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  6173. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  6174. frustumPlane.d = transform.m[15] + transform.m[13];
  6175. frustumPlane.normalize();
  6176. };
  6177. /**
  6178. * Sets the passed array "frustumPlanes" with the 6 Frustum planes computed by the passed transformation matrix.
  6179. */
  6180. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  6181. // Near
  6182. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  6183. // Far
  6184. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  6185. // Left
  6186. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  6187. // Right
  6188. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  6189. // Top
  6190. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  6191. // Bottom
  6192. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  6193. };
  6194. return Frustum;
  6195. }());
  6196. BABYLON.Frustum = Frustum;
  6197. var Space;
  6198. (function (Space) {
  6199. Space[Space["LOCAL"] = 0] = "LOCAL";
  6200. Space[Space["WORLD"] = 1] = "WORLD";
  6201. Space[Space["BONE"] = 2] = "BONE";
  6202. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  6203. var Axis = /** @class */ (function () {
  6204. function Axis() {
  6205. }
  6206. Axis.X = new Vector3(1.0, 0.0, 0.0);
  6207. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  6208. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  6209. return Axis;
  6210. }());
  6211. BABYLON.Axis = Axis;
  6212. ;
  6213. var BezierCurve = /** @class */ (function () {
  6214. function BezierCurve() {
  6215. }
  6216. /**
  6217. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the passed x1, y1, x2, y2 floats.
  6218. */
  6219. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  6220. // Extract X (which is equal to time here)
  6221. var f0 = 1 - 3 * x2 + 3 * x1;
  6222. var f1 = 3 * x2 - 6 * x1;
  6223. var f2 = 3 * x1;
  6224. var refinedT = t;
  6225. for (var i = 0; i < 5; i++) {
  6226. var refinedT2 = refinedT * refinedT;
  6227. var refinedT3 = refinedT2 * refinedT;
  6228. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  6229. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  6230. refinedT -= (x - t) * slope;
  6231. refinedT = Math.min(1, Math.max(0, refinedT));
  6232. }
  6233. // Resolve cubic bezier for the given x
  6234. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  6235. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  6236. Math.pow(refinedT, 3);
  6237. };
  6238. return BezierCurve;
  6239. }());
  6240. BABYLON.BezierCurve = BezierCurve;
  6241. var Orientation;
  6242. (function (Orientation) {
  6243. Orientation[Orientation["CW"] = 0] = "CW";
  6244. Orientation[Orientation["CCW"] = 1] = "CCW";
  6245. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  6246. var Angle = /** @class */ (function () {
  6247. /**
  6248. * Creates an Angle object of "radians" radians (float).
  6249. */
  6250. function Angle(radians) {
  6251. var _this = this;
  6252. /**
  6253. * Returns the Angle value in degrees (float).
  6254. */
  6255. this.degrees = function () { return _this._radians * 180.0 / Math.PI; };
  6256. /**
  6257. * Returns the Angle value in radians (float).
  6258. */
  6259. this.radians = function () { return _this._radians; };
  6260. this._radians = radians;
  6261. if (this._radians < 0.0)
  6262. this._radians += (2.0 * Math.PI);
  6263. }
  6264. /**
  6265. * Returns a new Angle object valued with the angle value in radians between the two passed vectors.
  6266. */
  6267. Angle.BetweenTwoPoints = function (a, b) {
  6268. var delta = b.subtract(a);
  6269. var theta = Math.atan2(delta.y, delta.x);
  6270. return new Angle(theta);
  6271. };
  6272. /**
  6273. * Returns a new Angle object from the passed float in radians.
  6274. */
  6275. Angle.FromRadians = function (radians) {
  6276. return new Angle(radians);
  6277. };
  6278. /**
  6279. * Returns a new Angle object from the passed float in degrees.
  6280. */
  6281. Angle.FromDegrees = function (degrees) {
  6282. return new Angle(degrees * Math.PI / 180.0);
  6283. };
  6284. return Angle;
  6285. }());
  6286. BABYLON.Angle = Angle;
  6287. var Arc2 = /** @class */ (function () {
  6288. /**
  6289. * Creates an Arc object from the three passed points : start, middle and end.
  6290. */
  6291. function Arc2(startPoint, midPoint, endPoint) {
  6292. this.startPoint = startPoint;
  6293. this.midPoint = midPoint;
  6294. this.endPoint = endPoint;
  6295. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  6296. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  6297. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  6298. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  6299. this.centerPoint = new Vector2((startToMid * (midPoint.y - endPoint.y) - midToEnd * (startPoint.y - midPoint.y)) / det, ((startPoint.x - midPoint.x) * midToEnd - (midPoint.x - endPoint.x) * startToMid) / det);
  6300. this.radius = this.centerPoint.subtract(this.startPoint).length();
  6301. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  6302. var a1 = this.startAngle.degrees();
  6303. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  6304. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  6305. // angles correction
  6306. if (a2 - a1 > +180.0)
  6307. a2 -= 360.0;
  6308. if (a2 - a1 < -180.0)
  6309. a2 += 360.0;
  6310. if (a3 - a2 > +180.0)
  6311. a3 -= 360.0;
  6312. if (a3 - a2 < -180.0)
  6313. a3 += 360.0;
  6314. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  6315. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  6316. }
  6317. return Arc2;
  6318. }());
  6319. BABYLON.Arc2 = Arc2;
  6320. var Path2 = /** @class */ (function () {
  6321. /**
  6322. * Creates a Path2 object from the starting 2D coordinates x and y.
  6323. */
  6324. function Path2(x, y) {
  6325. this._points = new Array();
  6326. this._length = 0.0;
  6327. this.closed = false;
  6328. this._points.push(new Vector2(x, y));
  6329. }
  6330. /**
  6331. * Adds a new segment until the passed coordinates (x, y) to the current Path2.
  6332. * Returns the updated Path2.
  6333. */
  6334. Path2.prototype.addLineTo = function (x, y) {
  6335. if (this.closed) {
  6336. return this;
  6337. }
  6338. var newPoint = new Vector2(x, y);
  6339. var previousPoint = this._points[this._points.length - 1];
  6340. this._points.push(newPoint);
  6341. this._length += newPoint.subtract(previousPoint).length();
  6342. return this;
  6343. };
  6344. /**
  6345. * Adds _numberOfSegments_ segments according to the arc definition (middle point coordinates, end point coordinates, the arc start point being the current Path2 last point) to the current Path2.
  6346. * Returns the updated Path2.
  6347. */
  6348. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  6349. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  6350. if (this.closed) {
  6351. return this;
  6352. }
  6353. var startPoint = this._points[this._points.length - 1];
  6354. var midPoint = new Vector2(midX, midY);
  6355. var endPoint = new Vector2(endX, endY);
  6356. var arc = new Arc2(startPoint, midPoint, endPoint);
  6357. var increment = arc.angle.radians() / numberOfSegments;
  6358. if (arc.orientation === Orientation.CW)
  6359. increment *= -1;
  6360. var currentAngle = arc.startAngle.radians() + increment;
  6361. for (var i = 0; i < numberOfSegments; i++) {
  6362. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  6363. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  6364. this.addLineTo(x, y);
  6365. currentAngle += increment;
  6366. }
  6367. return this;
  6368. };
  6369. /**
  6370. * Closes the Path2.
  6371. * Returns the Path2.
  6372. */
  6373. Path2.prototype.close = function () {
  6374. this.closed = true;
  6375. return this;
  6376. };
  6377. /**
  6378. * Returns the Path2 total length (float).
  6379. */
  6380. Path2.prototype.length = function () {
  6381. var result = this._length;
  6382. if (!this.closed) {
  6383. var lastPoint = this._points[this._points.length - 1];
  6384. var firstPoint = this._points[0];
  6385. result += (firstPoint.subtract(lastPoint).length());
  6386. }
  6387. return result;
  6388. };
  6389. /**
  6390. * Returns the Path2 internal array of points.
  6391. */
  6392. Path2.prototype.getPoints = function () {
  6393. return this._points;
  6394. };
  6395. /**
  6396. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  6397. */
  6398. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  6399. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  6400. return Vector2.Zero();
  6401. }
  6402. var lengthPosition = normalizedLengthPosition * this.length();
  6403. var previousOffset = 0;
  6404. for (var i = 0; i < this._points.length; i++) {
  6405. var j = (i + 1) % this._points.length;
  6406. var a = this._points[i];
  6407. var b = this._points[j];
  6408. var bToA = b.subtract(a);
  6409. var nextOffset = (bToA.length() + previousOffset);
  6410. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  6411. var dir = bToA.normalize();
  6412. var localOffset = lengthPosition - previousOffset;
  6413. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  6414. }
  6415. previousOffset = nextOffset;
  6416. }
  6417. return Vector2.Zero();
  6418. };
  6419. /**
  6420. * Returns a new Path2 starting at the coordinates (x, y).
  6421. */
  6422. Path2.StartingAt = function (x, y) {
  6423. return new Path2(x, y);
  6424. };
  6425. return Path2;
  6426. }());
  6427. BABYLON.Path2 = Path2;
  6428. var Path3D = /** @class */ (function () {
  6429. /**
  6430. * new Path3D(path, normal, raw)
  6431. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  6432. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  6433. * path : an array of Vector3, the curve axis of the Path3D
  6434. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  6435. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  6436. */
  6437. function Path3D(path, firstNormal, raw) {
  6438. if (firstNormal === void 0) { firstNormal = null; }
  6439. this.path = path;
  6440. this._curve = new Array();
  6441. this._distances = new Array();
  6442. this._tangents = new Array();
  6443. this._normals = new Array();
  6444. this._binormals = new Array();
  6445. for (var p = 0; p < path.length; p++) {
  6446. this._curve[p] = path[p].clone(); // hard copy
  6447. }
  6448. this._raw = raw || false;
  6449. this._compute(firstNormal);
  6450. }
  6451. /**
  6452. * Returns the Path3D array of successive Vector3 designing its curve.
  6453. */
  6454. Path3D.prototype.getCurve = function () {
  6455. return this._curve;
  6456. };
  6457. /**
  6458. * Returns an array populated with tangent vectors on each Path3D curve point.
  6459. */
  6460. Path3D.prototype.getTangents = function () {
  6461. return this._tangents;
  6462. };
  6463. /**
  6464. * Returns an array populated with normal vectors on each Path3D curve point.
  6465. */
  6466. Path3D.prototype.getNormals = function () {
  6467. return this._normals;
  6468. };
  6469. /**
  6470. * Returns an array populated with binormal vectors on each Path3D curve point.
  6471. */
  6472. Path3D.prototype.getBinormals = function () {
  6473. return this._binormals;
  6474. };
  6475. /**
  6476. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  6477. */
  6478. Path3D.prototype.getDistances = function () {
  6479. return this._distances;
  6480. };
  6481. /**
  6482. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  6483. * Returns the same object updated.
  6484. */
  6485. Path3D.prototype.update = function (path, firstNormal) {
  6486. if (firstNormal === void 0) { firstNormal = null; }
  6487. for (var p = 0; p < path.length; p++) {
  6488. this._curve[p].x = path[p].x;
  6489. this._curve[p].y = path[p].y;
  6490. this._curve[p].z = path[p].z;
  6491. }
  6492. this._compute(firstNormal);
  6493. return this;
  6494. };
  6495. // private function compute() : computes tangents, normals and binormals
  6496. Path3D.prototype._compute = function (firstNormal) {
  6497. var l = this._curve.length;
  6498. // first and last tangents
  6499. this._tangents[0] = this._getFirstNonNullVector(0);
  6500. if (!this._raw) {
  6501. this._tangents[0].normalize();
  6502. }
  6503. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  6504. if (!this._raw) {
  6505. this._tangents[l - 1].normalize();
  6506. }
  6507. // normals and binormals at first point : arbitrary vector with _normalVector()
  6508. var tg0 = this._tangents[0];
  6509. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  6510. this._normals[0] = pp0;
  6511. if (!this._raw) {
  6512. this._normals[0].normalize();
  6513. }
  6514. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  6515. if (!this._raw) {
  6516. this._binormals[0].normalize();
  6517. }
  6518. this._distances[0] = 0.0;
  6519. // normals and binormals : next points
  6520. var prev; // previous vector (segment)
  6521. var cur; // current vector (segment)
  6522. var curTang; // current tangent
  6523. // previous normal
  6524. var prevBinor; // previous binormal
  6525. for (var i = 1; i < l; i++) {
  6526. // tangents
  6527. prev = this._getLastNonNullVector(i);
  6528. if (i < l - 1) {
  6529. cur = this._getFirstNonNullVector(i);
  6530. this._tangents[i] = prev.add(cur);
  6531. this._tangents[i].normalize();
  6532. }
  6533. this._distances[i] = this._distances[i - 1] + prev.length();
  6534. // normals and binormals
  6535. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  6536. curTang = this._tangents[i];
  6537. prevBinor = this._binormals[i - 1];
  6538. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  6539. if (!this._raw) {
  6540. this._normals[i].normalize();
  6541. }
  6542. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  6543. if (!this._raw) {
  6544. this._binormals[i].normalize();
  6545. }
  6546. }
  6547. };
  6548. // private function getFirstNonNullVector(index)
  6549. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  6550. Path3D.prototype._getFirstNonNullVector = function (index) {
  6551. var i = 1;
  6552. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  6553. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  6554. i++;
  6555. nNVector = this._curve[index + i].subtract(this._curve[index]);
  6556. }
  6557. return nNVector;
  6558. };
  6559. // private function getLastNonNullVector(index)
  6560. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  6561. Path3D.prototype._getLastNonNullVector = function (index) {
  6562. var i = 1;
  6563. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  6564. while (nLVector.length() === 0 && index > i + 1) {
  6565. i++;
  6566. nLVector = this._curve[index].subtract(this._curve[index - i]);
  6567. }
  6568. return nLVector;
  6569. };
  6570. // private function normalVector(v0, vt, va) :
  6571. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  6572. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  6573. Path3D.prototype._normalVector = function (v0, vt, va) {
  6574. var normal0;
  6575. var tgl = vt.length();
  6576. if (tgl === 0.0) {
  6577. tgl = 1.0;
  6578. }
  6579. if (va === undefined || va === null) {
  6580. var point;
  6581. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  6582. point = new Vector3(0.0, -1.0, 0.0);
  6583. }
  6584. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  6585. point = new Vector3(1.0, 0.0, 0.0);
  6586. }
  6587. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  6588. point = new Vector3(0.0, 0.0, 1.0);
  6589. }
  6590. else {
  6591. point = Vector3.Zero();
  6592. }
  6593. normal0 = Vector3.Cross(vt, point);
  6594. }
  6595. else {
  6596. normal0 = Vector3.Cross(vt, va);
  6597. Vector3.CrossToRef(normal0, vt, normal0);
  6598. }
  6599. normal0.normalize();
  6600. return normal0;
  6601. };
  6602. return Path3D;
  6603. }());
  6604. BABYLON.Path3D = Path3D;
  6605. var Curve3 = /** @class */ (function () {
  6606. /**
  6607. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  6608. * A Curve3 is designed from a series of successive Vector3.
  6609. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  6610. */
  6611. function Curve3(points) {
  6612. this._length = 0.0;
  6613. this._points = points;
  6614. this._length = this._computeLength(points);
  6615. }
  6616. /**
  6617. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  6618. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  6619. * @param v1 (Vector3) the control point
  6620. * @param v2 (Vector3) the end point of the Quadratic Bezier
  6621. * @param nbPoints (integer) the wanted number of points in the curve
  6622. */
  6623. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  6624. nbPoints = nbPoints > 2 ? nbPoints : 3;
  6625. var bez = new Array();
  6626. var equation = function (t, val0, val1, val2) {
  6627. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  6628. return res;
  6629. };
  6630. for (var i = 0; i <= nbPoints; i++) {
  6631. bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x), equation(i / nbPoints, v0.y, v1.y, v2.y), equation(i / nbPoints, v0.z, v1.z, v2.z)));
  6632. }
  6633. return new Curve3(bez);
  6634. };
  6635. /**
  6636. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  6637. * @param v0 (Vector3) the origin point of the Cubic Bezier
  6638. * @param v1 (Vector3) the first control point
  6639. * @param v2 (Vector3) the second control point
  6640. * @param v3 (Vector3) the end point of the Cubic Bezier
  6641. * @param nbPoints (integer) the wanted number of points in the curve
  6642. */
  6643. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  6644. nbPoints = nbPoints > 3 ? nbPoints : 4;
  6645. var bez = new Array();
  6646. var equation = function (t, val0, val1, val2, val3) {
  6647. var res = (1.0 - t) * (1.0 - t) * (1.0 - t) * val0 + 3.0 * t * (1.0 - t) * (1.0 - t) * val1 + 3.0 * t * t * (1.0 - t) * val2 + t * t * t * val3;
  6648. return res;
  6649. };
  6650. for (var i = 0; i <= nbPoints; i++) {
  6651. bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x, v3.x), equation(i / nbPoints, v0.y, v1.y, v2.y, v3.y), equation(i / nbPoints, v0.z, v1.z, v2.z, v3.z)));
  6652. }
  6653. return new Curve3(bez);
  6654. };
  6655. /**
  6656. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  6657. * @param p1 (Vector3) the origin point of the Hermite Spline
  6658. * @param t1 (Vector3) the tangent vector at the origin point
  6659. * @param p2 (Vector3) the end point of the Hermite Spline
  6660. * @param t2 (Vector3) the tangent vector at the end point
  6661. * @param nbPoints (integer) the wanted number of points in the curve
  6662. */
  6663. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  6664. var hermite = new Array();
  6665. var step = 1.0 / nbPoints;
  6666. for (var i = 0; i <= nbPoints; i++) {
  6667. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  6668. }
  6669. return new Curve3(hermite);
  6670. };
  6671. /**
  6672. * Returns a Curve3 object along a CatmullRom Spline curve :
  6673. * @param points (array of Vector3) the points the spline must pass through. At least, four points required.
  6674. * @param nbPoints (integer) the wanted number of points between each curve control points.
  6675. */
  6676. Curve3.CreateCatmullRomSpline = function (points, nbPoints) {
  6677. var totalPoints = new Array();
  6678. totalPoints.push(points[0].clone());
  6679. Array.prototype.push.apply(totalPoints, points);
  6680. totalPoints.push(points[points.length - 1].clone());
  6681. var catmullRom = new Array();
  6682. var step = 1.0 / nbPoints;
  6683. var amount = 0.0;
  6684. for (var i = 0; i < totalPoints.length - 3; i++) {
  6685. amount = 0;
  6686. for (var c = 0; c < nbPoints; c++) {
  6687. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  6688. amount += step;
  6689. }
  6690. }
  6691. i--;
  6692. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  6693. return new Curve3(catmullRom);
  6694. };
  6695. /**
  6696. * Returns the Curve3 stored array of successive Vector3
  6697. */
  6698. Curve3.prototype.getPoints = function () {
  6699. return this._points;
  6700. };
  6701. /**
  6702. * Returns the computed length (float) of the curve.
  6703. */
  6704. Curve3.prototype.length = function () {
  6705. return this._length;
  6706. };
  6707. /**
  6708. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  6709. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  6710. * curveA and curveB keep unchanged.
  6711. */
  6712. Curve3.prototype.continue = function (curve) {
  6713. var lastPoint = this._points[this._points.length - 1];
  6714. var continuedPoints = this._points.slice();
  6715. var curvePoints = curve.getPoints();
  6716. for (var i = 1; i < curvePoints.length; i++) {
  6717. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  6718. }
  6719. var continuedCurve = new Curve3(continuedPoints);
  6720. return continuedCurve;
  6721. };
  6722. Curve3.prototype._computeLength = function (path) {
  6723. var l = 0;
  6724. for (var i = 1; i < path.length; i++) {
  6725. l += (path[i].subtract(path[i - 1])).length();
  6726. }
  6727. return l;
  6728. };
  6729. return Curve3;
  6730. }());
  6731. BABYLON.Curve3 = Curve3;
  6732. // Vertex formats
  6733. var PositionNormalVertex = /** @class */ (function () {
  6734. function PositionNormalVertex(position, normal) {
  6735. if (position === void 0) { position = Vector3.Zero(); }
  6736. if (normal === void 0) { normal = Vector3.Up(); }
  6737. this.position = position;
  6738. this.normal = normal;
  6739. }
  6740. PositionNormalVertex.prototype.clone = function () {
  6741. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  6742. };
  6743. return PositionNormalVertex;
  6744. }());
  6745. BABYLON.PositionNormalVertex = PositionNormalVertex;
  6746. var PositionNormalTextureVertex = /** @class */ (function () {
  6747. function PositionNormalTextureVertex(position, normal, uv) {
  6748. if (position === void 0) { position = Vector3.Zero(); }
  6749. if (normal === void 0) { normal = Vector3.Up(); }
  6750. if (uv === void 0) { uv = Vector2.Zero(); }
  6751. this.position = position;
  6752. this.normal = normal;
  6753. this.uv = uv;
  6754. }
  6755. PositionNormalTextureVertex.prototype.clone = function () {
  6756. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  6757. };
  6758. return PositionNormalTextureVertex;
  6759. }());
  6760. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  6761. // Temporary pre-allocated objects for engine internal use
  6762. // usage in any internal function :
  6763. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  6764. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  6765. var Tmp = /** @class */ (function () {
  6766. function Tmp() {
  6767. }
  6768. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  6769. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  6770. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  6771. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  6772. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  6773. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  6774. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  6775. Matrix.Zero(), Matrix.Zero(),
  6776. Matrix.Zero(), Matrix.Zero(),
  6777. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  6778. return Tmp;
  6779. }());
  6780. BABYLON.Tmp = Tmp;
  6781. // Same as Tmp but not exported to keep it onyl for math functions to avoid conflicts
  6782. var MathTmp = /** @class */ (function () {
  6783. function MathTmp() {
  6784. }
  6785. MathTmp.Vector3 = [Vector3.Zero()];
  6786. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  6787. MathTmp.Quaternion = [Quaternion.Zero()];
  6788. return MathTmp;
  6789. }());
  6790. })(BABYLON || (BABYLON = {}));
  6791. //# sourceMappingURL=babylon.math.js.map
  6792. var BABYLON;
  6793. (function (BABYLON) {
  6794. var Scalar = /** @class */ (function () {
  6795. function Scalar() {
  6796. }
  6797. /**
  6798. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  6799. */
  6800. Scalar.WithinEpsilon = function (a, b, epsilon) {
  6801. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  6802. var num = a - b;
  6803. return -epsilon <= num && num <= epsilon;
  6804. };
  6805. /**
  6806. * Returns a string : the upper case translation of the number i to hexadecimal.
  6807. */
  6808. Scalar.ToHex = function (i) {
  6809. var str = i.toString(16);
  6810. if (i <= 15) {
  6811. return ("0" + str).toUpperCase();
  6812. }
  6813. return str.toUpperCase();
  6814. };
  6815. /**
  6816. * Returns -1 if value is negative and +1 is value is positive.
  6817. * Returns the value itself if it's equal to zero.
  6818. */
  6819. Scalar.Sign = function (value) {
  6820. value = +value; // convert to a number
  6821. if (value === 0 || isNaN(value))
  6822. return value;
  6823. return value > 0 ? 1 : -1;
  6824. };
  6825. /**
  6826. * Returns the value itself if it's between min and max.
  6827. * Returns min if the value is lower than min.
  6828. * Returns max if the value is greater than max.
  6829. */
  6830. Scalar.Clamp = function (value, min, max) {
  6831. if (min === void 0) { min = 0; }
  6832. if (max === void 0) { max = 1; }
  6833. return Math.min(max, Math.max(min, value));
  6834. };
  6835. /**
  6836. * Returns the log2 of value.
  6837. */
  6838. Scalar.Log2 = function (value) {
  6839. return Math.log(value) * Math.LOG2E;
  6840. };
  6841. /**
  6842. * Loops the value, so that it is never larger than length and never smaller than 0.
  6843. *
  6844. * This is similar to the modulo operator but it works with floating point numbers.
  6845. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  6846. * With t = 5 and length = 2.5, the result would be 0.0.
  6847. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  6848. */
  6849. Scalar.Repeat = function (value, length) {
  6850. return value - Math.floor(value / length) * length;
  6851. };
  6852. /**
  6853. * Normalize the value between 0.0 and 1.0 using min and max values
  6854. */
  6855. Scalar.Normalize = function (value, min, max) {
  6856. return (value - min) / (max - min);
  6857. };
  6858. /**
  6859. * Denormalize the value from 0.0 and 1.0 using min and max values
  6860. */
  6861. Scalar.Denormalize = function (normalized, min, max) {
  6862. return (normalized * (max - min) + min);
  6863. };
  6864. /**
  6865. * Calculates the shortest difference between two given angles given in degrees.
  6866. */
  6867. Scalar.DeltaAngle = function (current, target) {
  6868. var num = Scalar.Repeat(target - current, 360.0);
  6869. if (num > 180.0) {
  6870. num -= 360.0;
  6871. }
  6872. return num;
  6873. };
  6874. /**
  6875. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  6876. *
  6877. * The returned value will move back and forth between 0 and length
  6878. */
  6879. Scalar.PingPong = function (tx, length) {
  6880. var t = Scalar.Repeat(tx, length * 2.0);
  6881. return length - Math.abs(t - length);
  6882. };
  6883. /**
  6884. * Interpolates between min and max with smoothing at the limits.
  6885. *
  6886. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  6887. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  6888. */
  6889. Scalar.SmoothStep = function (from, to, tx) {
  6890. var t = Scalar.Clamp(tx);
  6891. t = -2.0 * t * t * t + 3.0 * t * t;
  6892. return to * t + from * (1.0 - t);
  6893. };
  6894. /**
  6895. * Moves a value current towards target.
  6896. *
  6897. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  6898. * Negative values of maxDelta pushes the value away from target.
  6899. */
  6900. Scalar.MoveTowards = function (current, target, maxDelta) {
  6901. var result = 0;
  6902. if (Math.abs(target - current) <= maxDelta) {
  6903. result = target;
  6904. }
  6905. else {
  6906. result = current + Scalar.Sign(target - current) * maxDelta;
  6907. }
  6908. return result;
  6909. };
  6910. /**
  6911. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  6912. *
  6913. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  6914. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  6915. */
  6916. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  6917. var num = Scalar.DeltaAngle(current, target);
  6918. var result = 0;
  6919. if (-maxDelta < num && num < maxDelta) {
  6920. result = target;
  6921. }
  6922. else {
  6923. target = current + num;
  6924. result = Scalar.MoveTowards(current, target, maxDelta);
  6925. }
  6926. return result;
  6927. };
  6928. /**
  6929. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  6930. */
  6931. Scalar.Lerp = function (start, end, amount) {
  6932. return start + ((end - start) * amount);
  6933. };
  6934. /**
  6935. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  6936. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  6937. */
  6938. Scalar.LerpAngle = function (start, end, amount) {
  6939. var num = Scalar.Repeat(end - start, 360.0);
  6940. if (num > 180.0) {
  6941. num -= 360.0;
  6942. }
  6943. return start + num * Scalar.Clamp(amount);
  6944. };
  6945. /**
  6946. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  6947. */
  6948. Scalar.InverseLerp = function (a, b, value) {
  6949. var result = 0;
  6950. if (a != b) {
  6951. result = Scalar.Clamp((value - a) / (b - a));
  6952. }
  6953. else {
  6954. result = 0.0;
  6955. }
  6956. return result;
  6957. };
  6958. /**
  6959. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  6960. */
  6961. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  6962. var squared = amount * amount;
  6963. var cubed = amount * squared;
  6964. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  6965. var part2 = (-2.0 * cubed) + (3.0 * squared);
  6966. var part3 = (cubed - (2.0 * squared)) + amount;
  6967. var part4 = cubed - squared;
  6968. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  6969. };
  6970. /**
  6971. * Returns a random float number between and min and max values
  6972. */
  6973. Scalar.RandomRange = function (min, max) {
  6974. if (min === max)
  6975. return min;
  6976. return ((Math.random() * (max - min)) + min);
  6977. };
  6978. /**
  6979. * This function returns percentage of a number in a given range.
  6980. *
  6981. * RangeToPercent(40,20,60) will return 0.5 (50%)
  6982. * RangeToPercent(34,0,100) will return 0.34 (34%)
  6983. */
  6984. Scalar.RangeToPercent = function (number, min, max) {
  6985. return ((number - min) / (max - min));
  6986. };
  6987. /**
  6988. * This function returns number that corresponds to the percentage in a given range.
  6989. *
  6990. * PercentToRange(0.34,0,100) will return 34.
  6991. */
  6992. Scalar.PercentToRange = function (percent, min, max) {
  6993. return ((max - min) * percent + min);
  6994. };
  6995. /**
  6996. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  6997. * @param angle The angle to normalize in radian.
  6998. * @return The converted angle.
  6999. */
  7000. Scalar.NormalizeRadians = function (angle) {
  7001. // More precise but slower version kept for reference.
  7002. // angle = angle % Tools.TwoPi;
  7003. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  7004. //if (angle > Math.PI) {
  7005. // angle -= Tools.TwoPi;
  7006. //}
  7007. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  7008. return angle;
  7009. };
  7010. /**
  7011. * Two pi constants convenient for computation.
  7012. */
  7013. Scalar.TwoPi = Math.PI * 2;
  7014. return Scalar;
  7015. }());
  7016. BABYLON.Scalar = Scalar;
  7017. })(BABYLON || (BABYLON = {}));
  7018. //# sourceMappingURL=babylon.math.scalar.js.map
  7019. //# sourceMappingURL=babylon.mixins.js.map
  7020. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  7021. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  7022. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  7023. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  7024. //# sourceMappingURL=babylon.webgl2.js.map
  7025. var BABYLON;
  7026. (function (BABYLON) {
  7027. var __decoratorInitialStore = {};
  7028. var __mergedStore = {};
  7029. var _copySource = function (creationFunction, source, instanciate) {
  7030. var destination = creationFunction();
  7031. // Tags
  7032. if (BABYLON.Tags) {
  7033. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7034. }
  7035. var classStore = getMergedStore(destination);
  7036. // Properties
  7037. for (var property in classStore) {
  7038. var propertyDescriptor = classStore[property];
  7039. var sourceProperty = source[property];
  7040. var propertyType = propertyDescriptor.type;
  7041. if (sourceProperty !== undefined && sourceProperty !== null) {
  7042. switch (propertyType) {
  7043. case 0: // Value
  7044. case 6:// Mesh reference
  7045. destination[property] = sourceProperty;
  7046. break;
  7047. case 1:// Texture
  7048. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  7049. break;
  7050. case 2: // Color3
  7051. case 3: // FresnelParameters
  7052. case 4: // Vector2
  7053. case 5: // Vector3
  7054. case 7: // Color Curves
  7055. case 10:// Quaternion
  7056. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  7057. break;
  7058. }
  7059. }
  7060. }
  7061. return destination;
  7062. };
  7063. function getDirectStore(target) {
  7064. var classKey = target.getClassName();
  7065. if (!__decoratorInitialStore[classKey]) {
  7066. __decoratorInitialStore[classKey] = {};
  7067. }
  7068. return __decoratorInitialStore[classKey];
  7069. }
  7070. /**
  7071. * Return the list of properties flagged as serializable
  7072. * @param target: host object
  7073. */
  7074. function getMergedStore(target) {
  7075. var classKey = target.getClassName();
  7076. if (__mergedStore[classKey]) {
  7077. return __mergedStore[classKey];
  7078. }
  7079. __mergedStore[classKey] = {};
  7080. var store = __mergedStore[classKey];
  7081. var currentTarget = target;
  7082. var currentKey = classKey;
  7083. while (currentKey) {
  7084. var initialStore = __decoratorInitialStore[currentKey];
  7085. for (var property in initialStore) {
  7086. store[property] = initialStore[property];
  7087. }
  7088. var parent_1 = void 0;
  7089. var done = false;
  7090. do {
  7091. parent_1 = Object.getPrototypeOf(currentTarget);
  7092. if (!parent_1.getClassName) {
  7093. done = true;
  7094. break;
  7095. }
  7096. if (parent_1.getClassName() !== currentKey) {
  7097. break;
  7098. }
  7099. currentTarget = parent_1;
  7100. } while (parent_1);
  7101. if (done) {
  7102. break;
  7103. }
  7104. currentKey = parent_1.getClassName();
  7105. currentTarget = parent_1;
  7106. }
  7107. return store;
  7108. }
  7109. function generateSerializableMember(type, sourceName) {
  7110. return function (target, propertyKey) {
  7111. var classStore = getDirectStore(target);
  7112. if (!classStore[propertyKey]) {
  7113. classStore[propertyKey] = { type: type, sourceName: sourceName };
  7114. }
  7115. };
  7116. }
  7117. function generateExpandMember(setCallback, targetKey) {
  7118. if (targetKey === void 0) { targetKey = null; }
  7119. return function (target, propertyKey) {
  7120. var key = targetKey || ("_" + propertyKey);
  7121. Object.defineProperty(target, propertyKey, {
  7122. get: function () {
  7123. return this[key];
  7124. },
  7125. set: function (value) {
  7126. if (this[key] === value) {
  7127. return;
  7128. }
  7129. this[key] = value;
  7130. target[setCallback].apply(this);
  7131. },
  7132. enumerable: true,
  7133. configurable: true
  7134. });
  7135. };
  7136. }
  7137. function expandToProperty(callback, targetKey) {
  7138. if (targetKey === void 0) { targetKey = null; }
  7139. return generateExpandMember(callback, targetKey);
  7140. }
  7141. BABYLON.expandToProperty = expandToProperty;
  7142. function serialize(sourceName) {
  7143. return generateSerializableMember(0, sourceName); // value member
  7144. }
  7145. BABYLON.serialize = serialize;
  7146. function serializeAsTexture(sourceName) {
  7147. return generateSerializableMember(1, sourceName); // texture member
  7148. }
  7149. BABYLON.serializeAsTexture = serializeAsTexture;
  7150. function serializeAsColor3(sourceName) {
  7151. return generateSerializableMember(2, sourceName); // color3 member
  7152. }
  7153. BABYLON.serializeAsColor3 = serializeAsColor3;
  7154. function serializeAsFresnelParameters(sourceName) {
  7155. return generateSerializableMember(3, sourceName); // fresnel parameters member
  7156. }
  7157. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  7158. function serializeAsVector2(sourceName) {
  7159. return generateSerializableMember(4, sourceName); // vector2 member
  7160. }
  7161. BABYLON.serializeAsVector2 = serializeAsVector2;
  7162. function serializeAsVector3(sourceName) {
  7163. return generateSerializableMember(5, sourceName); // vector3 member
  7164. }
  7165. BABYLON.serializeAsVector3 = serializeAsVector3;
  7166. function serializeAsMeshReference(sourceName) {
  7167. return generateSerializableMember(6, sourceName); // mesh reference member
  7168. }
  7169. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  7170. function serializeAsColorCurves(sourceName) {
  7171. return generateSerializableMember(7, sourceName); // color curves
  7172. }
  7173. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  7174. function serializeAsColor4(sourceName) {
  7175. return generateSerializableMember(8, sourceName); // color 4
  7176. }
  7177. BABYLON.serializeAsColor4 = serializeAsColor4;
  7178. function serializeAsImageProcessingConfiguration(sourceName) {
  7179. return generateSerializableMember(9, sourceName); // image processing
  7180. }
  7181. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  7182. function serializeAsQuaternion(sourceName) {
  7183. return generateSerializableMember(10, sourceName); // quaternion member
  7184. }
  7185. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  7186. var SerializationHelper = /** @class */ (function () {
  7187. function SerializationHelper() {
  7188. }
  7189. SerializationHelper.Serialize = function (entity, serializationObject) {
  7190. if (!serializationObject) {
  7191. serializationObject = {};
  7192. }
  7193. // Tags
  7194. if (BABYLON.Tags) {
  7195. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  7196. }
  7197. var serializedProperties = getMergedStore(entity);
  7198. // Properties
  7199. for (var property in serializedProperties) {
  7200. var propertyDescriptor = serializedProperties[property];
  7201. var targetPropertyName = propertyDescriptor.sourceName || property;
  7202. var propertyType = propertyDescriptor.type;
  7203. var sourceProperty = entity[property];
  7204. if (sourceProperty !== undefined && sourceProperty !== null) {
  7205. switch (propertyType) {
  7206. case 0:// Value
  7207. serializationObject[targetPropertyName] = sourceProperty;
  7208. break;
  7209. case 1:// Texture
  7210. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7211. break;
  7212. case 2:// Color3
  7213. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7214. break;
  7215. case 3:// FresnelParameters
  7216. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7217. break;
  7218. case 4:// Vector2
  7219. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7220. break;
  7221. case 5:// Vector3
  7222. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7223. break;
  7224. case 6:// Mesh reference
  7225. serializationObject[targetPropertyName] = sourceProperty.id;
  7226. break;
  7227. case 7:// Color Curves
  7228. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7229. break;
  7230. case 8:// Color 4
  7231. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7232. break;
  7233. case 9:// Image Processing
  7234. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7235. break;
  7236. }
  7237. }
  7238. }
  7239. return serializationObject;
  7240. };
  7241. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  7242. if (rootUrl === void 0) { rootUrl = null; }
  7243. var destination = creationFunction();
  7244. if (!rootUrl) {
  7245. rootUrl = "";
  7246. }
  7247. // Tags
  7248. if (BABYLON.Tags) {
  7249. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7250. }
  7251. var classStore = getMergedStore(destination);
  7252. // Properties
  7253. for (var property in classStore) {
  7254. var propertyDescriptor = classStore[property];
  7255. var sourceProperty = source[propertyDescriptor.sourceName || property];
  7256. var propertyType = propertyDescriptor.type;
  7257. if (sourceProperty !== undefined && sourceProperty !== null) {
  7258. var dest = destination;
  7259. switch (propertyType) {
  7260. case 0:// Value
  7261. dest[property] = sourceProperty;
  7262. break;
  7263. case 1:// Texture
  7264. if (scene) {
  7265. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  7266. }
  7267. break;
  7268. case 2:// Color3
  7269. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  7270. break;
  7271. case 3:// FresnelParameters
  7272. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  7273. break;
  7274. case 4:// Vector2
  7275. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  7276. break;
  7277. case 5:// Vector3
  7278. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  7279. break;
  7280. case 6:// Mesh reference
  7281. if (scene) {
  7282. dest[property] = scene.getLastMeshByID(sourceProperty);
  7283. }
  7284. break;
  7285. case 7:// Color Curves
  7286. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  7287. break;
  7288. case 8:// Color 4
  7289. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  7290. break;
  7291. case 9:// Image Processing
  7292. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  7293. break;
  7294. }
  7295. }
  7296. }
  7297. return destination;
  7298. };
  7299. SerializationHelper.Clone = function (creationFunction, source) {
  7300. return _copySource(creationFunction, source, false);
  7301. };
  7302. SerializationHelper.Instanciate = function (creationFunction, source) {
  7303. return _copySource(creationFunction, source, true);
  7304. };
  7305. return SerializationHelper;
  7306. }());
  7307. BABYLON.SerializationHelper = SerializationHelper;
  7308. })(BABYLON || (BABYLON = {}));
  7309. //# sourceMappingURL=babylon.decorators.js.map
  7310. var BABYLON;
  7311. (function (BABYLON) {
  7312. /**
  7313. * Wrapper class for promise with external resolve and reject.
  7314. */
  7315. var Deferred = /** @class */ (function () {
  7316. /**
  7317. * Constructor for this deferred object.
  7318. */
  7319. function Deferred() {
  7320. var _this = this;
  7321. this.promise = new Promise(function (resolve, reject) {
  7322. _this._resolve = resolve;
  7323. _this._reject = reject;
  7324. });
  7325. }
  7326. Object.defineProperty(Deferred.prototype, "resolve", {
  7327. /**
  7328. * The resolve method of the promise associated with this deferred object.
  7329. */
  7330. get: function () {
  7331. return this._resolve;
  7332. },
  7333. enumerable: true,
  7334. configurable: true
  7335. });
  7336. Object.defineProperty(Deferred.prototype, "reject", {
  7337. /**
  7338. * The reject method of the promise associated with this deferred object.
  7339. */
  7340. get: function () {
  7341. return this._reject;
  7342. },
  7343. enumerable: true,
  7344. configurable: true
  7345. });
  7346. return Deferred;
  7347. }());
  7348. BABYLON.Deferred = Deferred;
  7349. })(BABYLON || (BABYLON = {}));
  7350. //# sourceMappingURL=babylon.deferred.js.map
  7351. var BABYLON;
  7352. (function (BABYLON) {
  7353. /**
  7354. * A class serves as a medium between the observable and its observers
  7355. */
  7356. var EventState = /** @class */ (function () {
  7357. /**
  7358. * Create a new EventState
  7359. * @param mask defines the mask associated with this state
  7360. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  7361. * @param target defines the original target of the state
  7362. * @param currentTarget defines the current target of the state
  7363. */
  7364. function EventState(mask, skipNextObservers, target, currentTarget) {
  7365. if (skipNextObservers === void 0) { skipNextObservers = false; }
  7366. this.initalize(mask, skipNextObservers, target, currentTarget);
  7367. }
  7368. /**
  7369. * Initialize the current event state
  7370. * @param mask defines the mask associated with this state
  7371. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  7372. * @param target defines the original target of the state
  7373. * @param currentTarget defines the current target of the state
  7374. * @returns the current event state
  7375. */
  7376. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  7377. if (skipNextObservers === void 0) { skipNextObservers = false; }
  7378. this.mask = mask;
  7379. this.skipNextObservers = skipNextObservers;
  7380. this.target = target;
  7381. this.currentTarget = currentTarget;
  7382. return this;
  7383. };
  7384. return EventState;
  7385. }());
  7386. BABYLON.EventState = EventState;
  7387. /**
  7388. * Represent an Observer registered to a given Observable object.
  7389. */
  7390. var Observer = /** @class */ (function () {
  7391. /**
  7392. * Creates a new observer
  7393. * @param callback defines the callback to call when the observer is notified
  7394. * @param mask defines the mask of the observer (used to filter notifications)
  7395. * @param scope defines the current scope used to restore the JS context
  7396. */
  7397. function Observer(
  7398. /**
  7399. * Defines the callback to call when the observer is notified
  7400. */
  7401. callback,
  7402. /**
  7403. * Defines the mask of the observer (used to filter notifications)
  7404. */
  7405. mask,
  7406. /**
  7407. * Defines the current scope used to restore the JS context
  7408. */
  7409. scope) {
  7410. if (scope === void 0) { scope = null; }
  7411. this.callback = callback;
  7412. this.mask = mask;
  7413. this.scope = scope;
  7414. /** @ignore */
  7415. this._willBeUnregistered = false;
  7416. /**
  7417. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  7418. */
  7419. this.unregisterOnNextCall = false;
  7420. }
  7421. return Observer;
  7422. }());
  7423. BABYLON.Observer = Observer;
  7424. /**
  7425. * Represent a list of observers registered to multiple Observables object.
  7426. */
  7427. var MultiObserver = /** @class */ (function () {
  7428. function MultiObserver() {
  7429. }
  7430. /**
  7431. * Release associated resources
  7432. */
  7433. MultiObserver.prototype.dispose = function () {
  7434. if (this._observers && this._observables) {
  7435. for (var index = 0; index < this._observers.length; index++) {
  7436. this._observables[index].remove(this._observers[index]);
  7437. }
  7438. }
  7439. this._observers = null;
  7440. this._observables = null;
  7441. };
  7442. /**
  7443. * Raise a callback when one of the observable will notify
  7444. * @param observables defines a list of observables to watch
  7445. * @param callback defines the callback to call on notification
  7446. * @param mask defines the mask used to filter notifications
  7447. * @param scope defines the current scope used to restore the JS context
  7448. * @returns the new MultiObserver
  7449. */
  7450. MultiObserver.Watch = function (observables, callback, mask, scope) {
  7451. if (mask === void 0) { mask = -1; }
  7452. if (scope === void 0) { scope = null; }
  7453. var result = new MultiObserver();
  7454. result._observers = new Array();
  7455. result._observables = observables;
  7456. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  7457. var observable = observables_1[_i];
  7458. var observer = observable.add(callback, mask, false, scope);
  7459. if (observer) {
  7460. result._observers.push(observer);
  7461. }
  7462. }
  7463. return result;
  7464. };
  7465. return MultiObserver;
  7466. }());
  7467. BABYLON.MultiObserver = MultiObserver;
  7468. /**
  7469. * The Observable class is a simple implementation of the Observable pattern.
  7470. * There's one slight particularity though: a given Observable can notify its observer using a particular mask value, only the Observers registered with this mask value will be notified.
  7471. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  7472. * For instance you may have a given Observable that have four different types of notifications: Move (mask = 0x01), Stop (mask = 0x02), Turn Right (mask = 0X04), Turn Left (mask = 0X08).
  7473. * A given observer can register itself with only Move and Stop (mask = 0x03), then it will only be notified when one of these two occurs and will never be for Turn Left/Right.
  7474. */
  7475. var Observable = /** @class */ (function () {
  7476. /**
  7477. * Creates a new observable
  7478. * @param onObserverAdded defines a callback to call when a new observer is added
  7479. */
  7480. function Observable(onObserverAdded) {
  7481. this._observers = new Array();
  7482. this._eventState = new EventState(0);
  7483. if (onObserverAdded) {
  7484. this._onObserverAdded = onObserverAdded;
  7485. }
  7486. }
  7487. /**
  7488. * Create a new Observer with the specified callback
  7489. * @param callback the callback that will be executed for that Observer
  7490. * @param mask the mask used to filter observers
  7491. * @param insertFirst if true the callback will be inserted at the first position, hence executed before the others ones. If false (default behavior) the callback will be inserted at the last position, executed after all the others already present.
  7492. * @param scope optional scope for the callback to be called from
  7493. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  7494. * @returns the new observer created for the callback
  7495. */
  7496. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  7497. if (mask === void 0) { mask = -1; }
  7498. if (insertFirst === void 0) { insertFirst = false; }
  7499. if (scope === void 0) { scope = null; }
  7500. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  7501. if (!callback) {
  7502. return null;
  7503. }
  7504. var observer = new Observer(callback, mask, scope);
  7505. observer.unregisterOnNextCall = unregisterOnFirstCall;
  7506. if (insertFirst) {
  7507. this._observers.unshift(observer);
  7508. }
  7509. else {
  7510. this._observers.push(observer);
  7511. }
  7512. if (this._onObserverAdded) {
  7513. this._onObserverAdded(observer);
  7514. }
  7515. return observer;
  7516. };
  7517. /**
  7518. * Remove an Observer from the Observable object
  7519. * @param observer the instance of the Observer to remove
  7520. * @returns false if it doesn't belong to this Observable
  7521. */
  7522. Observable.prototype.remove = function (observer) {
  7523. if (!observer) {
  7524. return false;
  7525. }
  7526. var index = this._observers.indexOf(observer);
  7527. if (index !== -1) {
  7528. this._observers.splice(index, 1);
  7529. return true;
  7530. }
  7531. return false;
  7532. };
  7533. /**
  7534. * Remove a callback from the Observable object
  7535. * @param callback the callback to remove
  7536. * @param scope optional scope. If used only the callbacks with this scope will be removed
  7537. * @returns false if it doesn't belong to this Observable
  7538. */
  7539. Observable.prototype.removeCallback = function (callback, scope) {
  7540. for (var index = 0; index < this._observers.length; index++) {
  7541. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  7542. this._observers.splice(index, 1);
  7543. return true;
  7544. }
  7545. }
  7546. return false;
  7547. };
  7548. Observable.prototype._deferUnregister = function (observer) {
  7549. var _this = this;
  7550. observer.unregisterOnNextCall = false;
  7551. observer._willBeUnregistered = true;
  7552. BABYLON.Tools.SetImmediate(function () {
  7553. _this.remove(observer);
  7554. });
  7555. };
  7556. /**
  7557. * Notify all Observers by calling their respective callback with the given data
  7558. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  7559. * @param eventData defines the data to send to all observers
  7560. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  7561. * @param target defines the original target of the state
  7562. * @param currentTarget defines the current target of the state
  7563. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  7564. */
  7565. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  7566. if (mask === void 0) { mask = -1; }
  7567. if (!this._observers.length) {
  7568. return true;
  7569. }
  7570. var state = this._eventState;
  7571. state.mask = mask;
  7572. state.target = target;
  7573. state.currentTarget = currentTarget;
  7574. state.skipNextObservers = false;
  7575. state.lastReturnValue = eventData;
  7576. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  7577. var obs = _a[_i];
  7578. if (obs._willBeUnregistered) {
  7579. continue;
  7580. }
  7581. if (obs.mask & mask) {
  7582. if (obs.scope) {
  7583. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  7584. }
  7585. else {
  7586. state.lastReturnValue = obs.callback(eventData, state);
  7587. }
  7588. if (obs.unregisterOnNextCall) {
  7589. this._deferUnregister(obs);
  7590. }
  7591. }
  7592. if (state.skipNextObservers) {
  7593. return false;
  7594. }
  7595. }
  7596. return true;
  7597. };
  7598. /**
  7599. * Calling this will execute each callback, expecting it to be a promise or return a value.
  7600. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  7601. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  7602. * and it is crucial that all callbacks will be executed.
  7603. * The order of the callbacks is kept, callbacks are not executed parallel.
  7604. *
  7605. * @param eventData The data to be sent to each callback
  7606. * @param mask is used to filter observers defaults to -1
  7607. * @param target defines the callback target (see EventState)
  7608. * @param currentTarget defines he current object in the bubbling phase
  7609. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  7610. */
  7611. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  7612. var _this = this;
  7613. if (mask === void 0) { mask = -1; }
  7614. // create an empty promise
  7615. var p = Promise.resolve(eventData);
  7616. // no observers? return this promise.
  7617. if (!this._observers.length) {
  7618. return p;
  7619. }
  7620. var state = this._eventState;
  7621. state.mask = mask;
  7622. state.target = target;
  7623. state.currentTarget = currentTarget;
  7624. state.skipNextObservers = false;
  7625. // execute one callback after another (not using Promise.all, the order is important)
  7626. this._observers.forEach(function (obs) {
  7627. if (state.skipNextObservers) {
  7628. return;
  7629. }
  7630. if (obs._willBeUnregistered) {
  7631. return;
  7632. }
  7633. if (obs.mask & mask) {
  7634. if (obs.scope) {
  7635. p = p.then(function (lastReturnedValue) {
  7636. state.lastReturnValue = lastReturnedValue;
  7637. return obs.callback.apply(obs.scope, [eventData, state]);
  7638. });
  7639. }
  7640. else {
  7641. p = p.then(function (lastReturnedValue) {
  7642. state.lastReturnValue = lastReturnedValue;
  7643. return obs.callback(eventData, state);
  7644. });
  7645. }
  7646. if (obs.unregisterOnNextCall) {
  7647. _this._deferUnregister(obs);
  7648. }
  7649. }
  7650. });
  7651. // return the eventData
  7652. return p.then(function () { return eventData; });
  7653. };
  7654. /**
  7655. * Notify a specific observer
  7656. * @param observer defines the observer to notify
  7657. * @param eventData defines the data to be sent to each callback
  7658. * @param mask is used to filter observers defaults to -1
  7659. */
  7660. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  7661. if (mask === void 0) { mask = -1; }
  7662. var state = this._eventState;
  7663. state.mask = mask;
  7664. state.skipNextObservers = false;
  7665. observer.callback(eventData, state);
  7666. };
  7667. /**
  7668. * Gets a boolean indicating if the observable has at least one observer
  7669. * @returns true is the Observable has at least one Observer registered
  7670. */
  7671. Observable.prototype.hasObservers = function () {
  7672. return this._observers.length > 0;
  7673. };
  7674. /**
  7675. * Clear the list of observers
  7676. */
  7677. Observable.prototype.clear = function () {
  7678. this._observers = new Array();
  7679. this._onObserverAdded = null;
  7680. };
  7681. /**
  7682. * Clone the current observable
  7683. * @returns a new observable
  7684. */
  7685. Observable.prototype.clone = function () {
  7686. var result = new Observable();
  7687. result._observers = this._observers.slice(0);
  7688. return result;
  7689. };
  7690. /**
  7691. * Does this observable handles observer registered with a given mask
  7692. * @param mask defines the mask to be tested
  7693. * @return whether or not one observer registered with the given mask is handeled
  7694. **/
  7695. Observable.prototype.hasSpecificMask = function (mask) {
  7696. if (mask === void 0) { mask = -1; }
  7697. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  7698. var obs = _a[_i];
  7699. if (obs.mask & mask || obs.mask === mask) {
  7700. return true;
  7701. }
  7702. }
  7703. return false;
  7704. };
  7705. return Observable;
  7706. }());
  7707. BABYLON.Observable = Observable;
  7708. })(BABYLON || (BABYLON = {}));
  7709. //# sourceMappingURL=babylon.observable.js.map
  7710. var BABYLON;
  7711. (function (BABYLON) {
  7712. var SmartArray = /** @class */ (function () {
  7713. function SmartArray(capacity) {
  7714. this.length = 0;
  7715. this.data = new Array(capacity);
  7716. this._id = SmartArray._GlobalId++;
  7717. }
  7718. SmartArray.prototype.push = function (value) {
  7719. this.data[this.length++] = value;
  7720. if (this.length > this.data.length) {
  7721. this.data.length *= 2;
  7722. }
  7723. };
  7724. SmartArray.prototype.forEach = function (func) {
  7725. for (var index = 0; index < this.length; index++) {
  7726. func(this.data[index]);
  7727. }
  7728. };
  7729. SmartArray.prototype.sort = function (compareFn) {
  7730. this.data.sort(compareFn);
  7731. };
  7732. SmartArray.prototype.reset = function () {
  7733. this.length = 0;
  7734. };
  7735. SmartArray.prototype.dispose = function () {
  7736. this.reset();
  7737. if (this.data) {
  7738. this.data.length = 0;
  7739. this.data = [];
  7740. }
  7741. };
  7742. SmartArray.prototype.concat = function (array) {
  7743. if (array.length === 0) {
  7744. return;
  7745. }
  7746. if (this.length + array.length > this.data.length) {
  7747. this.data.length = (this.length + array.length) * 2;
  7748. }
  7749. for (var index = 0; index < array.length; index++) {
  7750. this.data[this.length++] = (array.data || array)[index];
  7751. }
  7752. };
  7753. SmartArray.prototype.indexOf = function (value) {
  7754. var position = this.data.indexOf(value);
  7755. if (position >= this.length) {
  7756. return -1;
  7757. }
  7758. return position;
  7759. };
  7760. SmartArray.prototype.contains = function (value) {
  7761. return this.data.indexOf(value) !== -1;
  7762. };
  7763. // Statics
  7764. SmartArray._GlobalId = 0;
  7765. return SmartArray;
  7766. }());
  7767. BABYLON.SmartArray = SmartArray;
  7768. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  7769. __extends(SmartArrayNoDuplicate, _super);
  7770. function SmartArrayNoDuplicate() {
  7771. var _this = _super !== null && _super.apply(this, arguments) || this;
  7772. _this._duplicateId = 0;
  7773. return _this;
  7774. }
  7775. SmartArrayNoDuplicate.prototype.push = function (value) {
  7776. _super.prototype.push.call(this, value);
  7777. if (!value.__smartArrayFlags) {
  7778. value.__smartArrayFlags = {};
  7779. }
  7780. value.__smartArrayFlags[this._id] = this._duplicateId;
  7781. };
  7782. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  7783. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  7784. return false;
  7785. }
  7786. this.push(value);
  7787. return true;
  7788. };
  7789. SmartArrayNoDuplicate.prototype.reset = function () {
  7790. _super.prototype.reset.call(this);
  7791. this._duplicateId++;
  7792. };
  7793. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  7794. if (array.length === 0) {
  7795. return;
  7796. }
  7797. if (this.length + array.length > this.data.length) {
  7798. this.data.length = (this.length + array.length) * 2;
  7799. }
  7800. for (var index = 0; index < array.length; index++) {
  7801. var item = (array.data || array)[index];
  7802. this.pushNoDuplicate(item);
  7803. }
  7804. };
  7805. return SmartArrayNoDuplicate;
  7806. }(SmartArray));
  7807. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  7808. })(BABYLON || (BABYLON = {}));
  7809. //# sourceMappingURL=babylon.smartArray.js.map
  7810. var BABYLON;
  7811. (function (BABYLON) {
  7812. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  7813. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  7814. var LoadFileError = /** @class */ (function (_super) {
  7815. __extends(LoadFileError, _super);
  7816. function LoadFileError(message, request) {
  7817. var _this = _super.call(this, message) || this;
  7818. _this.request = request;
  7819. _this.name = "LoadFileError";
  7820. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  7821. return _this;
  7822. }
  7823. // Polyfill for Object.setPrototypeOf if necessary.
  7824. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  7825. return LoadFileError;
  7826. }(Error));
  7827. BABYLON.LoadFileError = LoadFileError;
  7828. var RetryStrategy = /** @class */ (function () {
  7829. function RetryStrategy() {
  7830. }
  7831. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  7832. if (maxRetries === void 0) { maxRetries = 3; }
  7833. if (baseInterval === void 0) { baseInterval = 500; }
  7834. return function (url, request, retryIndex) {
  7835. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  7836. return -1;
  7837. }
  7838. return Math.pow(2, retryIndex) * baseInterval;
  7839. };
  7840. };
  7841. return RetryStrategy;
  7842. }());
  7843. BABYLON.RetryStrategy = RetryStrategy;
  7844. // Screenshots
  7845. var screenshotCanvas;
  7846. var cloneValue = function (source, destinationObject) {
  7847. if (!source)
  7848. return null;
  7849. if (source instanceof BABYLON.Mesh) {
  7850. return null;
  7851. }
  7852. if (source instanceof BABYLON.SubMesh) {
  7853. return source.clone(destinationObject);
  7854. }
  7855. else if (source.clone) {
  7856. return source.clone();
  7857. }
  7858. return null;
  7859. };
  7860. var Tools = /** @class */ (function () {
  7861. function Tools() {
  7862. }
  7863. /**
  7864. * Interpolates between a and b via alpha
  7865. * @param a The lower value (returned when alpha = 0)
  7866. * @param b The upper value (returned when alpha = 1)
  7867. * @param alpha The interpolation-factor
  7868. * @return The mixed value
  7869. */
  7870. Tools.Mix = function (a, b, alpha) {
  7871. return a * (1 - alpha) + b * alpha;
  7872. };
  7873. Tools.Instantiate = function (className) {
  7874. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  7875. return Tools.RegisteredExternalClasses[className];
  7876. }
  7877. var arr = className.split(".");
  7878. var fn = (window || this);
  7879. for (var i = 0, len = arr.length; i < len; i++) {
  7880. fn = fn[arr[i]];
  7881. }
  7882. if (typeof fn !== "function") {
  7883. return null;
  7884. }
  7885. return fn;
  7886. };
  7887. /**
  7888. * Provides a slice function that will work even on IE
  7889. * @param data defines the array to slice
  7890. * @returns the new sliced array
  7891. */
  7892. Tools.Slice = function (data) {
  7893. if (data.slice) {
  7894. return data.slice();
  7895. }
  7896. return Array.prototype.slice.call(data);
  7897. };
  7898. Tools.SetImmediate = function (action) {
  7899. if (window.setImmediate) {
  7900. window.setImmediate(action);
  7901. }
  7902. else {
  7903. setTimeout(action, 1);
  7904. }
  7905. };
  7906. Tools.IsExponentOfTwo = function (value) {
  7907. var count = 1;
  7908. do {
  7909. count *= 2;
  7910. } while (count < value);
  7911. return count === value;
  7912. };
  7913. /**
  7914. * Find the next highest power of two.
  7915. * @param x Number to start search from.
  7916. * @return Next highest power of two.
  7917. */
  7918. Tools.CeilingPOT = function (x) {
  7919. x--;
  7920. x |= x >> 1;
  7921. x |= x >> 2;
  7922. x |= x >> 4;
  7923. x |= x >> 8;
  7924. x |= x >> 16;
  7925. x++;
  7926. return x;
  7927. };
  7928. /**
  7929. * Find the next lowest power of two.
  7930. * @param x Number to start search from.
  7931. * @return Next lowest power of two.
  7932. */
  7933. Tools.FloorPOT = function (x) {
  7934. x = x | (x >> 1);
  7935. x = x | (x >> 2);
  7936. x = x | (x >> 4);
  7937. x = x | (x >> 8);
  7938. x = x | (x >> 16);
  7939. return x - (x >> 1);
  7940. };
  7941. /**
  7942. * Find the nearest power of two.
  7943. * @param x Number to start search from.
  7944. * @return Next nearest power of two.
  7945. */
  7946. Tools.NearestPOT = function (x) {
  7947. var c = Tools.CeilingPOT(x);
  7948. var f = Tools.FloorPOT(x);
  7949. return (c - x) > (x - f) ? f : c;
  7950. };
  7951. Tools.GetExponentOfTwo = function (value, max, mode) {
  7952. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  7953. var pot;
  7954. switch (mode) {
  7955. case BABYLON.Engine.SCALEMODE_FLOOR:
  7956. pot = Tools.FloorPOT(value);
  7957. break;
  7958. case BABYLON.Engine.SCALEMODE_NEAREST:
  7959. pot = Tools.NearestPOT(value);
  7960. break;
  7961. case BABYLON.Engine.SCALEMODE_CEILING:
  7962. default:
  7963. pot = Tools.CeilingPOT(value);
  7964. break;
  7965. }
  7966. return Math.min(pot, max);
  7967. };
  7968. Tools.GetFilename = function (path) {
  7969. var index = path.lastIndexOf("/");
  7970. if (index < 0)
  7971. return path;
  7972. return path.substring(index + 1);
  7973. };
  7974. /**
  7975. * Extracts the "folder" part of a path (everything before the filename).
  7976. * @param uri The URI to extract the info from
  7977. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  7978. * @returns The "folder" part of the path
  7979. */
  7980. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  7981. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  7982. var index = uri.lastIndexOf("/");
  7983. if (index < 0) {
  7984. if (returnUnchangedIfNoSlash) {
  7985. return uri;
  7986. }
  7987. return "";
  7988. }
  7989. return uri.substring(0, index + 1);
  7990. };
  7991. Tools.GetDOMTextContent = function (element) {
  7992. var result = "";
  7993. var child = element.firstChild;
  7994. while (child) {
  7995. if (child.nodeType === 3) {
  7996. result += child.textContent;
  7997. }
  7998. child = child.nextSibling;
  7999. }
  8000. return result;
  8001. };
  8002. Tools.ToDegrees = function (angle) {
  8003. return angle * 180 / Math.PI;
  8004. };
  8005. Tools.ToRadians = function (angle) {
  8006. return angle * Math.PI / 180;
  8007. };
  8008. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  8009. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  8010. var output = "";
  8011. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  8012. var i = 0;
  8013. var bytes = new Uint8Array(buffer);
  8014. while (i < bytes.length) {
  8015. chr1 = bytes[i++];
  8016. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  8017. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  8018. enc1 = chr1 >> 2;
  8019. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  8020. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  8021. enc4 = chr3 & 63;
  8022. if (isNaN(chr2)) {
  8023. enc3 = enc4 = 64;
  8024. }
  8025. else if (isNaN(chr3)) {
  8026. enc4 = 64;
  8027. }
  8028. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  8029. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  8030. }
  8031. return "data:image/png;base64," + output;
  8032. };
  8033. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  8034. if (bias === void 0) { bias = null; }
  8035. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8036. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8037. for (var index = indexStart; index < indexStart + indexCount; index++) {
  8038. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  8039. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8040. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8041. }
  8042. if (bias) {
  8043. minimum.x -= minimum.x * bias.x + bias.y;
  8044. minimum.y -= minimum.y * bias.x + bias.y;
  8045. minimum.z -= minimum.z * bias.x + bias.y;
  8046. maximum.x += maximum.x * bias.x + bias.y;
  8047. maximum.y += maximum.y * bias.x + bias.y;
  8048. maximum.z += maximum.z * bias.x + bias.y;
  8049. }
  8050. return {
  8051. minimum: minimum,
  8052. maximum: maximum
  8053. };
  8054. };
  8055. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  8056. if (bias === void 0) { bias = null; }
  8057. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8058. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8059. if (!stride) {
  8060. stride = 3;
  8061. }
  8062. for (var index = start; index < start + count; index++) {
  8063. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  8064. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8065. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8066. }
  8067. if (bias) {
  8068. minimum.x -= minimum.x * bias.x + bias.y;
  8069. minimum.y -= minimum.y * bias.x + bias.y;
  8070. minimum.z -= minimum.z * bias.x + bias.y;
  8071. maximum.x += maximum.x * bias.x + bias.y;
  8072. maximum.y += maximum.y * bias.x + bias.y;
  8073. maximum.z += maximum.z * bias.x + bias.y;
  8074. }
  8075. return {
  8076. minimum: minimum,
  8077. maximum: maximum
  8078. };
  8079. };
  8080. Tools.Vector2ArrayFeeder = function (array) {
  8081. return function (index) {
  8082. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  8083. var length = isFloatArray ? array.length / 2 : array.length;
  8084. if (index >= length) {
  8085. return null;
  8086. }
  8087. if (isFloatArray) {
  8088. var fa = array;
  8089. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  8090. }
  8091. var a = array;
  8092. return a[index];
  8093. };
  8094. };
  8095. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  8096. if (bias === void 0) { bias = null; }
  8097. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  8098. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  8099. var i = 0;
  8100. var cur = feeder(i++);
  8101. while (cur) {
  8102. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  8103. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  8104. cur = feeder(i++);
  8105. }
  8106. if (bias) {
  8107. minimum.x -= minimum.x * bias.x + bias.y;
  8108. minimum.y -= minimum.y * bias.x + bias.y;
  8109. maximum.x += maximum.x * bias.x + bias.y;
  8110. maximum.y += maximum.y * bias.x + bias.y;
  8111. }
  8112. return {
  8113. minimum: minimum,
  8114. maximum: maximum
  8115. };
  8116. };
  8117. Tools.MakeArray = function (obj, allowsNullUndefined) {
  8118. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  8119. return null;
  8120. return Array.isArray(obj) ? obj : [obj];
  8121. };
  8122. // Misc.
  8123. Tools.GetPointerPrefix = function () {
  8124. var eventPrefix = "pointer";
  8125. // Check if pointer events are supported
  8126. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  8127. eventPrefix = "mouse";
  8128. }
  8129. return eventPrefix;
  8130. };
  8131. /**
  8132. * @param func - the function to be called
  8133. * @param requester - the object that will request the next frame. Falls back to window.
  8134. */
  8135. Tools.QueueNewFrame = function (func, requester) {
  8136. if (!Tools.IsWindowObjectExist()) {
  8137. return setTimeout(func, 16);
  8138. }
  8139. if (!requester) {
  8140. requester = window;
  8141. }
  8142. if (requester.requestAnimationFrame) {
  8143. return requester.requestAnimationFrame(func);
  8144. }
  8145. else if (requester.msRequestAnimationFrame) {
  8146. return requester.msRequestAnimationFrame(func);
  8147. }
  8148. else if (requester.webkitRequestAnimationFrame) {
  8149. return requester.webkitRequestAnimationFrame(func);
  8150. }
  8151. else if (requester.mozRequestAnimationFrame) {
  8152. return requester.mozRequestAnimationFrame(func);
  8153. }
  8154. else if (requester.oRequestAnimationFrame) {
  8155. return requester.oRequestAnimationFrame(func);
  8156. }
  8157. else {
  8158. return window.setTimeout(func, 16);
  8159. }
  8160. };
  8161. Tools.RequestFullscreen = function (element) {
  8162. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  8163. if (!requestFunction)
  8164. return;
  8165. requestFunction.call(element);
  8166. };
  8167. Tools.ExitFullscreen = function () {
  8168. if (document.exitFullscreen) {
  8169. document.exitFullscreen();
  8170. }
  8171. else if (document.mozCancelFullScreen) {
  8172. document.mozCancelFullScreen();
  8173. }
  8174. else if (document.webkitCancelFullScreen) {
  8175. document.webkitCancelFullScreen();
  8176. }
  8177. else if (document.msCancelFullScreen) {
  8178. document.msCancelFullScreen();
  8179. }
  8180. };
  8181. Tools.SetCorsBehavior = function (url, element) {
  8182. if (url && url.indexOf("data:") === 0) {
  8183. return;
  8184. }
  8185. if (Tools.CorsBehavior) {
  8186. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  8187. element.crossOrigin = Tools.CorsBehavior;
  8188. }
  8189. else {
  8190. var result = Tools.CorsBehavior(url);
  8191. if (result) {
  8192. element.crossOrigin = result;
  8193. }
  8194. }
  8195. }
  8196. };
  8197. // External files
  8198. Tools.CleanUrl = function (url) {
  8199. url = url.replace(/#/mg, "%23");
  8200. return url;
  8201. };
  8202. Tools.LoadImage = function (url, onLoad, onError, database) {
  8203. if (url instanceof ArrayBuffer) {
  8204. url = Tools.EncodeArrayBufferTobase64(url);
  8205. }
  8206. url = Tools.CleanUrl(url);
  8207. url = Tools.PreprocessUrl(url);
  8208. var img = new Image();
  8209. Tools.SetCorsBehavior(url, img);
  8210. var loadHandler = function () {
  8211. img.removeEventListener("load", loadHandler);
  8212. img.removeEventListener("error", errorHandler);
  8213. onLoad(img);
  8214. };
  8215. var errorHandler = function (err) {
  8216. img.removeEventListener("load", loadHandler);
  8217. img.removeEventListener("error", errorHandler);
  8218. Tools.Error("Error while trying to load image: " + url);
  8219. if (onError) {
  8220. onError("Error while trying to load image: " + url, err);
  8221. }
  8222. };
  8223. img.addEventListener("load", loadHandler);
  8224. img.addEventListener("error", errorHandler);
  8225. var noIndexedDB = function () {
  8226. img.src = url;
  8227. };
  8228. var loadFromIndexedDB = function () {
  8229. if (database) {
  8230. database.loadImageFromDB(url, img);
  8231. }
  8232. };
  8233. //ANY database to do!
  8234. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  8235. database.openAsync(loadFromIndexedDB, noIndexedDB);
  8236. }
  8237. else {
  8238. if (url.indexOf("file:") !== -1) {
  8239. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  8240. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  8241. try {
  8242. var blobURL;
  8243. try {
  8244. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  8245. }
  8246. catch (ex) {
  8247. // Chrome doesn't support oneTimeOnly parameter
  8248. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  8249. }
  8250. img.src = blobURL;
  8251. }
  8252. catch (e) {
  8253. img.src = "";
  8254. }
  8255. return img;
  8256. }
  8257. }
  8258. noIndexedDB();
  8259. }
  8260. return img;
  8261. };
  8262. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  8263. url = Tools.CleanUrl(url);
  8264. url = Tools.PreprocessUrl(url);
  8265. // If file and file input are set
  8266. if (url.indexOf("file:") !== -1) {
  8267. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  8268. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  8269. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  8270. }
  8271. }
  8272. var loadUrl = Tools.BaseUrl + url;
  8273. var aborted = false;
  8274. var fileRequest = {
  8275. onCompleteObservable: new BABYLON.Observable(),
  8276. abort: function () { return aborted = true; },
  8277. };
  8278. var requestFile = function () {
  8279. var request = new XMLHttpRequest();
  8280. var retryHandle = null;
  8281. fileRequest.abort = function () {
  8282. aborted = true;
  8283. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  8284. request.abort();
  8285. }
  8286. if (retryHandle !== null) {
  8287. clearTimeout(retryHandle);
  8288. retryHandle = null;
  8289. }
  8290. };
  8291. var retryLoop = function (retryIndex) {
  8292. request.open('GET', loadUrl, true);
  8293. if (useArrayBuffer) {
  8294. request.responseType = "arraybuffer";
  8295. }
  8296. if (onProgress) {
  8297. request.addEventListener("progress", onProgress);
  8298. }
  8299. var onLoadEnd = function () {
  8300. request.removeEventListener("loadend", onLoadEnd);
  8301. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  8302. fileRequest.onCompleteObservable.clear();
  8303. };
  8304. request.addEventListener("loadend", onLoadEnd);
  8305. var onReadyStateChange = function () {
  8306. if (aborted) {
  8307. return;
  8308. }
  8309. // In case of undefined state in some browsers.
  8310. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  8311. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  8312. request.removeEventListener("readystatechange", onReadyStateChange);
  8313. if (request.status >= 200 && request.status < 300 || (!Tools.IsWindowObjectExist() && (request.status === 0))) {
  8314. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  8315. return;
  8316. }
  8317. var retryStrategy = Tools.DefaultRetryStrategy;
  8318. if (retryStrategy) {
  8319. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  8320. if (waitTime !== -1) {
  8321. // Prevent the request from completing for retry.
  8322. request.removeEventListener("loadend", onLoadEnd);
  8323. request = new XMLHttpRequest();
  8324. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  8325. return;
  8326. }
  8327. }
  8328. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  8329. if (onError) {
  8330. onError(request, e);
  8331. }
  8332. else {
  8333. throw e;
  8334. }
  8335. }
  8336. };
  8337. request.addEventListener("readystatechange", onReadyStateChange);
  8338. request.send();
  8339. };
  8340. retryLoop(0);
  8341. };
  8342. // Caching all files
  8343. if (database && database.enableSceneOffline) {
  8344. var noIndexedDB_1 = function () {
  8345. if (!aborted) {
  8346. requestFile();
  8347. }
  8348. };
  8349. var loadFromIndexedDB = function () {
  8350. // TODO: database needs to support aborting and should return a IFileRequest
  8351. if (aborted) {
  8352. return;
  8353. }
  8354. if (database) {
  8355. database.loadFileFromDB(url, function (data) {
  8356. if (!aborted) {
  8357. onSuccess(data);
  8358. }
  8359. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  8360. }, onProgress ? function (event) {
  8361. if (!aborted) {
  8362. onProgress(event);
  8363. }
  8364. } : undefined, noIndexedDB_1, useArrayBuffer);
  8365. }
  8366. };
  8367. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  8368. }
  8369. else {
  8370. requestFile();
  8371. }
  8372. return fileRequest;
  8373. };
  8374. /**
  8375. * Load a script (identified by an url). When the url returns, the
  8376. * content of this file is added into a new script element, attached to the DOM (body element)
  8377. */
  8378. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  8379. var head = document.getElementsByTagName('head')[0];
  8380. var script = document.createElement('script');
  8381. script.type = 'text/javascript';
  8382. script.src = scriptUrl;
  8383. script.onload = function () {
  8384. if (onSuccess) {
  8385. onSuccess();
  8386. }
  8387. };
  8388. script.onerror = function (e) {
  8389. if (onError) {
  8390. onError("Unable to load script", e);
  8391. }
  8392. };
  8393. head.appendChild(script);
  8394. };
  8395. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  8396. var reader = new FileReader();
  8397. var request = {
  8398. onCompleteObservable: new BABYLON.Observable(),
  8399. abort: function () { return reader.abort(); },
  8400. };
  8401. reader.onloadend = function (e) {
  8402. request.onCompleteObservable.notifyObservers(request);
  8403. };
  8404. reader.onload = function (e) {
  8405. //target doesn't have result from ts 1.3
  8406. callback(e.target['result']);
  8407. };
  8408. reader.onprogress = progressCallback;
  8409. reader.readAsDataURL(fileToLoad);
  8410. return request;
  8411. };
  8412. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  8413. var reader = new FileReader();
  8414. var request = {
  8415. onCompleteObservable: new BABYLON.Observable(),
  8416. abort: function () { return reader.abort(); },
  8417. };
  8418. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  8419. reader.onerror = function (e) {
  8420. Tools.Log("Error while reading file: " + fileToLoad.name);
  8421. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  8422. };
  8423. reader.onload = function (e) {
  8424. //target doesn't have result from ts 1.3
  8425. callback(e.target['result']);
  8426. };
  8427. if (progressCallBack) {
  8428. reader.onprogress = progressCallBack;
  8429. }
  8430. if (!useArrayBuffer) {
  8431. // Asynchronous read
  8432. reader.readAsText(fileToLoad);
  8433. }
  8434. else {
  8435. reader.readAsArrayBuffer(fileToLoad);
  8436. }
  8437. return request;
  8438. };
  8439. //returns a downloadable url to a file content.
  8440. Tools.FileAsURL = function (content) {
  8441. var fileBlob = new Blob([content]);
  8442. var url = window.URL || window.webkitURL;
  8443. var link = url.createObjectURL(fileBlob);
  8444. return link;
  8445. };
  8446. // Misc.
  8447. Tools.Format = function (value, decimals) {
  8448. if (decimals === void 0) { decimals = 2; }
  8449. return value.toFixed(decimals);
  8450. };
  8451. Tools.CheckExtends = function (v, min, max) {
  8452. if (v.x < min.x)
  8453. min.x = v.x;
  8454. if (v.y < min.y)
  8455. min.y = v.y;
  8456. if (v.z < min.z)
  8457. min.z = v.z;
  8458. if (v.x > max.x)
  8459. max.x = v.x;
  8460. if (v.y > max.y)
  8461. max.y = v.y;
  8462. if (v.z > max.z)
  8463. max.z = v.z;
  8464. };
  8465. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  8466. for (var prop in source) {
  8467. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  8468. continue;
  8469. }
  8470. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  8471. continue;
  8472. }
  8473. var sourceValue = source[prop];
  8474. var typeOfSourceValue = typeof sourceValue;
  8475. if (typeOfSourceValue === "function") {
  8476. continue;
  8477. }
  8478. if (typeOfSourceValue === "object") {
  8479. if (sourceValue instanceof Array) {
  8480. destination[prop] = [];
  8481. if (sourceValue.length > 0) {
  8482. if (typeof sourceValue[0] == "object") {
  8483. for (var index = 0; index < sourceValue.length; index++) {
  8484. var clonedValue = cloneValue(sourceValue[index], destination);
  8485. if (destination[prop].indexOf(clonedValue) === -1) {
  8486. destination[prop].push(clonedValue);
  8487. }
  8488. }
  8489. }
  8490. else {
  8491. destination[prop] = sourceValue.slice(0);
  8492. }
  8493. }
  8494. }
  8495. else {
  8496. destination[prop] = cloneValue(sourceValue, destination);
  8497. }
  8498. }
  8499. else {
  8500. destination[prop] = sourceValue;
  8501. }
  8502. }
  8503. };
  8504. Tools.IsEmpty = function (obj) {
  8505. for (var i in obj) {
  8506. if (obj.hasOwnProperty(i)) {
  8507. return false;
  8508. }
  8509. }
  8510. return true;
  8511. };
  8512. Tools.RegisterTopRootEvents = function (events) {
  8513. for (var index = 0; index < events.length; index++) {
  8514. var event = events[index];
  8515. window.addEventListener(event.name, event.handler, false);
  8516. try {
  8517. if (window.parent) {
  8518. window.parent.addEventListener(event.name, event.handler, false);
  8519. }
  8520. }
  8521. catch (e) {
  8522. // Silently fails...
  8523. }
  8524. }
  8525. };
  8526. Tools.UnregisterTopRootEvents = function (events) {
  8527. for (var index = 0; index < events.length; index++) {
  8528. var event = events[index];
  8529. window.removeEventListener(event.name, event.handler);
  8530. try {
  8531. if (window.parent) {
  8532. window.parent.removeEventListener(event.name, event.handler);
  8533. }
  8534. }
  8535. catch (e) {
  8536. // Silently fails...
  8537. }
  8538. }
  8539. };
  8540. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  8541. if (mimeType === void 0) { mimeType = "image/png"; }
  8542. // Read the contents of the framebuffer
  8543. var numberOfChannelsByLine = width * 4;
  8544. var halfHeight = height / 2;
  8545. //Reading datas from WebGL
  8546. var data = engine.readPixels(0, 0, width, height);
  8547. //To flip image on Y axis.
  8548. for (var i = 0; i < halfHeight; i++) {
  8549. for (var j = 0; j < numberOfChannelsByLine; j++) {
  8550. var currentCell = j + i * numberOfChannelsByLine;
  8551. var targetLine = height - i - 1;
  8552. var targetCell = j + targetLine * numberOfChannelsByLine;
  8553. var temp = data[currentCell];
  8554. data[currentCell] = data[targetCell];
  8555. data[targetCell] = temp;
  8556. }
  8557. }
  8558. // Create a 2D canvas to store the result
  8559. if (!screenshotCanvas) {
  8560. screenshotCanvas = document.createElement('canvas');
  8561. }
  8562. screenshotCanvas.width = width;
  8563. screenshotCanvas.height = height;
  8564. var context = screenshotCanvas.getContext('2d');
  8565. if (context) {
  8566. // Copy the pixels to a 2D canvas
  8567. var imageData = context.createImageData(width, height);
  8568. var castData = (imageData.data);
  8569. castData.set(data);
  8570. context.putImageData(imageData, 0, 0);
  8571. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  8572. }
  8573. };
  8574. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  8575. if (mimeType === void 0) { mimeType = "image/png"; }
  8576. var base64Image = screenshotCanvas.toDataURL(mimeType);
  8577. if (successCallback) {
  8578. successCallback(base64Image);
  8579. }
  8580. else {
  8581. // We need HTMLCanvasElement.toBlob for HD screenshots
  8582. if (!screenshotCanvas.toBlob) {
  8583. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  8584. screenshotCanvas.toBlob = function (callback, type, quality) {
  8585. var _this = this;
  8586. setTimeout(function () {
  8587. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  8588. for (var i = 0; i < len; i++) {
  8589. arr[i] = binStr.charCodeAt(i);
  8590. }
  8591. callback(new Blob([arr], { type: type || 'image/png' }));
  8592. });
  8593. };
  8594. }
  8595. screenshotCanvas.toBlob(function (blob) {
  8596. var url = URL.createObjectURL(blob);
  8597. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  8598. if (("download" in document.createElement("a"))) {
  8599. var a = window.document.createElement("a");
  8600. a.href = url;
  8601. if (fileName) {
  8602. a.setAttribute("download", fileName);
  8603. }
  8604. else {
  8605. var date = new Date();
  8606. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  8607. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  8608. }
  8609. window.document.body.appendChild(a);
  8610. a.addEventListener("click", function () {
  8611. if (a.parentElement) {
  8612. a.parentElement.removeChild(a);
  8613. }
  8614. });
  8615. a.click();
  8616. }
  8617. else {
  8618. var newWindow = window.open("");
  8619. if (!newWindow)
  8620. return;
  8621. var img = newWindow.document.createElement("img");
  8622. img.onload = function () {
  8623. // no longer need to read the blob so it's revoked
  8624. URL.revokeObjectURL(url);
  8625. };
  8626. img.src = url;
  8627. newWindow.document.body.appendChild(img);
  8628. }
  8629. });
  8630. }
  8631. };
  8632. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  8633. if (mimeType === void 0) { mimeType = "image/png"; }
  8634. var width;
  8635. var height;
  8636. // If a precision value is specified
  8637. if (size.precision) {
  8638. width = Math.round(engine.getRenderWidth() * size.precision);
  8639. height = Math.round(width / engine.getAspectRatio(camera));
  8640. }
  8641. else if (size.width && size.height) {
  8642. width = size.width;
  8643. height = size.height;
  8644. }
  8645. else if (size.width && !size.height) {
  8646. width = size.width;
  8647. height = Math.round(width / engine.getAspectRatio(camera));
  8648. }
  8649. else if (size.height && !size.width) {
  8650. height = size.height;
  8651. width = Math.round(height * engine.getAspectRatio(camera));
  8652. }
  8653. else if (!isNaN(size)) {
  8654. height = size;
  8655. width = size;
  8656. }
  8657. else {
  8658. Tools.Error("Invalid 'size' parameter !");
  8659. return;
  8660. }
  8661. if (!screenshotCanvas) {
  8662. screenshotCanvas = document.createElement('canvas');
  8663. }
  8664. screenshotCanvas.width = width;
  8665. screenshotCanvas.height = height;
  8666. var renderContext = screenshotCanvas.getContext("2d");
  8667. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  8668. var newWidth = width;
  8669. var newHeight = newWidth / ratio;
  8670. if (newHeight > height) {
  8671. newHeight = height;
  8672. newWidth = newHeight * ratio;
  8673. }
  8674. var offsetX = Math.max(0, width - newWidth) / 2;
  8675. var offsetY = Math.max(0, height - newHeight) / 2;
  8676. var renderingCanvas = engine.getRenderingCanvas();
  8677. if (renderContext && renderingCanvas) {
  8678. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  8679. }
  8680. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  8681. };
  8682. /**
  8683. * Generates an image screenshot from the specified camera.
  8684. *
  8685. * @param engine The engine to use for rendering
  8686. * @param camera The camera to use for rendering
  8687. * @param size This parameter can be set to a single number or to an object with the
  8688. * following (optional) properties: precision, width, height. If a single number is passed,
  8689. * it will be used for both width and height. If an object is passed, the screenshot size
  8690. * will be derived from the parameters. The precision property is a multiplier allowing
  8691. * rendering at a higher or lower resolution.
  8692. * @param successCallback The callback receives a single parameter which contains the
  8693. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  8694. * src parameter of an <img> to display it.
  8695. * @param mimeType The MIME type of the screenshot image (default: image/png).
  8696. * Check your browser for supported MIME types.
  8697. * @param samples Texture samples (default: 1)
  8698. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  8699. * @param fileName A name for for the downloaded file.
  8700. * @constructor
  8701. */
  8702. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  8703. if (mimeType === void 0) { mimeType = "image/png"; }
  8704. if (samples === void 0) { samples = 1; }
  8705. if (antialiasing === void 0) { antialiasing = false; }
  8706. var width;
  8707. var height;
  8708. //If a precision value is specified
  8709. if (size.precision) {
  8710. width = Math.round(engine.getRenderWidth() * size.precision);
  8711. height = Math.round(width / engine.getAspectRatio(camera));
  8712. size = { width: width, height: height };
  8713. }
  8714. else if (size.width && size.height) {
  8715. width = size.width;
  8716. height = size.height;
  8717. }
  8718. else if (size.width && !size.height) {
  8719. width = size.width;
  8720. height = Math.round(width / engine.getAspectRatio(camera));
  8721. size = { width: width, height: height };
  8722. }
  8723. else if (size.height && !size.width) {
  8724. height = size.height;
  8725. width = Math.round(height * engine.getAspectRatio(camera));
  8726. size = { width: width, height: height };
  8727. }
  8728. else if (!isNaN(size)) {
  8729. height = size;
  8730. width = size;
  8731. }
  8732. else {
  8733. Tools.Error("Invalid 'size' parameter !");
  8734. return;
  8735. }
  8736. var scene = camera.getScene();
  8737. var previousCamera = null;
  8738. if (scene.activeCamera !== camera) {
  8739. previousCamera = scene.activeCamera;
  8740. scene.activeCamera = camera;
  8741. }
  8742. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  8743. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8744. texture.renderList = null;
  8745. texture.samples = samples;
  8746. if (antialiasing) {
  8747. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  8748. }
  8749. texture.onAfterRenderObservable.add(function () {
  8750. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  8751. });
  8752. scene.incrementRenderId();
  8753. scene.resetCachedMaterial();
  8754. texture.render(true);
  8755. texture.dispose();
  8756. if (previousCamera) {
  8757. scene.activeCamera = previousCamera;
  8758. }
  8759. camera.getProjectionMatrix(true); // Force cache refresh;
  8760. };
  8761. // XHR response validator for local file scenario
  8762. Tools.ValidateXHRData = function (xhr, dataType) {
  8763. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  8764. if (dataType === void 0) { dataType = 7; }
  8765. try {
  8766. if (dataType & 1) {
  8767. if (xhr.responseText && xhr.responseText.length > 0) {
  8768. return true;
  8769. }
  8770. else if (dataType === 1) {
  8771. return false;
  8772. }
  8773. }
  8774. if (dataType & 2) {
  8775. // Check header width and height since there is no "TGA" magic number
  8776. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  8777. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  8778. return true;
  8779. }
  8780. else if (dataType === 2) {
  8781. return false;
  8782. }
  8783. }
  8784. if (dataType & 4) {
  8785. // Check for the "DDS" magic number
  8786. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  8787. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  8788. return true;
  8789. }
  8790. else {
  8791. return false;
  8792. }
  8793. }
  8794. }
  8795. catch (e) {
  8796. // Global protection
  8797. }
  8798. return false;
  8799. };
  8800. /**
  8801. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  8802. * Be aware Math.random() could cause collisions, but:
  8803. * "All but 6 of the 128 bits of the ID are randomly generated, which means that for any two ids, there's a 1 in 2^^122 (or 5.3x10^^36) chance they'll collide"
  8804. */
  8805. Tools.RandomId = function () {
  8806. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  8807. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  8808. return v.toString(16);
  8809. });
  8810. };
  8811. /**
  8812. * Test if the given uri is a base64 string.
  8813. * @param uri The uri to test
  8814. * @return True if the uri is a base64 string or false otherwise.
  8815. */
  8816. Tools.IsBase64 = function (uri) {
  8817. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  8818. };
  8819. /**
  8820. * Decode the given base64 uri.
  8821. * @param uri The uri to decode
  8822. * @return The decoded base64 data.
  8823. */
  8824. Tools.DecodeBase64 = function (uri) {
  8825. var decodedString = atob(uri.split(",")[1]);
  8826. var bufferLength = decodedString.length;
  8827. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  8828. for (var i = 0; i < bufferLength; i++) {
  8829. bufferView[i] = decodedString.charCodeAt(i);
  8830. }
  8831. return bufferView.buffer;
  8832. };
  8833. Object.defineProperty(Tools, "NoneLogLevel", {
  8834. get: function () {
  8835. return Tools._NoneLogLevel;
  8836. },
  8837. enumerable: true,
  8838. configurable: true
  8839. });
  8840. Object.defineProperty(Tools, "MessageLogLevel", {
  8841. get: function () {
  8842. return Tools._MessageLogLevel;
  8843. },
  8844. enumerable: true,
  8845. configurable: true
  8846. });
  8847. Object.defineProperty(Tools, "WarningLogLevel", {
  8848. get: function () {
  8849. return Tools._WarningLogLevel;
  8850. },
  8851. enumerable: true,
  8852. configurable: true
  8853. });
  8854. Object.defineProperty(Tools, "ErrorLogLevel", {
  8855. get: function () {
  8856. return Tools._ErrorLogLevel;
  8857. },
  8858. enumerable: true,
  8859. configurable: true
  8860. });
  8861. Object.defineProperty(Tools, "AllLogLevel", {
  8862. get: function () {
  8863. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  8864. },
  8865. enumerable: true,
  8866. configurable: true
  8867. });
  8868. Tools._AddLogEntry = function (entry) {
  8869. Tools._LogCache = entry + Tools._LogCache;
  8870. if (Tools.OnNewCacheEntry) {
  8871. Tools.OnNewCacheEntry(entry);
  8872. }
  8873. };
  8874. Tools._FormatMessage = function (message) {
  8875. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  8876. var date = new Date();
  8877. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  8878. };
  8879. Tools._LogDisabled = function (message) {
  8880. // nothing to do
  8881. };
  8882. Tools._LogEnabled = function (message) {
  8883. var formattedMessage = Tools._FormatMessage(message);
  8884. console.log("BJS - " + formattedMessage);
  8885. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  8886. Tools._AddLogEntry(entry);
  8887. };
  8888. Tools._WarnDisabled = function (message) {
  8889. // nothing to do
  8890. };
  8891. Tools._WarnEnabled = function (message) {
  8892. var formattedMessage = Tools._FormatMessage(message);
  8893. console.warn("BJS - " + formattedMessage);
  8894. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  8895. Tools._AddLogEntry(entry);
  8896. };
  8897. Tools._ErrorDisabled = function (message) {
  8898. // nothing to do
  8899. };
  8900. Tools._ErrorEnabled = function (message) {
  8901. Tools.errorsCount++;
  8902. var formattedMessage = Tools._FormatMessage(message);
  8903. console.error("BJS - " + formattedMessage);
  8904. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  8905. Tools._AddLogEntry(entry);
  8906. };
  8907. Object.defineProperty(Tools, "LogCache", {
  8908. get: function () {
  8909. return Tools._LogCache;
  8910. },
  8911. enumerable: true,
  8912. configurable: true
  8913. });
  8914. Tools.ClearLogCache = function () {
  8915. Tools._LogCache = "";
  8916. Tools.errorsCount = 0;
  8917. };
  8918. Object.defineProperty(Tools, "LogLevels", {
  8919. set: function (level) {
  8920. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  8921. Tools.Log = Tools._LogEnabled;
  8922. }
  8923. else {
  8924. Tools.Log = Tools._LogDisabled;
  8925. }
  8926. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  8927. Tools.Warn = Tools._WarnEnabled;
  8928. }
  8929. else {
  8930. Tools.Warn = Tools._WarnDisabled;
  8931. }
  8932. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  8933. Tools.Error = Tools._ErrorEnabled;
  8934. }
  8935. else {
  8936. Tools.Error = Tools._ErrorDisabled;
  8937. }
  8938. },
  8939. enumerable: true,
  8940. configurable: true
  8941. });
  8942. Tools.IsWindowObjectExist = function () {
  8943. return (typeof window) !== "undefined";
  8944. };
  8945. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  8946. get: function () {
  8947. return Tools._PerformanceNoneLogLevel;
  8948. },
  8949. enumerable: true,
  8950. configurable: true
  8951. });
  8952. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  8953. get: function () {
  8954. return Tools._PerformanceUserMarkLogLevel;
  8955. },
  8956. enumerable: true,
  8957. configurable: true
  8958. });
  8959. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  8960. get: function () {
  8961. return Tools._PerformanceConsoleLogLevel;
  8962. },
  8963. enumerable: true,
  8964. configurable: true
  8965. });
  8966. Object.defineProperty(Tools, "PerformanceLogLevel", {
  8967. set: function (level) {
  8968. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  8969. Tools.StartPerformanceCounter = Tools._StartUserMark;
  8970. Tools.EndPerformanceCounter = Tools._EndUserMark;
  8971. return;
  8972. }
  8973. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  8974. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  8975. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  8976. return;
  8977. }
  8978. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  8979. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  8980. },
  8981. enumerable: true,
  8982. configurable: true
  8983. });
  8984. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  8985. };
  8986. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  8987. };
  8988. Tools._StartUserMark = function (counterName, condition) {
  8989. if (condition === void 0) { condition = true; }
  8990. if (!Tools._performance) {
  8991. if (!Tools.IsWindowObjectExist()) {
  8992. return;
  8993. }
  8994. Tools._performance = window.performance;
  8995. }
  8996. if (!condition || !Tools._performance.mark) {
  8997. return;
  8998. }
  8999. Tools._performance.mark(counterName + "-Begin");
  9000. };
  9001. Tools._EndUserMark = function (counterName, condition) {
  9002. if (condition === void 0) { condition = true; }
  9003. if (!condition || !Tools._performance.mark) {
  9004. return;
  9005. }
  9006. Tools._performance.mark(counterName + "-End");
  9007. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  9008. };
  9009. Tools._StartPerformanceConsole = function (counterName, condition) {
  9010. if (condition === void 0) { condition = true; }
  9011. if (!condition) {
  9012. return;
  9013. }
  9014. Tools._StartUserMark(counterName, condition);
  9015. if (console.time) {
  9016. console.time(counterName);
  9017. }
  9018. };
  9019. Tools._EndPerformanceConsole = function (counterName, condition) {
  9020. if (condition === void 0) { condition = true; }
  9021. if (!condition) {
  9022. return;
  9023. }
  9024. Tools._EndUserMark(counterName, condition);
  9025. if (console.time) {
  9026. console.timeEnd(counterName);
  9027. }
  9028. };
  9029. Object.defineProperty(Tools, "Now", {
  9030. get: function () {
  9031. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  9032. return window.performance.now();
  9033. }
  9034. return new Date().getTime();
  9035. },
  9036. enumerable: true,
  9037. configurable: true
  9038. });
  9039. /**
  9040. * This method will return the name of the class used to create the instance of the given object.
  9041. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  9042. * @param object the object to get the class name from
  9043. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  9044. */
  9045. Tools.GetClassName = function (object, isType) {
  9046. if (isType === void 0) { isType = false; }
  9047. var name = null;
  9048. if (!isType && object.getClassName) {
  9049. name = object.getClassName();
  9050. }
  9051. else {
  9052. if (object instanceof Object) {
  9053. var classObj = isType ? object : Object.getPrototypeOf(object);
  9054. name = classObj.constructor["__bjsclassName__"];
  9055. }
  9056. if (!name) {
  9057. name = typeof object;
  9058. }
  9059. }
  9060. return name;
  9061. };
  9062. Tools.First = function (array, predicate) {
  9063. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  9064. var el = array_1[_i];
  9065. if (predicate(el)) {
  9066. return el;
  9067. }
  9068. }
  9069. return null;
  9070. };
  9071. /**
  9072. * This method will return the name of the full name of the class, including its owning module (if any).
  9073. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator or implementing a method getClassName():string (in which case the module won't be specified).
  9074. * @param object the object to get the class name from
  9075. * @return a string that can have two forms: "moduleName.className" if module was specified when the class' Name was registered or "className" if there was not module specified.
  9076. */
  9077. Tools.getFullClassName = function (object, isType) {
  9078. if (isType === void 0) { isType = false; }
  9079. var className = null;
  9080. var moduleName = null;
  9081. if (!isType && object.getClassName) {
  9082. className = object.getClassName();
  9083. }
  9084. else {
  9085. if (object instanceof Object) {
  9086. var classObj = isType ? object : Object.getPrototypeOf(object);
  9087. className = classObj.constructor["__bjsclassName__"];
  9088. moduleName = classObj.constructor["__bjsmoduleName__"];
  9089. }
  9090. if (!className) {
  9091. className = typeof object;
  9092. }
  9093. }
  9094. if (!className) {
  9095. return null;
  9096. }
  9097. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  9098. };
  9099. /**
  9100. * This method can be used with hashCodeFromStream when your input is an array of values that are either: number, string, boolean or custom type implementing the getHashCode():number method.
  9101. * @param array
  9102. */
  9103. Tools.arrayOrStringFeeder = function (array) {
  9104. return function (index) {
  9105. if (index >= array.length) {
  9106. return null;
  9107. }
  9108. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  9109. if (val && val.getHashCode) {
  9110. val = val.getHashCode();
  9111. }
  9112. if (typeof val === "string") {
  9113. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  9114. }
  9115. return val;
  9116. };
  9117. };
  9118. /**
  9119. * Compute the hashCode of a stream of number
  9120. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  9121. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  9122. * @return the hash code computed
  9123. */
  9124. Tools.hashCodeFromStream = function (feeder) {
  9125. // Based from here: http://stackoverflow.com/a/7616484/802124
  9126. var hash = 0;
  9127. var index = 0;
  9128. var chr = feeder(index++);
  9129. while (chr != null) {
  9130. hash = ((hash << 5) - hash) + chr;
  9131. hash |= 0; // Convert to 32bit integer
  9132. chr = feeder(index++);
  9133. }
  9134. return hash;
  9135. };
  9136. /**
  9137. * Returns a promise that resolves after the given amount of time.
  9138. * @param delay Number of milliseconds to delay
  9139. * @returns Promise that resolves after the given amount of time
  9140. */
  9141. Tools.DelayAsync = function (delay) {
  9142. return new Promise(function (resolve) {
  9143. setTimeout(function () {
  9144. resolve();
  9145. }, delay);
  9146. });
  9147. };
  9148. Tools.BaseUrl = "";
  9149. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  9150. /**
  9151. * Default behaviour for cors in the application.
  9152. * It can be a string if the expected behavior is identical in the entire app.
  9153. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  9154. */
  9155. Tools.CorsBehavior = "anonymous";
  9156. Tools.UseFallbackTexture = true;
  9157. /**
  9158. * Use this object to register external classes like custom textures or material
  9159. * to allow the laoders to instantiate them
  9160. */
  9161. Tools.RegisteredExternalClasses = {};
  9162. // Used in case of a texture loading problem
  9163. Tools.fallbackTexture = "data:image/jpg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/4QBmRXhpZgAATU0AKgAAAAgABAEaAAUAAAABAAAAPgEbAAUAAAABAAAARgEoAAMAAAABAAIAAAExAAIAAAAQAAAATgAAAAAAAABgAAAAAQAAAGAAAAABcGFpbnQubmV0IDQuMC41AP/bAEMABAIDAwMCBAMDAwQEBAQFCQYFBQUFCwgIBgkNCw0NDQsMDA4QFBEODxMPDAwSGBITFRYXFxcOERkbGRYaFBYXFv/bAEMBBAQEBQUFCgYGChYPDA8WFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFv/AABEIAQABAAMBIgACEQEDEQH/xAAfAAABBQEBAQEBAQAAAAAAAAAAAQIDBAUGBwgJCgv/xAC1EAACAQMDAgQDBQUEBAAAAX0BAgMABBEFEiExQQYTUWEHInEUMoGRoQgjQrHBFVLR8CQzYnKCCQoWFxgZGiUmJygpKjQ1Njc4OTpDREVGR0hJSlNUVVZXWFlaY2RlZmdoaWpzdHV2d3h5eoOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4eLj5OXm5+jp6vHy8/T19vf4+fr/xAAfAQADAQEBAQEBAQEBAAAAAAAAAQIDBAUGBwgJCgv/xAC1EQACAQIEBAMEBwUEBAABAncAAQIDEQQFITEGEkFRB2FxEyIygQgUQpGhscEJIzNS8BVictEKFiQ04SXxFxgZGiYnKCkqNTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqCg4SFhoeIiYqSk5SVlpeYmZqio6Slpqeoqaqys7S1tre4ubrCw8TFxsfIycrS09TV1tfY2dri4+Tl5ufo6ery8/T19vf4+fr/2gAMAwEAAhEDEQA/APH6KKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76P//Z";
  9164. Tools.PreprocessUrl = function (url) {
  9165. return url;
  9166. };
  9167. // Logs
  9168. Tools._NoneLogLevel = 0;
  9169. Tools._MessageLogLevel = 1;
  9170. Tools._WarningLogLevel = 2;
  9171. Tools._ErrorLogLevel = 4;
  9172. Tools._LogCache = "";
  9173. Tools.errorsCount = 0;
  9174. Tools.Log = Tools._LogEnabled;
  9175. Tools.Warn = Tools._WarnEnabled;
  9176. Tools.Error = Tools._ErrorEnabled;
  9177. // Performances
  9178. Tools._PerformanceNoneLogLevel = 0;
  9179. Tools._PerformanceUserMarkLogLevel = 1;
  9180. Tools._PerformanceConsoleLogLevel = 2;
  9181. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9182. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9183. return Tools;
  9184. }());
  9185. BABYLON.Tools = Tools;
  9186. /**
  9187. * This class is used to track a performance counter which is number based.
  9188. * The user has access to many properties which give statistics of different nature
  9189. *
  9190. * The implementer can track two kinds of Performance Counter: time and count
  9191. * For time you can optionally call fetchNewFrame() to notify the start of a new frame to monitor, then call beginMonitoring() to start and endMonitoring() to record the lapsed time. endMonitoring takes a newFrame parameter for you to specify if the monitored time should be set for a new frame or accumulated to the current frame being monitored.
  9192. * For count you first have to call fetchNewFrame() to notify the start of a new frame to monitor, then call addCount() how many time required to increment the count value you monitor.
  9193. */
  9194. var PerfCounter = /** @class */ (function () {
  9195. function PerfCounter() {
  9196. this._startMonitoringTime = 0;
  9197. this._min = 0;
  9198. this._max = 0;
  9199. this._average = 0;
  9200. this._lastSecAverage = 0;
  9201. this._current = 0;
  9202. this._totalValueCount = 0;
  9203. this._totalAccumulated = 0;
  9204. this._lastSecAccumulated = 0;
  9205. this._lastSecTime = 0;
  9206. this._lastSecValueCount = 0;
  9207. }
  9208. Object.defineProperty(PerfCounter.prototype, "min", {
  9209. /**
  9210. * Returns the smallest value ever
  9211. */
  9212. get: function () {
  9213. return this._min;
  9214. },
  9215. enumerable: true,
  9216. configurable: true
  9217. });
  9218. Object.defineProperty(PerfCounter.prototype, "max", {
  9219. /**
  9220. * Returns the biggest value ever
  9221. */
  9222. get: function () {
  9223. return this._max;
  9224. },
  9225. enumerable: true,
  9226. configurable: true
  9227. });
  9228. Object.defineProperty(PerfCounter.prototype, "average", {
  9229. /**
  9230. * Returns the average value since the performance counter is running
  9231. */
  9232. get: function () {
  9233. return this._average;
  9234. },
  9235. enumerable: true,
  9236. configurable: true
  9237. });
  9238. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  9239. /**
  9240. * Returns the average value of the last second the counter was monitored
  9241. */
  9242. get: function () {
  9243. return this._lastSecAverage;
  9244. },
  9245. enumerable: true,
  9246. configurable: true
  9247. });
  9248. Object.defineProperty(PerfCounter.prototype, "current", {
  9249. /**
  9250. * Returns the current value
  9251. */
  9252. get: function () {
  9253. return this._current;
  9254. },
  9255. enumerable: true,
  9256. configurable: true
  9257. });
  9258. Object.defineProperty(PerfCounter.prototype, "total", {
  9259. get: function () {
  9260. return this._totalAccumulated;
  9261. },
  9262. enumerable: true,
  9263. configurable: true
  9264. });
  9265. Object.defineProperty(PerfCounter.prototype, "count", {
  9266. get: function () {
  9267. return this._totalValueCount;
  9268. },
  9269. enumerable: true,
  9270. configurable: true
  9271. });
  9272. /**
  9273. * Call this method to start monitoring a new frame.
  9274. * This scenario is typically used when you accumulate monitoring time many times for a single frame, you call this method at the start of the frame, then beginMonitoring to start recording and endMonitoring(false) to accumulated the recorded time to the PerfCounter or addCount() to accumulate a monitored count.
  9275. */
  9276. PerfCounter.prototype.fetchNewFrame = function () {
  9277. this._totalValueCount++;
  9278. this._current = 0;
  9279. this._lastSecValueCount++;
  9280. };
  9281. /**
  9282. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  9283. * @param newCount the count value to add to the monitored count
  9284. * @param fetchResult true when it's the last time in the frame you add to the counter and you wish to update the statistics properties (min/max/average), false if you only want to update statistics.
  9285. */
  9286. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  9287. if (!PerfCounter.Enabled) {
  9288. return;
  9289. }
  9290. this._current += newCount;
  9291. if (fetchResult) {
  9292. this._fetchResult();
  9293. }
  9294. };
  9295. /**
  9296. * Start monitoring this performance counter
  9297. */
  9298. PerfCounter.prototype.beginMonitoring = function () {
  9299. if (!PerfCounter.Enabled) {
  9300. return;
  9301. }
  9302. this._startMonitoringTime = Tools.Now;
  9303. };
  9304. /**
  9305. * Compute the time lapsed since the previous beginMonitoring() call.
  9306. * @param newFrame true by default to fetch the result and monitor a new frame, if false the time monitored will be added to the current frame counter
  9307. */
  9308. PerfCounter.prototype.endMonitoring = function (newFrame) {
  9309. if (newFrame === void 0) { newFrame = true; }
  9310. if (!PerfCounter.Enabled) {
  9311. return;
  9312. }
  9313. if (newFrame) {
  9314. this.fetchNewFrame();
  9315. }
  9316. var currentTime = Tools.Now;
  9317. this._current = currentTime - this._startMonitoringTime;
  9318. if (newFrame) {
  9319. this._fetchResult();
  9320. }
  9321. };
  9322. PerfCounter.prototype._fetchResult = function () {
  9323. this._totalAccumulated += this._current;
  9324. this._lastSecAccumulated += this._current;
  9325. // Min/Max update
  9326. this._min = Math.min(this._min, this._current);
  9327. this._max = Math.max(this._max, this._current);
  9328. this._average = this._totalAccumulated / this._totalValueCount;
  9329. // Reset last sec?
  9330. var now = Tools.Now;
  9331. if ((now - this._lastSecTime) > 1000) {
  9332. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  9333. this._lastSecTime = now;
  9334. this._lastSecAccumulated = 0;
  9335. this._lastSecValueCount = 0;
  9336. }
  9337. };
  9338. PerfCounter.Enabled = true;
  9339. return PerfCounter;
  9340. }());
  9341. BABYLON.PerfCounter = PerfCounter;
  9342. /**
  9343. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  9344. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  9345. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  9346. * @param name The name of the class, case should be preserved
  9347. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  9348. */
  9349. function className(name, module) {
  9350. return function (target) {
  9351. target["__bjsclassName__"] = name;
  9352. target["__bjsmoduleName__"] = (module != null) ? module : null;
  9353. };
  9354. }
  9355. BABYLON.className = className;
  9356. /**
  9357. * An implementation of a loop for asynchronous functions.
  9358. */
  9359. var AsyncLoop = /** @class */ (function () {
  9360. /**
  9361. * Constroctor.
  9362. * @param iterations the number of iterations.
  9363. * @param _fn the function to run each iteration
  9364. * @param _successCallback the callback that will be called upon succesful execution
  9365. * @param offset starting offset.
  9366. */
  9367. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  9368. if (offset === void 0) { offset = 0; }
  9369. this.iterations = iterations;
  9370. this._fn = _fn;
  9371. this._successCallback = _successCallback;
  9372. this.index = offset - 1;
  9373. this._done = false;
  9374. }
  9375. /**
  9376. * Execute the next iteration. Must be called after the last iteration was finished.
  9377. */
  9378. AsyncLoop.prototype.executeNext = function () {
  9379. if (!this._done) {
  9380. if (this.index + 1 < this.iterations) {
  9381. ++this.index;
  9382. this._fn(this);
  9383. }
  9384. else {
  9385. this.breakLoop();
  9386. }
  9387. }
  9388. };
  9389. /**
  9390. * Break the loop and run the success callback.
  9391. */
  9392. AsyncLoop.prototype.breakLoop = function () {
  9393. this._done = true;
  9394. this._successCallback();
  9395. };
  9396. /**
  9397. * Helper function
  9398. */
  9399. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  9400. if (offset === void 0) { offset = 0; }
  9401. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  9402. loop.executeNext();
  9403. return loop;
  9404. };
  9405. /**
  9406. * A for-loop that will run a given number of iterations synchronous and the rest async.
  9407. * @param iterations total number of iterations
  9408. * @param syncedIterations number of synchronous iterations in each async iteration.
  9409. * @param fn the function to call each iteration.
  9410. * @param callback a success call back that will be called when iterating stops.
  9411. * @param breakFunction a break condition (optional)
  9412. * @param timeout timeout settings for the setTimeout function. default - 0.
  9413. * @constructor
  9414. */
  9415. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  9416. if (timeout === void 0) { timeout = 0; }
  9417. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  9418. if (breakFunction && breakFunction())
  9419. loop.breakLoop();
  9420. else {
  9421. setTimeout(function () {
  9422. for (var i = 0; i < syncedIterations; ++i) {
  9423. var iteration = (loop.index * syncedIterations) + i;
  9424. if (iteration >= iterations)
  9425. break;
  9426. fn(iteration);
  9427. if (breakFunction && breakFunction()) {
  9428. loop.breakLoop();
  9429. break;
  9430. }
  9431. }
  9432. loop.executeNext();
  9433. }, timeout);
  9434. }
  9435. }, callback);
  9436. };
  9437. return AsyncLoop;
  9438. }());
  9439. BABYLON.AsyncLoop = AsyncLoop;
  9440. })(BABYLON || (BABYLON = {}));
  9441. //# sourceMappingURL=babylon.tools.js.map
  9442. var BABYLON;
  9443. (function (BABYLON) {
  9444. var PromiseStates;
  9445. (function (PromiseStates) {
  9446. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  9447. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  9448. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  9449. })(PromiseStates || (PromiseStates = {}));
  9450. var FulFillmentAgregator = /** @class */ (function () {
  9451. function FulFillmentAgregator() {
  9452. this.count = 0;
  9453. this.target = 0;
  9454. this.results = [];
  9455. }
  9456. return FulFillmentAgregator;
  9457. }());
  9458. var InternalPromise = /** @class */ (function () {
  9459. function InternalPromise(resolver) {
  9460. var _this = this;
  9461. this._state = PromiseStates.Pending;
  9462. this._children = new Array();
  9463. this._rejectWasConsumed = false;
  9464. if (!resolver) {
  9465. return;
  9466. }
  9467. try {
  9468. resolver(function (value) {
  9469. _this._resolve(value);
  9470. }, function (reason) {
  9471. _this._reject(reason);
  9472. });
  9473. }
  9474. catch (e) {
  9475. this._reject(e);
  9476. }
  9477. }
  9478. InternalPromise.prototype.catch = function (onRejected) {
  9479. return this.then(undefined, onRejected);
  9480. };
  9481. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  9482. var _this = this;
  9483. var newPromise = new InternalPromise();
  9484. newPromise._onFulfilled = onFulfilled;
  9485. newPromise._onRejected = onRejected;
  9486. // Composition
  9487. this._children.push(newPromise);
  9488. if (this._state !== PromiseStates.Pending) {
  9489. BABYLON.Tools.SetImmediate(function () {
  9490. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  9491. var returnedValue = newPromise._resolve(_this._result);
  9492. if (returnedValue !== undefined && returnedValue !== null) {
  9493. if (returnedValue._state !== undefined) {
  9494. var returnedPromise = returnedValue;
  9495. newPromise._children.push(returnedPromise);
  9496. newPromise = returnedPromise;
  9497. }
  9498. else {
  9499. newPromise._result = returnedValue;
  9500. }
  9501. }
  9502. }
  9503. else {
  9504. newPromise._reject(_this._reason);
  9505. }
  9506. });
  9507. }
  9508. return newPromise;
  9509. };
  9510. InternalPromise.prototype._moveChildren = function (children) {
  9511. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  9512. if (this._state === PromiseStates.Fulfilled) {
  9513. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  9514. var child = _b[_i];
  9515. child._resolve(this._result);
  9516. }
  9517. }
  9518. else if (this._state === PromiseStates.Rejected) {
  9519. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  9520. var child = _d[_c];
  9521. child._reject(this._reason);
  9522. }
  9523. }
  9524. var _a;
  9525. };
  9526. InternalPromise.prototype._resolve = function (value) {
  9527. try {
  9528. this._state = PromiseStates.Fulfilled;
  9529. this._result = value;
  9530. var returnedValue = null;
  9531. if (this._onFulfilled) {
  9532. returnedValue = this._onFulfilled(value);
  9533. }
  9534. if (returnedValue !== undefined && returnedValue !== null) {
  9535. if (returnedValue._state !== undefined) {
  9536. // Transmit children
  9537. var returnedPromise = returnedValue;
  9538. returnedPromise._moveChildren(this._children);
  9539. }
  9540. else {
  9541. value = returnedValue;
  9542. }
  9543. }
  9544. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  9545. var child = _a[_i];
  9546. child._resolve(value);
  9547. }
  9548. this._children.length = 0;
  9549. delete this._onFulfilled;
  9550. delete this._onRejected;
  9551. return returnedValue;
  9552. }
  9553. catch (e) {
  9554. this._reject(e, true);
  9555. }
  9556. return null;
  9557. };
  9558. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  9559. if (onLocalThrow === void 0) { onLocalThrow = false; }
  9560. this._state = PromiseStates.Rejected;
  9561. this._reason = reason;
  9562. if (this._onRejected && !onLocalThrow) {
  9563. try {
  9564. this._onRejected(reason);
  9565. this._rejectWasConsumed = true;
  9566. }
  9567. catch (e) {
  9568. reason = e;
  9569. }
  9570. }
  9571. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  9572. var child = _a[_i];
  9573. if (this._rejectWasConsumed) {
  9574. child._resolve(null);
  9575. }
  9576. else {
  9577. child._reject(reason);
  9578. }
  9579. }
  9580. this._children.length = 0;
  9581. delete this._onFulfilled;
  9582. delete this._onRejected;
  9583. };
  9584. InternalPromise.resolve = function (value) {
  9585. var newPromise = new InternalPromise();
  9586. newPromise._resolve(value);
  9587. return newPromise;
  9588. };
  9589. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  9590. promise.then(function (value) {
  9591. agregator.results[index] = value;
  9592. agregator.count++;
  9593. if (agregator.count === agregator.target) {
  9594. agregator.rootPromise._resolve(agregator.results);
  9595. }
  9596. return null;
  9597. }, function (reason) {
  9598. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  9599. agregator.rootPromise._reject(reason);
  9600. }
  9601. });
  9602. };
  9603. InternalPromise.all = function (promises) {
  9604. var newPromise = new InternalPromise();
  9605. var agregator = new FulFillmentAgregator();
  9606. agregator.target = promises.length;
  9607. agregator.rootPromise = newPromise;
  9608. if (promises.length) {
  9609. for (var index = 0; index < promises.length; index++) {
  9610. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  9611. }
  9612. }
  9613. else {
  9614. newPromise._resolve([]);
  9615. }
  9616. return newPromise;
  9617. };
  9618. InternalPromise.race = function (promises) {
  9619. var newPromise = new InternalPromise();
  9620. if (promises.length) {
  9621. for (var _i = 0, promises_1 = promises; _i < promises_1.length; _i++) {
  9622. var promise = promises_1[_i];
  9623. promise.then(function (value) {
  9624. if (newPromise) {
  9625. newPromise._resolve(value);
  9626. newPromise = null;
  9627. }
  9628. return null;
  9629. }, function (reason) {
  9630. if (newPromise) {
  9631. newPromise._reject(reason);
  9632. newPromise = null;
  9633. }
  9634. });
  9635. }
  9636. }
  9637. return newPromise;
  9638. };
  9639. return InternalPromise;
  9640. }());
  9641. /**
  9642. * Helper class that provides a small promise polyfill
  9643. */
  9644. var PromisePolyfill = /** @class */ (function () {
  9645. function PromisePolyfill() {
  9646. }
  9647. /**
  9648. * Static function used to check if the polyfill is required
  9649. * If this is the case then the function will inject the polyfill to window.Promise
  9650. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  9651. */
  9652. PromisePolyfill.Apply = function (force) {
  9653. if (force === void 0) { force = false; }
  9654. if (force || typeof Promise === 'undefined') {
  9655. var root = window;
  9656. root.Promise = InternalPromise;
  9657. }
  9658. };
  9659. return PromisePolyfill;
  9660. }());
  9661. BABYLON.PromisePolyfill = PromisePolyfill;
  9662. })(BABYLON || (BABYLON = {}));
  9663. //# sourceMappingURL=babylon.promise.js.map
  9664. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  9665. var BABYLON;
  9666. (function (BABYLON) {
  9667. /**
  9668. * Helper class to push actions to a pool of workers.
  9669. */
  9670. var WorkerPool = /** @class */ (function () {
  9671. /**
  9672. * Constructor
  9673. * @param workers Array of workers to use for actions
  9674. */
  9675. function WorkerPool(workers) {
  9676. this._pendingActions = new Array();
  9677. this._workerInfos = workers.map(function (worker) { return ({
  9678. worker: worker,
  9679. active: false
  9680. }); });
  9681. }
  9682. /**
  9683. * Terminates all workers and clears any pending actions.
  9684. */
  9685. WorkerPool.prototype.dispose = function () {
  9686. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  9687. var workerInfo = _a[_i];
  9688. workerInfo.worker.terminate();
  9689. }
  9690. delete this._workerInfos;
  9691. delete this._pendingActions;
  9692. };
  9693. /**
  9694. * Pushes an action to the worker pool. If all the workers are active, the action will be
  9695. * pended until a worker has completed its action.
  9696. * @param action The action to perform. Call onComplete when the action is complete.
  9697. */
  9698. WorkerPool.prototype.push = function (action) {
  9699. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  9700. var workerInfo = _a[_i];
  9701. if (!workerInfo.active) {
  9702. this._execute(workerInfo, action);
  9703. return;
  9704. }
  9705. }
  9706. this._pendingActions.push(action);
  9707. };
  9708. WorkerPool.prototype._execute = function (workerInfo, action) {
  9709. var _this = this;
  9710. workerInfo.active = true;
  9711. action(workerInfo.worker, function () {
  9712. workerInfo.active = false;
  9713. var nextAction = _this._pendingActions.shift();
  9714. if (nextAction) {
  9715. _this._execute(workerInfo, nextAction);
  9716. }
  9717. });
  9718. };
  9719. return WorkerPool;
  9720. }());
  9721. BABYLON.WorkerPool = WorkerPool;
  9722. })(BABYLON || (BABYLON = {}));
  9723. //# sourceMappingURL=babylon.workerPool.js.map
  9724. var BABYLON;
  9725. (function (BABYLON) {
  9726. var _AlphaState = /** @class */ (function () {
  9727. /**
  9728. * Initializes the state.
  9729. */
  9730. function _AlphaState() {
  9731. this._isAlphaBlendDirty = false;
  9732. this._isBlendFunctionParametersDirty = false;
  9733. this._isBlendEquationParametersDirty = false;
  9734. this._isBlendConstantsDirty = false;
  9735. this._alphaBlend = false;
  9736. this._blendFunctionParameters = new Array(4);
  9737. this._blendEquationParameters = new Array(2);
  9738. this._blendConstants = new Array(4);
  9739. this.reset();
  9740. }
  9741. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  9742. get: function () {
  9743. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  9744. },
  9745. enumerable: true,
  9746. configurable: true
  9747. });
  9748. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  9749. get: function () {
  9750. return this._alphaBlend;
  9751. },
  9752. set: function (value) {
  9753. if (this._alphaBlend === value) {
  9754. return;
  9755. }
  9756. this._alphaBlend = value;
  9757. this._isAlphaBlendDirty = true;
  9758. },
  9759. enumerable: true,
  9760. configurable: true
  9761. });
  9762. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  9763. if (this._blendConstants[0] === r &&
  9764. this._blendConstants[1] === g &&
  9765. this._blendConstants[2] === b &&
  9766. this._blendConstants[3] === a) {
  9767. return;
  9768. }
  9769. this._blendConstants[0] = r;
  9770. this._blendConstants[1] = g;
  9771. this._blendConstants[2] = b;
  9772. this._blendConstants[3] = a;
  9773. this._isBlendConstantsDirty = true;
  9774. };
  9775. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  9776. if (this._blendFunctionParameters[0] === value0 &&
  9777. this._blendFunctionParameters[1] === value1 &&
  9778. this._blendFunctionParameters[2] === value2 &&
  9779. this._blendFunctionParameters[3] === value3) {
  9780. return;
  9781. }
  9782. this._blendFunctionParameters[0] = value0;
  9783. this._blendFunctionParameters[1] = value1;
  9784. this._blendFunctionParameters[2] = value2;
  9785. this._blendFunctionParameters[3] = value3;
  9786. this._isBlendFunctionParametersDirty = true;
  9787. };
  9788. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  9789. if (this._blendEquationParameters[0] === rgb &&
  9790. this._blendEquationParameters[1] === alpha) {
  9791. return;
  9792. }
  9793. this._blendEquationParameters[0] = rgb;
  9794. this._blendEquationParameters[1] = alpha;
  9795. this._isBlendEquationParametersDirty = true;
  9796. };
  9797. _AlphaState.prototype.reset = function () {
  9798. this._alphaBlend = false;
  9799. this._blendFunctionParameters[0] = null;
  9800. this._blendFunctionParameters[1] = null;
  9801. this._blendFunctionParameters[2] = null;
  9802. this._blendFunctionParameters[3] = null;
  9803. this._blendEquationParameters[0] = null;
  9804. this._blendEquationParameters[1] = null;
  9805. this._blendConstants[0] = null;
  9806. this._blendConstants[1] = null;
  9807. this._blendConstants[2] = null;
  9808. this._blendConstants[3] = null;
  9809. this._isAlphaBlendDirty = true;
  9810. this._isBlendFunctionParametersDirty = false;
  9811. this._isBlendEquationParametersDirty = false;
  9812. this._isBlendConstantsDirty = false;
  9813. };
  9814. _AlphaState.prototype.apply = function (gl) {
  9815. if (!this.isDirty) {
  9816. return;
  9817. }
  9818. // Alpha blend
  9819. if (this._isAlphaBlendDirty) {
  9820. if (this._alphaBlend) {
  9821. gl.enable(gl.BLEND);
  9822. }
  9823. else {
  9824. gl.disable(gl.BLEND);
  9825. }
  9826. this._isAlphaBlendDirty = false;
  9827. }
  9828. // Alpha function
  9829. if (this._isBlendFunctionParametersDirty) {
  9830. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  9831. this._isBlendFunctionParametersDirty = false;
  9832. }
  9833. // Alpha equation
  9834. if (this._isBlendEquationParametersDirty) {
  9835. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  9836. this._isBlendEquationParametersDirty = false;
  9837. }
  9838. // Constants
  9839. if (this._isBlendConstantsDirty) {
  9840. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  9841. this._isBlendConstantsDirty = false;
  9842. }
  9843. };
  9844. return _AlphaState;
  9845. }());
  9846. BABYLON._AlphaState = _AlphaState;
  9847. })(BABYLON || (BABYLON = {}));
  9848. //# sourceMappingURL=babylon.alphaCullingState.js.map
  9849. var BABYLON;
  9850. (function (BABYLON) {
  9851. var _DepthCullingState = /** @class */ (function () {
  9852. /**
  9853. * Initializes the state.
  9854. */
  9855. function _DepthCullingState() {
  9856. this._isDepthTestDirty = false;
  9857. this._isDepthMaskDirty = false;
  9858. this._isDepthFuncDirty = false;
  9859. this._isCullFaceDirty = false;
  9860. this._isCullDirty = false;
  9861. this._isZOffsetDirty = false;
  9862. this._isFrontFaceDirty = false;
  9863. this.reset();
  9864. }
  9865. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  9866. get: function () {
  9867. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  9868. },
  9869. enumerable: true,
  9870. configurable: true
  9871. });
  9872. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  9873. get: function () {
  9874. return this._zOffset;
  9875. },
  9876. set: function (value) {
  9877. if (this._zOffset === value) {
  9878. return;
  9879. }
  9880. this._zOffset = value;
  9881. this._isZOffsetDirty = true;
  9882. },
  9883. enumerable: true,
  9884. configurable: true
  9885. });
  9886. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  9887. get: function () {
  9888. return this._cullFace;
  9889. },
  9890. set: function (value) {
  9891. if (this._cullFace === value) {
  9892. return;
  9893. }
  9894. this._cullFace = value;
  9895. this._isCullFaceDirty = true;
  9896. },
  9897. enumerable: true,
  9898. configurable: true
  9899. });
  9900. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  9901. get: function () {
  9902. return this._cull;
  9903. },
  9904. set: function (value) {
  9905. if (this._cull === value) {
  9906. return;
  9907. }
  9908. this._cull = value;
  9909. this._isCullDirty = true;
  9910. },
  9911. enumerable: true,
  9912. configurable: true
  9913. });
  9914. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  9915. get: function () {
  9916. return this._depthFunc;
  9917. },
  9918. set: function (value) {
  9919. if (this._depthFunc === value) {
  9920. return;
  9921. }
  9922. this._depthFunc = value;
  9923. this._isDepthFuncDirty = true;
  9924. },
  9925. enumerable: true,
  9926. configurable: true
  9927. });
  9928. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  9929. get: function () {
  9930. return this._depthMask;
  9931. },
  9932. set: function (value) {
  9933. if (this._depthMask === value) {
  9934. return;
  9935. }
  9936. this._depthMask = value;
  9937. this._isDepthMaskDirty = true;
  9938. },
  9939. enumerable: true,
  9940. configurable: true
  9941. });
  9942. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  9943. get: function () {
  9944. return this._depthTest;
  9945. },
  9946. set: function (value) {
  9947. if (this._depthTest === value) {
  9948. return;
  9949. }
  9950. this._depthTest = value;
  9951. this._isDepthTestDirty = true;
  9952. },
  9953. enumerable: true,
  9954. configurable: true
  9955. });
  9956. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  9957. get: function () {
  9958. return this._frontFace;
  9959. },
  9960. set: function (value) {
  9961. if (this._frontFace === value) {
  9962. return;
  9963. }
  9964. this._frontFace = value;
  9965. this._isFrontFaceDirty = true;
  9966. },
  9967. enumerable: true,
  9968. configurable: true
  9969. });
  9970. _DepthCullingState.prototype.reset = function () {
  9971. this._depthMask = true;
  9972. this._depthTest = true;
  9973. this._depthFunc = null;
  9974. this._cullFace = null;
  9975. this._cull = null;
  9976. this._zOffset = 0;
  9977. this._frontFace = null;
  9978. this._isDepthTestDirty = true;
  9979. this._isDepthMaskDirty = true;
  9980. this._isDepthFuncDirty = false;
  9981. this._isCullFaceDirty = false;
  9982. this._isCullDirty = false;
  9983. this._isZOffsetDirty = false;
  9984. this._isFrontFaceDirty = false;
  9985. };
  9986. _DepthCullingState.prototype.apply = function (gl) {
  9987. if (!this.isDirty) {
  9988. return;
  9989. }
  9990. // Cull
  9991. if (this._isCullDirty) {
  9992. if (this.cull) {
  9993. gl.enable(gl.CULL_FACE);
  9994. }
  9995. else {
  9996. gl.disable(gl.CULL_FACE);
  9997. }
  9998. this._isCullDirty = false;
  9999. }
  10000. // Cull face
  10001. if (this._isCullFaceDirty) {
  10002. gl.cullFace(this.cullFace);
  10003. this._isCullFaceDirty = false;
  10004. }
  10005. // Depth mask
  10006. if (this._isDepthMaskDirty) {
  10007. gl.depthMask(this.depthMask);
  10008. this._isDepthMaskDirty = false;
  10009. }
  10010. // Depth test
  10011. if (this._isDepthTestDirty) {
  10012. if (this.depthTest) {
  10013. gl.enable(gl.DEPTH_TEST);
  10014. }
  10015. else {
  10016. gl.disable(gl.DEPTH_TEST);
  10017. }
  10018. this._isDepthTestDirty = false;
  10019. }
  10020. // Depth func
  10021. if (this._isDepthFuncDirty) {
  10022. gl.depthFunc(this.depthFunc);
  10023. this._isDepthFuncDirty = false;
  10024. }
  10025. // zOffset
  10026. if (this._isZOffsetDirty) {
  10027. if (this.zOffset) {
  10028. gl.enable(gl.POLYGON_OFFSET_FILL);
  10029. gl.polygonOffset(this.zOffset, 0);
  10030. }
  10031. else {
  10032. gl.disable(gl.POLYGON_OFFSET_FILL);
  10033. }
  10034. this._isZOffsetDirty = false;
  10035. }
  10036. // Front face
  10037. if (this._isFrontFaceDirty) {
  10038. gl.frontFace(this.frontFace);
  10039. this._isFrontFaceDirty = false;
  10040. }
  10041. };
  10042. return _DepthCullingState;
  10043. }());
  10044. BABYLON._DepthCullingState = _DepthCullingState;
  10045. })(BABYLON || (BABYLON = {}));
  10046. //# sourceMappingURL=babylon.depthCullingState.js.map
  10047. var BABYLON;
  10048. (function (BABYLON) {
  10049. var _StencilState = /** @class */ (function () {
  10050. function _StencilState() {
  10051. this._isStencilTestDirty = false;
  10052. this._isStencilMaskDirty = false;
  10053. this._isStencilFuncDirty = false;
  10054. this._isStencilOpDirty = false;
  10055. this.reset();
  10056. }
  10057. Object.defineProperty(_StencilState.prototype, "isDirty", {
  10058. get: function () {
  10059. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  10060. },
  10061. enumerable: true,
  10062. configurable: true
  10063. });
  10064. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  10065. get: function () {
  10066. return this._stencilFunc;
  10067. },
  10068. set: function (value) {
  10069. if (this._stencilFunc === value) {
  10070. return;
  10071. }
  10072. this._stencilFunc = value;
  10073. this._isStencilFuncDirty = true;
  10074. },
  10075. enumerable: true,
  10076. configurable: true
  10077. });
  10078. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  10079. get: function () {
  10080. return this._stencilFuncRef;
  10081. },
  10082. set: function (value) {
  10083. if (this._stencilFuncRef === value) {
  10084. return;
  10085. }
  10086. this._stencilFuncRef = value;
  10087. this._isStencilFuncDirty = true;
  10088. },
  10089. enumerable: true,
  10090. configurable: true
  10091. });
  10092. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  10093. get: function () {
  10094. return this._stencilFuncMask;
  10095. },
  10096. set: function (value) {
  10097. if (this._stencilFuncMask === value) {
  10098. return;
  10099. }
  10100. this._stencilFuncMask = value;
  10101. this._isStencilFuncDirty = true;
  10102. },
  10103. enumerable: true,
  10104. configurable: true
  10105. });
  10106. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  10107. get: function () {
  10108. return this._stencilOpStencilFail;
  10109. },
  10110. set: function (value) {
  10111. if (this._stencilOpStencilFail === value) {
  10112. return;
  10113. }
  10114. this._stencilOpStencilFail = value;
  10115. this._isStencilOpDirty = true;
  10116. },
  10117. enumerable: true,
  10118. configurable: true
  10119. });
  10120. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  10121. get: function () {
  10122. return this._stencilOpDepthFail;
  10123. },
  10124. set: function (value) {
  10125. if (this._stencilOpDepthFail === value) {
  10126. return;
  10127. }
  10128. this._stencilOpDepthFail = value;
  10129. this._isStencilOpDirty = true;
  10130. },
  10131. enumerable: true,
  10132. configurable: true
  10133. });
  10134. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  10135. get: function () {
  10136. return this._stencilOpStencilDepthPass;
  10137. },
  10138. set: function (value) {
  10139. if (this._stencilOpStencilDepthPass === value) {
  10140. return;
  10141. }
  10142. this._stencilOpStencilDepthPass = value;
  10143. this._isStencilOpDirty = true;
  10144. },
  10145. enumerable: true,
  10146. configurable: true
  10147. });
  10148. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  10149. get: function () {
  10150. return this._stencilMask;
  10151. },
  10152. set: function (value) {
  10153. if (this._stencilMask === value) {
  10154. return;
  10155. }
  10156. this._stencilMask = value;
  10157. this._isStencilMaskDirty = true;
  10158. },
  10159. enumerable: true,
  10160. configurable: true
  10161. });
  10162. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  10163. get: function () {
  10164. return this._stencilTest;
  10165. },
  10166. set: function (value) {
  10167. if (this._stencilTest === value) {
  10168. return;
  10169. }
  10170. this._stencilTest = value;
  10171. this._isStencilTestDirty = true;
  10172. },
  10173. enumerable: true,
  10174. configurable: true
  10175. });
  10176. _StencilState.prototype.reset = function () {
  10177. this._stencilTest = false;
  10178. this._stencilMask = 0xFF;
  10179. this._stencilFunc = BABYLON.Engine.ALWAYS;
  10180. this._stencilFuncRef = 1;
  10181. this._stencilFuncMask = 0xFF;
  10182. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  10183. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  10184. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  10185. this._isStencilTestDirty = true;
  10186. this._isStencilMaskDirty = true;
  10187. this._isStencilFuncDirty = true;
  10188. this._isStencilOpDirty = true;
  10189. };
  10190. _StencilState.prototype.apply = function (gl) {
  10191. if (!this.isDirty) {
  10192. return;
  10193. }
  10194. // Stencil test
  10195. if (this._isStencilTestDirty) {
  10196. if (this.stencilTest) {
  10197. gl.enable(gl.STENCIL_TEST);
  10198. }
  10199. else {
  10200. gl.disable(gl.STENCIL_TEST);
  10201. }
  10202. this._isStencilTestDirty = false;
  10203. }
  10204. // Stencil mask
  10205. if (this._isStencilMaskDirty) {
  10206. gl.stencilMask(this.stencilMask);
  10207. this._isStencilMaskDirty = false;
  10208. }
  10209. // Stencil func
  10210. if (this._isStencilFuncDirty) {
  10211. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  10212. this._isStencilFuncDirty = false;
  10213. }
  10214. // Stencil op
  10215. if (this._isStencilOpDirty) {
  10216. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  10217. this._isStencilOpDirty = false;
  10218. }
  10219. };
  10220. return _StencilState;
  10221. }());
  10222. BABYLON._StencilState = _StencilState;
  10223. })(BABYLON || (BABYLON = {}));
  10224. //# sourceMappingURL=babylon.stencilState.js.map
  10225. var __assign = (this && this.__assign) || Object.assign || function(t) {
  10226. for (var s, i = 1, n = arguments.length; i < n; i++) {
  10227. s = arguments[i];
  10228. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  10229. t[p] = s[p];
  10230. }
  10231. return t;
  10232. };
  10233. var BABYLON;
  10234. (function (BABYLON) {
  10235. var compileShader = function (gl, source, type, defines, shaderVersion) {
  10236. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  10237. };
  10238. var compileRawShader = function (gl, source, type) {
  10239. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  10240. gl.shaderSource(shader, source);
  10241. gl.compileShader(shader);
  10242. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  10243. var log = gl.getShaderInfoLog(shader);
  10244. if (log) {
  10245. throw new Error(log);
  10246. }
  10247. }
  10248. if (!shader) {
  10249. throw new Error("Something went wrong while compile the shader.");
  10250. }
  10251. return shader;
  10252. };
  10253. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  10254. var magFilter = gl.NEAREST;
  10255. var minFilter = gl.NEAREST;
  10256. switch (samplingMode) {
  10257. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  10258. magFilter = gl.LINEAR;
  10259. if (generateMipMaps) {
  10260. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  10261. }
  10262. else {
  10263. minFilter = gl.LINEAR;
  10264. }
  10265. break;
  10266. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  10267. magFilter = gl.LINEAR;
  10268. if (generateMipMaps) {
  10269. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  10270. }
  10271. else {
  10272. minFilter = gl.LINEAR;
  10273. }
  10274. break;
  10275. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  10276. magFilter = gl.NEAREST;
  10277. if (generateMipMaps) {
  10278. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  10279. }
  10280. else {
  10281. minFilter = gl.NEAREST;
  10282. }
  10283. break;
  10284. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  10285. magFilter = gl.NEAREST;
  10286. if (generateMipMaps) {
  10287. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  10288. }
  10289. else {
  10290. minFilter = gl.NEAREST;
  10291. }
  10292. break;
  10293. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  10294. magFilter = gl.NEAREST;
  10295. if (generateMipMaps) {
  10296. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  10297. }
  10298. else {
  10299. minFilter = gl.LINEAR;
  10300. }
  10301. break;
  10302. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  10303. magFilter = gl.NEAREST;
  10304. if (generateMipMaps) {
  10305. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  10306. }
  10307. else {
  10308. minFilter = gl.LINEAR;
  10309. }
  10310. break;
  10311. case BABYLON.Texture.NEAREST_LINEAR:
  10312. magFilter = gl.NEAREST;
  10313. minFilter = gl.LINEAR;
  10314. break;
  10315. case BABYLON.Texture.NEAREST_NEAREST:
  10316. magFilter = gl.NEAREST;
  10317. minFilter = gl.NEAREST;
  10318. break;
  10319. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  10320. magFilter = gl.LINEAR;
  10321. if (generateMipMaps) {
  10322. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  10323. }
  10324. else {
  10325. minFilter = gl.NEAREST;
  10326. }
  10327. break;
  10328. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  10329. magFilter = gl.LINEAR;
  10330. if (generateMipMaps) {
  10331. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  10332. }
  10333. else {
  10334. minFilter = gl.NEAREST;
  10335. }
  10336. break;
  10337. case BABYLON.Texture.LINEAR_LINEAR:
  10338. magFilter = gl.LINEAR;
  10339. minFilter = gl.LINEAR;
  10340. break;
  10341. case BABYLON.Texture.LINEAR_NEAREST:
  10342. magFilter = gl.LINEAR;
  10343. minFilter = gl.NEAREST;
  10344. break;
  10345. }
  10346. return {
  10347. min: minFilter,
  10348. mag: magFilter
  10349. };
  10350. };
  10351. var partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  10352. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  10353. var img;
  10354. var onload = function () {
  10355. loadedImages[index] = img;
  10356. loadedImages._internalCount++;
  10357. if (scene) {
  10358. scene._removePendingData(img);
  10359. }
  10360. if (loadedImages._internalCount === 6) {
  10361. onfinish(loadedImages);
  10362. }
  10363. };
  10364. var onerror = function (message, exception) {
  10365. if (scene) {
  10366. scene._removePendingData(img);
  10367. }
  10368. if (onErrorCallBack) {
  10369. onErrorCallBack(message, exception);
  10370. }
  10371. };
  10372. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  10373. if (scene) {
  10374. scene._addPendingData(img);
  10375. }
  10376. };
  10377. var cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  10378. if (onError === void 0) { onError = null; }
  10379. var loadedImages = [];
  10380. loadedImages._internalCount = 0;
  10381. for (var index = 0; index < 6; index++) {
  10382. partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  10383. }
  10384. };
  10385. var BufferPointer = /** @class */ (function () {
  10386. function BufferPointer() {
  10387. }
  10388. return BufferPointer;
  10389. }());
  10390. var InstancingAttributeInfo = /** @class */ (function () {
  10391. function InstancingAttributeInfo() {
  10392. }
  10393. return InstancingAttributeInfo;
  10394. }());
  10395. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  10396. /**
  10397. * Define options used to create a render target texture
  10398. */
  10399. var RenderTargetCreationOptions = /** @class */ (function () {
  10400. function RenderTargetCreationOptions() {
  10401. }
  10402. return RenderTargetCreationOptions;
  10403. }());
  10404. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  10405. /**
  10406. * Define options used to create a depth texture
  10407. */
  10408. var DepthTextureCreationOptions = /** @class */ (function () {
  10409. function DepthTextureCreationOptions() {
  10410. }
  10411. return DepthTextureCreationOptions;
  10412. }());
  10413. BABYLON.DepthTextureCreationOptions = DepthTextureCreationOptions;
  10414. /**
  10415. * Regroup several parameters relative to the browser in use
  10416. */
  10417. var EngineCapabilities = /** @class */ (function () {
  10418. function EngineCapabilities() {
  10419. }
  10420. return EngineCapabilities;
  10421. }());
  10422. BABYLON.EngineCapabilities = EngineCapabilities;
  10423. /**
  10424. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  10425. */
  10426. var Engine = /** @class */ (function () {
  10427. /**
  10428. * @constructor
  10429. * @param canvasOrContext defines the canvas or WebGL context to use for rendering
  10430. * @param antialias defines enable antialiasing (default: false)
  10431. * @param options defines further options to be sent to the getContext() function
  10432. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  10433. */
  10434. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  10435. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  10436. var _this = this;
  10437. // Public members
  10438. this.forcePOTTextures = false;
  10439. this.isFullscreen = false;
  10440. this.isPointerLock = false;
  10441. this.cullBackFaces = true;
  10442. this.renderEvenInBackground = true;
  10443. this.preventCacheWipeBetweenFrames = false;
  10444. // To enable/disable IDB support and avoid XHR on .manifest
  10445. this.enableOfflineSupport = false;
  10446. this.scenes = new Array();
  10447. this.postProcesses = new Array();
  10448. // Observables
  10449. /**
  10450. * Observable event triggered each time the rendering canvas is resized
  10451. */
  10452. this.onResizeObservable = new BABYLON.Observable();
  10453. /**
  10454. * Observable event triggered each time the canvas loses focus
  10455. */
  10456. this.onCanvasBlurObservable = new BABYLON.Observable();
  10457. /**
  10458. * Observable event triggered each time the canvas gains focus
  10459. */
  10460. this.onCanvasFocusObservable = new BABYLON.Observable();
  10461. /**
  10462. * Observable event triggered each time the canvas receives pointerout event
  10463. */
  10464. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  10465. /**
  10466. * Observable event triggered before each texture is initialized
  10467. */
  10468. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  10469. //WebVR
  10470. this._vrDisplay = undefined;
  10471. this._vrSupported = false;
  10472. this._vrExclusivePointerMode = false;
  10473. // Uniform buffers list
  10474. this.disableUniformBuffers = false;
  10475. this._uniformBuffers = new Array();
  10476. // Observables
  10477. /**
  10478. * Observable raised when the engine begins a new frame
  10479. */
  10480. this.onBeginFrameObservable = new BABYLON.Observable();
  10481. /**
  10482. * Observable raised when the engine ends the current frame
  10483. */
  10484. this.onEndFrameObservable = new BABYLON.Observable();
  10485. /**
  10486. * Observable raised when the engine is about to compile a shader
  10487. */
  10488. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  10489. /**
  10490. * Observable raised when the engine has jsut compiled a shader
  10491. */
  10492. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  10493. this._windowIsBackground = false;
  10494. this._webGLVersion = 1.0;
  10495. this._badOS = false;
  10496. this._badDesktopOS = false;
  10497. /**
  10498. * Gets or sets a value indicating if we want to disable texture binding optmization.
  10499. * This could be required on some buggy drivers which wants to have textures bound in a progressive order
  10500. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is.
  10501. */
  10502. this.disableTextureBindingOptimization = false;
  10503. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  10504. this.onVRRequestPresentComplete = new BABYLON.Observable();
  10505. this.onVRRequestPresentStart = new BABYLON.Observable();
  10506. this._colorWrite = true;
  10507. this._drawCalls = new BABYLON.PerfCounter();
  10508. this._textureCollisions = new BABYLON.PerfCounter();
  10509. this._renderingQueueLaunched = false;
  10510. this._activeRenderLoops = new Array();
  10511. // Deterministic lockstepMaxSteps
  10512. this._deterministicLockstep = false;
  10513. this._lockstepMaxSteps = 4;
  10514. // Lost context
  10515. this.onContextLostObservable = new BABYLON.Observable();
  10516. this.onContextRestoredObservable = new BABYLON.Observable();
  10517. this._contextWasLost = false;
  10518. this._doNotHandleContextLost = false;
  10519. // FPS
  10520. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  10521. this._fps = 60;
  10522. this._deltaTime = 0;
  10523. /**
  10524. * Turn this value on if you want to pause FPS computation when in background
  10525. */
  10526. this.disablePerformanceMonitorInBackground = false;
  10527. // States
  10528. this._depthCullingState = new BABYLON._DepthCullingState();
  10529. this._stencilState = new BABYLON._StencilState();
  10530. this._alphaState = new BABYLON._AlphaState();
  10531. this._alphaMode = Engine.ALPHA_DISABLE;
  10532. // Cache
  10533. this._internalTexturesCache = new Array();
  10534. this._activeChannel = 0;
  10535. this._currentTextureChannel = -1;
  10536. this._boundTexturesCache = {};
  10537. this._compiledEffects = {};
  10538. this._vertexAttribArraysEnabled = [];
  10539. this._uintIndicesCurrentlySet = false;
  10540. this._currentBoundBuffer = new Array();
  10541. this._currentBufferPointers = new Array();
  10542. this._currentInstanceLocations = new Array();
  10543. this._currentInstanceBuffers = new Array();
  10544. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  10545. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  10546. this._vaoRecordInProgress = false;
  10547. this._mustWipeVertexAttributes = false;
  10548. this._nextFreeTextureSlots = new Array();
  10549. this._maxSimultaneousTextures = 0;
  10550. this._activeRequests = new Array();
  10551. // Hardware supported Compressed Textures
  10552. this._texturesSupported = new Array();
  10553. this._onVRFullScreenTriggered = function () {
  10554. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  10555. //get the old size before we change
  10556. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  10557. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  10558. //get the width and height, change the render size
  10559. var leftEye = _this._vrDisplay.getEyeParameters('left');
  10560. _this.setHardwareScalingLevel(1);
  10561. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  10562. }
  10563. else {
  10564. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  10565. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  10566. }
  10567. };
  10568. this._boundUniforms = {};
  10569. // Register promises
  10570. BABYLON.PromisePolyfill.Apply();
  10571. var canvas = null;
  10572. Engine.Instances.push(this);
  10573. if (!canvasOrContext) {
  10574. return;
  10575. }
  10576. options = options || {};
  10577. if (canvasOrContext.getContext) {
  10578. canvas = canvasOrContext;
  10579. this._renderingCanvas = canvas;
  10580. if (antialias != null) {
  10581. options.antialias = antialias;
  10582. }
  10583. if (options.deterministicLockstep === undefined) {
  10584. options.deterministicLockstep = false;
  10585. }
  10586. if (options.lockstepMaxSteps === undefined) {
  10587. options.lockstepMaxSteps = 4;
  10588. }
  10589. if (options.preserveDrawingBuffer === undefined) {
  10590. options.preserveDrawingBuffer = false;
  10591. }
  10592. if (options.audioEngine === undefined) {
  10593. options.audioEngine = true;
  10594. }
  10595. if (options.stencil === undefined) {
  10596. options.stencil = true;
  10597. }
  10598. this._deterministicLockstep = options.deterministicLockstep;
  10599. this._lockstepMaxSteps = options.lockstepMaxSteps;
  10600. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  10601. // Exceptions
  10602. if (navigator && navigator.userAgent) {
  10603. var ua = navigator.userAgent;
  10604. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  10605. var exception = _a[_i];
  10606. var key = exception.key;
  10607. var targets = exception.targets;
  10608. if (ua.indexOf(key) > -1) {
  10609. if (exception.capture && exception.captureConstraint) {
  10610. var capture = exception.capture;
  10611. var constraint = exception.captureConstraint;
  10612. var regex = new RegExp(capture);
  10613. var matches = regex.exec(ua);
  10614. if (matches && matches.length > 0) {
  10615. var capturedValue = parseInt(matches[matches.length - 1]);
  10616. if (capturedValue >= constraint) {
  10617. continue;
  10618. }
  10619. }
  10620. }
  10621. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  10622. var target = targets_1[_b];
  10623. switch (target) {
  10624. case "uniformBuffer":
  10625. this.disableUniformBuffers = true;
  10626. break;
  10627. case "textureBindingOptimization":
  10628. this.disableTextureBindingOptimization = true;
  10629. break;
  10630. }
  10631. }
  10632. }
  10633. }
  10634. }
  10635. // GL
  10636. if (!options.disableWebGL2Support) {
  10637. try {
  10638. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  10639. if (this._gl) {
  10640. this._webGLVersion = 2.0;
  10641. }
  10642. }
  10643. catch (e) {
  10644. // Do nothing
  10645. }
  10646. }
  10647. if (!this._gl) {
  10648. if (!canvas) {
  10649. throw new Error("The provided canvas is null or undefined.");
  10650. }
  10651. try {
  10652. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  10653. }
  10654. catch (e) {
  10655. throw new Error("WebGL not supported");
  10656. }
  10657. }
  10658. if (!this._gl) {
  10659. throw new Error("WebGL not supported");
  10660. }
  10661. this._onCanvasFocus = function () {
  10662. _this.onCanvasFocusObservable.notifyObservers(_this);
  10663. };
  10664. this._onCanvasBlur = function () {
  10665. _this.onCanvasBlurObservable.notifyObservers(_this);
  10666. };
  10667. canvas.addEventListener("focus", this._onCanvasFocus);
  10668. canvas.addEventListener("blur", this._onCanvasBlur);
  10669. this._onBlur = function () {
  10670. if (_this.disablePerformanceMonitorInBackground) {
  10671. _this._performanceMonitor.disable();
  10672. }
  10673. _this._windowIsBackground = true;
  10674. };
  10675. this._onFocus = function () {
  10676. if (_this.disablePerformanceMonitorInBackground) {
  10677. _this._performanceMonitor.enable();
  10678. }
  10679. _this._windowIsBackground = false;
  10680. };
  10681. this._onCanvasPointerOut = function (ev) {
  10682. _this.onCanvasPointerOutObservable.notifyObservers(ev);
  10683. };
  10684. window.addEventListener("blur", this._onBlur);
  10685. window.addEventListener("focus", this._onFocus);
  10686. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  10687. // Context lost
  10688. if (!this._doNotHandleContextLost) {
  10689. this._onContextLost = function (evt) {
  10690. evt.preventDefault();
  10691. _this._contextWasLost = true;
  10692. BABYLON.Tools.Warn("WebGL context lost.");
  10693. _this.onContextLostObservable.notifyObservers(_this);
  10694. };
  10695. this._onContextRestored = function (evt) {
  10696. // Adding a timeout to avoid race condition at browser level
  10697. setTimeout(function () {
  10698. // Rebuild gl context
  10699. _this._initGLContext();
  10700. // Rebuild effects
  10701. _this._rebuildEffects();
  10702. // Rebuild textures
  10703. _this._rebuildInternalTextures();
  10704. // Rebuild buffers
  10705. _this._rebuildBuffers();
  10706. // Cache
  10707. _this.wipeCaches(true);
  10708. BABYLON.Tools.Warn("WebGL context successfully restored.");
  10709. _this.onContextRestoredObservable.notifyObservers(_this);
  10710. _this._contextWasLost = false;
  10711. }, 0);
  10712. };
  10713. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  10714. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  10715. }
  10716. }
  10717. else {
  10718. this._gl = canvasOrContext;
  10719. this._renderingCanvas = this._gl.canvas;
  10720. if (this._gl.renderbufferStorageMultisample) {
  10721. this._webGLVersion = 2.0;
  10722. }
  10723. options.stencil = this._gl.getContextAttributes().stencil;
  10724. }
  10725. // Viewport
  10726. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  10727. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  10728. this.resize();
  10729. this._isStencilEnable = options.stencil ? true : false;
  10730. this._initGLContext();
  10731. if (canvas) {
  10732. // Fullscreen
  10733. this._onFullscreenChange = function () {
  10734. if (document.fullscreen !== undefined) {
  10735. _this.isFullscreen = document.fullscreen;
  10736. }
  10737. else if (document.mozFullScreen !== undefined) {
  10738. _this.isFullscreen = document.mozFullScreen;
  10739. }
  10740. else if (document.webkitIsFullScreen !== undefined) {
  10741. _this.isFullscreen = document.webkitIsFullScreen;
  10742. }
  10743. else if (document.msIsFullScreen !== undefined) {
  10744. _this.isFullscreen = document.msIsFullScreen;
  10745. }
  10746. // Pointer lock
  10747. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  10748. canvas.requestPointerLock = canvas.requestPointerLock ||
  10749. canvas.msRequestPointerLock ||
  10750. canvas.mozRequestPointerLock ||
  10751. canvas.webkitRequestPointerLock;
  10752. if (canvas.requestPointerLock) {
  10753. canvas.requestPointerLock();
  10754. }
  10755. }
  10756. };
  10757. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  10758. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  10759. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  10760. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  10761. // Pointer lock
  10762. this._onPointerLockChange = function () {
  10763. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  10764. document.webkitPointerLockElement === canvas ||
  10765. document.msPointerLockElement === canvas ||
  10766. document.pointerLockElement === canvas);
  10767. };
  10768. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  10769. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  10770. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  10771. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  10772. this._onVRDisplayPointerRestricted = function () {
  10773. if (canvas) {
  10774. canvas.requestPointerLock();
  10775. }
  10776. };
  10777. this._onVRDisplayPointerUnrestricted = function () {
  10778. document.exitPointerLock();
  10779. };
  10780. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  10781. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  10782. }
  10783. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  10784. Engine.audioEngine = new BABYLON.AudioEngine();
  10785. }
  10786. // Prepare buffer pointers
  10787. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  10788. this._currentBufferPointers[i] = new BufferPointer();
  10789. }
  10790. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  10791. // Load WebVR Devices
  10792. if (options.autoEnableWebVR) {
  10793. this.initWebVR();
  10794. }
  10795. // Detect if we are running on a faulty buggy OS.
  10796. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  10797. // Detect if we are running on a faulty buggy desktop OS.
  10798. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  10799. console.log("Babylon.js engine (v" + Engine.Version + ") launched");
  10800. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  10801. }
  10802. Object.defineProperty(Engine, "LastCreatedEngine", {
  10803. get: function () {
  10804. if (Engine.Instances.length === 0) {
  10805. return null;
  10806. }
  10807. return Engine.Instances[Engine.Instances.length - 1];
  10808. },
  10809. enumerable: true,
  10810. configurable: true
  10811. });
  10812. Object.defineProperty(Engine, "LastCreatedScene", {
  10813. get: function () {
  10814. var lastCreatedEngine = Engine.LastCreatedEngine;
  10815. if (!lastCreatedEngine) {
  10816. return null;
  10817. }
  10818. if (lastCreatedEngine.scenes.length === 0) {
  10819. return null;
  10820. }
  10821. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  10822. },
  10823. enumerable: true,
  10824. configurable: true
  10825. });
  10826. /**
  10827. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  10828. */
  10829. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  10830. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  10831. var engine = Engine.Instances[engineIndex];
  10832. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  10833. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  10834. }
  10835. }
  10836. };
  10837. Object.defineProperty(Engine, "NEVER", {
  10838. get: function () {
  10839. return Engine._NEVER;
  10840. },
  10841. enumerable: true,
  10842. configurable: true
  10843. });
  10844. Object.defineProperty(Engine, "ALWAYS", {
  10845. get: function () {
  10846. return Engine._ALWAYS;
  10847. },
  10848. enumerable: true,
  10849. configurable: true
  10850. });
  10851. Object.defineProperty(Engine, "LESS", {
  10852. get: function () {
  10853. return Engine._LESS;
  10854. },
  10855. enumerable: true,
  10856. configurable: true
  10857. });
  10858. Object.defineProperty(Engine, "EQUAL", {
  10859. get: function () {
  10860. return Engine._EQUAL;
  10861. },
  10862. enumerable: true,
  10863. configurable: true
  10864. });
  10865. Object.defineProperty(Engine, "LEQUAL", {
  10866. get: function () {
  10867. return Engine._LEQUAL;
  10868. },
  10869. enumerable: true,
  10870. configurable: true
  10871. });
  10872. Object.defineProperty(Engine, "GREATER", {
  10873. get: function () {
  10874. return Engine._GREATER;
  10875. },
  10876. enumerable: true,
  10877. configurable: true
  10878. });
  10879. Object.defineProperty(Engine, "GEQUAL", {
  10880. get: function () {
  10881. return Engine._GEQUAL;
  10882. },
  10883. enumerable: true,
  10884. configurable: true
  10885. });
  10886. Object.defineProperty(Engine, "NOTEQUAL", {
  10887. get: function () {
  10888. return Engine._NOTEQUAL;
  10889. },
  10890. enumerable: true,
  10891. configurable: true
  10892. });
  10893. Object.defineProperty(Engine, "KEEP", {
  10894. get: function () {
  10895. return Engine._KEEP;
  10896. },
  10897. enumerable: true,
  10898. configurable: true
  10899. });
  10900. Object.defineProperty(Engine, "REPLACE", {
  10901. get: function () {
  10902. return Engine._REPLACE;
  10903. },
  10904. enumerable: true,
  10905. configurable: true
  10906. });
  10907. Object.defineProperty(Engine, "INCR", {
  10908. get: function () {
  10909. return Engine._INCR;
  10910. },
  10911. enumerable: true,
  10912. configurable: true
  10913. });
  10914. Object.defineProperty(Engine, "DECR", {
  10915. get: function () {
  10916. return Engine._DECR;
  10917. },
  10918. enumerable: true,
  10919. configurable: true
  10920. });
  10921. Object.defineProperty(Engine, "INVERT", {
  10922. get: function () {
  10923. return Engine._INVERT;
  10924. },
  10925. enumerable: true,
  10926. configurable: true
  10927. });
  10928. Object.defineProperty(Engine, "INCR_WRAP", {
  10929. get: function () {
  10930. return Engine._INCR_WRAP;
  10931. },
  10932. enumerable: true,
  10933. configurable: true
  10934. });
  10935. Object.defineProperty(Engine, "DECR_WRAP", {
  10936. get: function () {
  10937. return Engine._DECR_WRAP;
  10938. },
  10939. enumerable: true,
  10940. configurable: true
  10941. });
  10942. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  10943. get: function () {
  10944. return Engine._ALPHA_DISABLE;
  10945. },
  10946. enumerable: true,
  10947. configurable: true
  10948. });
  10949. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  10950. get: function () {
  10951. return Engine._ALPHA_ONEONE;
  10952. },
  10953. enumerable: true,
  10954. configurable: true
  10955. });
  10956. Object.defineProperty(Engine, "ALPHA_ADD", {
  10957. get: function () {
  10958. return Engine._ALPHA_ADD;
  10959. },
  10960. enumerable: true,
  10961. configurable: true
  10962. });
  10963. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  10964. get: function () {
  10965. return Engine._ALPHA_COMBINE;
  10966. },
  10967. enumerable: true,
  10968. configurable: true
  10969. });
  10970. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  10971. get: function () {
  10972. return Engine._ALPHA_SUBTRACT;
  10973. },
  10974. enumerable: true,
  10975. configurable: true
  10976. });
  10977. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  10978. get: function () {
  10979. return Engine._ALPHA_MULTIPLY;
  10980. },
  10981. enumerable: true,
  10982. configurable: true
  10983. });
  10984. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  10985. get: function () {
  10986. return Engine._ALPHA_MAXIMIZED;
  10987. },
  10988. enumerable: true,
  10989. configurable: true
  10990. });
  10991. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  10992. get: function () {
  10993. return Engine._ALPHA_PREMULTIPLIED;
  10994. },
  10995. enumerable: true,
  10996. configurable: true
  10997. });
  10998. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  10999. get: function () {
  11000. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  11001. },
  11002. enumerable: true,
  11003. configurable: true
  11004. });
  11005. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  11006. get: function () {
  11007. return Engine._ALPHA_INTERPOLATE;
  11008. },
  11009. enumerable: true,
  11010. configurable: true
  11011. });
  11012. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  11013. get: function () {
  11014. return Engine._ALPHA_SCREENMODE;
  11015. },
  11016. enumerable: true,
  11017. configurable: true
  11018. });
  11019. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  11020. get: function () {
  11021. return Engine._DELAYLOADSTATE_NONE;
  11022. },
  11023. enumerable: true,
  11024. configurable: true
  11025. });
  11026. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  11027. get: function () {
  11028. return Engine._DELAYLOADSTATE_LOADED;
  11029. },
  11030. enumerable: true,
  11031. configurable: true
  11032. });
  11033. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  11034. get: function () {
  11035. return Engine._DELAYLOADSTATE_LOADING;
  11036. },
  11037. enumerable: true,
  11038. configurable: true
  11039. });
  11040. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  11041. get: function () {
  11042. return Engine._DELAYLOADSTATE_NOTLOADED;
  11043. },
  11044. enumerable: true,
  11045. configurable: true
  11046. });
  11047. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  11048. get: function () {
  11049. return Engine._TEXTUREFORMAT_ALPHA;
  11050. },
  11051. enumerable: true,
  11052. configurable: true
  11053. });
  11054. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  11055. get: function () {
  11056. return Engine._TEXTUREFORMAT_LUMINANCE;
  11057. },
  11058. enumerable: true,
  11059. configurable: true
  11060. });
  11061. Object.defineProperty(Engine, "TEXTUREFORMAT_R32F", {
  11062. /**
  11063. * R32F
  11064. */
  11065. get: function () {
  11066. return Engine._TEXTUREFORMAT_R32F;
  11067. },
  11068. enumerable: true,
  11069. configurable: true
  11070. });
  11071. Object.defineProperty(Engine, "TEXTUREFORMAT_RG32F", {
  11072. /**
  11073. * RG32F
  11074. */
  11075. get: function () {
  11076. return Engine._TEXTUREFORMAT_RG32F;
  11077. },
  11078. enumerable: true,
  11079. configurable: true
  11080. });
  11081. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB32F", {
  11082. /**
  11083. * RGB32F
  11084. */
  11085. get: function () {
  11086. return Engine._TEXTUREFORMAT_RGB32F;
  11087. },
  11088. enumerable: true,
  11089. configurable: true
  11090. });
  11091. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA32F", {
  11092. /**
  11093. * RGBA32F
  11094. */
  11095. get: function () {
  11096. return Engine._TEXTUREFORMAT_RGBA32F;
  11097. },
  11098. enumerable: true,
  11099. configurable: true
  11100. });
  11101. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  11102. get: function () {
  11103. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  11104. },
  11105. enumerable: true,
  11106. configurable: true
  11107. });
  11108. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  11109. get: function () {
  11110. return Engine._TEXTUREFORMAT_RGB;
  11111. },
  11112. enumerable: true,
  11113. configurable: true
  11114. });
  11115. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  11116. get: function () {
  11117. return Engine._TEXTUREFORMAT_RGBA;
  11118. },
  11119. enumerable: true,
  11120. configurable: true
  11121. });
  11122. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  11123. get: function () {
  11124. return Engine._TEXTURETYPE_UNSIGNED_INT;
  11125. },
  11126. enumerable: true,
  11127. configurable: true
  11128. });
  11129. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  11130. get: function () {
  11131. return Engine._TEXTURETYPE_FLOAT;
  11132. },
  11133. enumerable: true,
  11134. configurable: true
  11135. });
  11136. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  11137. get: function () {
  11138. return Engine._TEXTURETYPE_HALF_FLOAT;
  11139. },
  11140. enumerable: true,
  11141. configurable: true
  11142. });
  11143. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  11144. get: function () {
  11145. return Engine._SCALEMODE_FLOOR;
  11146. },
  11147. enumerable: true,
  11148. configurable: true
  11149. });
  11150. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  11151. get: function () {
  11152. return Engine._SCALEMODE_NEAREST;
  11153. },
  11154. enumerable: true,
  11155. configurable: true
  11156. });
  11157. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  11158. get: function () {
  11159. return Engine._SCALEMODE_CEILING;
  11160. },
  11161. enumerable: true,
  11162. configurable: true
  11163. });
  11164. Object.defineProperty(Engine, "Version", {
  11165. get: function () {
  11166. return "3.2.0-alphaB";
  11167. },
  11168. enumerable: true,
  11169. configurable: true
  11170. });
  11171. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  11172. get: function () {
  11173. return this._vrExclusivePointerMode;
  11174. },
  11175. enumerable: true,
  11176. configurable: true
  11177. });
  11178. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  11179. get: function () {
  11180. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  11181. },
  11182. enumerable: true,
  11183. configurable: true
  11184. });
  11185. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  11186. get: function () {
  11187. return this._webGLVersion < 2 || this.forcePOTTextures;
  11188. },
  11189. enumerable: true,
  11190. configurable: true
  11191. });
  11192. Object.defineProperty(Engine.prototype, "badOS", {
  11193. get: function () {
  11194. return this._badOS;
  11195. },
  11196. enumerable: true,
  11197. configurable: true
  11198. });
  11199. Object.defineProperty(Engine.prototype, "badDesktopOS", {
  11200. get: function () {
  11201. return this._badDesktopOS;
  11202. },
  11203. enumerable: true,
  11204. configurable: true
  11205. });
  11206. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  11207. get: function () {
  11208. return this._performanceMonitor;
  11209. },
  11210. enumerable: true,
  11211. configurable: true
  11212. });
  11213. Object.defineProperty(Engine.prototype, "texturesSupported", {
  11214. get: function () {
  11215. return this._texturesSupported;
  11216. },
  11217. enumerable: true,
  11218. configurable: true
  11219. });
  11220. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  11221. get: function () {
  11222. return this._textureFormatInUse;
  11223. },
  11224. enumerable: true,
  11225. configurable: true
  11226. });
  11227. Object.defineProperty(Engine.prototype, "currentViewport", {
  11228. get: function () {
  11229. return this._cachedViewport;
  11230. },
  11231. enumerable: true,
  11232. configurable: true
  11233. });
  11234. Object.defineProperty(Engine.prototype, "emptyTexture", {
  11235. // Empty texture
  11236. get: function () {
  11237. if (!this._emptyTexture) {
  11238. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11239. }
  11240. return this._emptyTexture;
  11241. },
  11242. enumerable: true,
  11243. configurable: true
  11244. });
  11245. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  11246. get: function () {
  11247. if (!this._emptyTexture3D) {
  11248. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11249. }
  11250. return this._emptyTexture3D;
  11251. },
  11252. enumerable: true,
  11253. configurable: true
  11254. });
  11255. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  11256. get: function () {
  11257. if (!this._emptyCubeTexture) {
  11258. var faceData = new Uint8Array(4);
  11259. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  11260. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11261. }
  11262. return this._emptyCubeTexture;
  11263. },
  11264. enumerable: true,
  11265. configurable: true
  11266. });
  11267. Engine.prototype._rebuildInternalTextures = function () {
  11268. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  11269. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  11270. var internalTexture = currentState_1[_i];
  11271. internalTexture._rebuild();
  11272. }
  11273. };
  11274. Engine.prototype._rebuildEffects = function () {
  11275. for (var key in this._compiledEffects) {
  11276. var effect = this._compiledEffects[key];
  11277. effect._prepareEffect();
  11278. }
  11279. BABYLON.Effect.ResetCache();
  11280. };
  11281. Engine.prototype._rebuildBuffers = function () {
  11282. // Index / Vertex
  11283. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  11284. var scene = _a[_i];
  11285. scene.resetCachedMaterial();
  11286. scene._rebuildGeometries();
  11287. scene._rebuildTextures();
  11288. }
  11289. // Uniforms
  11290. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  11291. var uniformBuffer = _c[_b];
  11292. uniformBuffer._rebuild();
  11293. }
  11294. };
  11295. Engine.prototype._initGLContext = function () {
  11296. // Caps
  11297. this._caps = new EngineCapabilities();
  11298. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  11299. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  11300. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  11301. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  11302. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  11303. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  11304. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  11305. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  11306. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  11307. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  11308. // Infos
  11309. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  11310. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  11311. if (rendererInfo != null) {
  11312. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  11313. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  11314. }
  11315. if (!this._glVendor) {
  11316. this._glVendor = "Unknown vendor";
  11317. }
  11318. if (!this._glRenderer) {
  11319. this._glRenderer = "Unknown renderer";
  11320. }
  11321. // Constants
  11322. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  11323. if (this._gl.RGBA16F !== 0x881A) {
  11324. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  11325. }
  11326. if (this._gl.RGBA32F !== 0x8814) {
  11327. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  11328. }
  11329. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  11330. this._gl.DEPTH24_STENCIL8 = 35056;
  11331. }
  11332. // Extensions
  11333. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  11334. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  11335. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  11336. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  11337. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  11338. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  11339. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  11340. this._caps.textureAnisotropicFilterExtension = this._gl.getExtension('EXT_texture_filter_anisotropic') || this._gl.getExtension('WEBKIT_EXT_texture_filter_anisotropic') || this._gl.getExtension('MOZ_EXT_texture_filter_anisotropic');
  11341. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  11342. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  11343. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  11344. this._caps.highPrecisionShaderSupported = true;
  11345. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  11346. if (this._caps.timerQuery) {
  11347. if (this._webGLVersion === 1) {
  11348. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  11349. }
  11350. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  11351. }
  11352. // Checks if some of the format renders first to allow the use of webgl inspector.
  11353. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  11354. this._caps.textureFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float');
  11355. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear');
  11356. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer();
  11357. this._caps.textureHalfFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float');
  11358. this._caps.textureHalfFloatLinearFiltering = this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'));
  11359. if (this._webGLVersion > 1) {
  11360. this._gl.HALF_FLOAT_OES = 0x140B;
  11361. }
  11362. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  11363. this._caps.textureLOD = this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod');
  11364. // Draw buffers
  11365. if (this._webGLVersion > 1) {
  11366. this._caps.drawBuffersExtension = true;
  11367. }
  11368. else {
  11369. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  11370. if (drawBuffersExtension !== null) {
  11371. this._caps.drawBuffersExtension = true;
  11372. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  11373. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  11374. for (var i = 0; i < 16; i++) {
  11375. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  11376. }
  11377. }
  11378. else {
  11379. this._caps.drawBuffersExtension = false;
  11380. }
  11381. }
  11382. // Depth Texture
  11383. if (this._webGLVersion > 1) {
  11384. this._caps.depthTextureExtension = true;
  11385. }
  11386. else {
  11387. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  11388. if (depthTextureExtension != null) {
  11389. this._caps.depthTextureExtension = true;
  11390. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  11391. }
  11392. }
  11393. // Vertex array object
  11394. if (this._webGLVersion > 1) {
  11395. this._caps.vertexArrayObject = true;
  11396. }
  11397. else {
  11398. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  11399. if (vertexArrayObjectExtension != null) {
  11400. this._caps.vertexArrayObject = true;
  11401. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  11402. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  11403. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  11404. }
  11405. else {
  11406. this._caps.vertexArrayObject = false;
  11407. }
  11408. }
  11409. // Instances count
  11410. if (this._webGLVersion > 1) {
  11411. this._caps.instancedArrays = true;
  11412. }
  11413. else {
  11414. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  11415. if (instanceExtension != null) {
  11416. this._caps.instancedArrays = true;
  11417. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  11418. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  11419. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  11420. }
  11421. else {
  11422. this._caps.instancedArrays = false;
  11423. }
  11424. }
  11425. // Intelligently add supported compressed formats in order to check for.
  11426. // Check for ASTC support first as it is most powerful and to be very cross platform.
  11427. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  11428. // Likely no hardware which supports both PVR & DXT, so order matters little.
  11429. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  11430. if (this._caps.astc)
  11431. this.texturesSupported.push('-astc.ktx');
  11432. if (this._caps.s3tc)
  11433. this.texturesSupported.push('-dxt.ktx');
  11434. if (this._caps.pvrtc)
  11435. this.texturesSupported.push('-pvrtc.ktx');
  11436. if (this._caps.etc2)
  11437. this.texturesSupported.push('-etc2.ktx');
  11438. if (this._caps.etc1)
  11439. this.texturesSupported.push('-etc1.ktx');
  11440. if (this._gl.getShaderPrecisionFormat) {
  11441. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  11442. if (highp) {
  11443. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  11444. }
  11445. }
  11446. // Depth buffer
  11447. this.setDepthBuffer(true);
  11448. this.setDepthFunctionToLessOrEqual();
  11449. this.setDepthWrite(true);
  11450. // Texture maps
  11451. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  11452. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  11453. this._nextFreeTextureSlots.push(slot);
  11454. }
  11455. };
  11456. Object.defineProperty(Engine.prototype, "webGLVersion", {
  11457. get: function () {
  11458. return this._webGLVersion;
  11459. },
  11460. enumerable: true,
  11461. configurable: true
  11462. });
  11463. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  11464. /**
  11465. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  11466. */
  11467. get: function () {
  11468. return this._isStencilEnable;
  11469. },
  11470. enumerable: true,
  11471. configurable: true
  11472. });
  11473. Engine.prototype._prepareWorkingCanvas = function () {
  11474. if (this._workingCanvas) {
  11475. return;
  11476. }
  11477. this._workingCanvas = document.createElement("canvas");
  11478. var context = this._workingCanvas.getContext("2d");
  11479. if (context) {
  11480. this._workingContext = context;
  11481. }
  11482. };
  11483. Engine.prototype.resetTextureCache = function () {
  11484. for (var key in this._boundTexturesCache) {
  11485. var boundTexture = this._boundTexturesCache[key];
  11486. if (boundTexture) {
  11487. this._removeDesignatedSlot(boundTexture);
  11488. }
  11489. this._boundTexturesCache[key] = null;
  11490. }
  11491. if (!this.disableTextureBindingOptimization) {
  11492. this._nextFreeTextureSlots = [];
  11493. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  11494. this._nextFreeTextureSlots.push(slot);
  11495. }
  11496. }
  11497. this._currentTextureChannel = -1;
  11498. };
  11499. Engine.prototype.isDeterministicLockStep = function () {
  11500. return this._deterministicLockstep;
  11501. };
  11502. Engine.prototype.getLockstepMaxSteps = function () {
  11503. return this._lockstepMaxSteps;
  11504. };
  11505. Engine.prototype.getGlInfo = function () {
  11506. return {
  11507. vendor: this._glVendor,
  11508. renderer: this._glRenderer,
  11509. version: this._glVersion
  11510. };
  11511. };
  11512. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  11513. if (useScreen === void 0) { useScreen = false; }
  11514. var viewport = camera.viewport;
  11515. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  11516. };
  11517. Engine.prototype.getRenderWidth = function (useScreen) {
  11518. if (useScreen === void 0) { useScreen = false; }
  11519. if (!useScreen && this._currentRenderTarget) {
  11520. return this._currentRenderTarget.width;
  11521. }
  11522. return this._gl.drawingBufferWidth;
  11523. };
  11524. Engine.prototype.getRenderHeight = function (useScreen) {
  11525. if (useScreen === void 0) { useScreen = false; }
  11526. if (!useScreen && this._currentRenderTarget) {
  11527. return this._currentRenderTarget.height;
  11528. }
  11529. return this._gl.drawingBufferHeight;
  11530. };
  11531. Engine.prototype.getRenderingCanvas = function () {
  11532. return this._renderingCanvas;
  11533. };
  11534. Engine.prototype.getRenderingCanvasClientRect = function () {
  11535. if (!this._renderingCanvas) {
  11536. return null;
  11537. }
  11538. return this._renderingCanvas.getBoundingClientRect();
  11539. };
  11540. Engine.prototype.setHardwareScalingLevel = function (level) {
  11541. this._hardwareScalingLevel = level;
  11542. this.resize();
  11543. };
  11544. Engine.prototype.getHardwareScalingLevel = function () {
  11545. return this._hardwareScalingLevel;
  11546. };
  11547. Engine.prototype.getLoadedTexturesCache = function () {
  11548. return this._internalTexturesCache;
  11549. };
  11550. Engine.prototype.getCaps = function () {
  11551. return this._caps;
  11552. };
  11553. Object.defineProperty(Engine.prototype, "drawCalls", {
  11554. /** The number of draw calls submitted last frame */
  11555. get: function () {
  11556. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  11557. return 0;
  11558. },
  11559. enumerable: true,
  11560. configurable: true
  11561. });
  11562. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  11563. get: function () {
  11564. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  11565. return null;
  11566. },
  11567. enumerable: true,
  11568. configurable: true
  11569. });
  11570. Engine.prototype.getDepthFunction = function () {
  11571. return this._depthCullingState.depthFunc;
  11572. };
  11573. Engine.prototype.setDepthFunction = function (depthFunc) {
  11574. this._depthCullingState.depthFunc = depthFunc;
  11575. };
  11576. Engine.prototype.setDepthFunctionToGreater = function () {
  11577. this._depthCullingState.depthFunc = this._gl.GREATER;
  11578. };
  11579. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  11580. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  11581. };
  11582. Engine.prototype.setDepthFunctionToLess = function () {
  11583. this._depthCullingState.depthFunc = this._gl.LESS;
  11584. };
  11585. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  11586. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  11587. };
  11588. Engine.prototype.getStencilBuffer = function () {
  11589. return this._stencilState.stencilTest;
  11590. };
  11591. Engine.prototype.setStencilBuffer = function (enable) {
  11592. this._stencilState.stencilTest = enable;
  11593. };
  11594. Engine.prototype.getStencilMask = function () {
  11595. return this._stencilState.stencilMask;
  11596. };
  11597. Engine.prototype.setStencilMask = function (mask) {
  11598. this._stencilState.stencilMask = mask;
  11599. };
  11600. Engine.prototype.getStencilFunction = function () {
  11601. return this._stencilState.stencilFunc;
  11602. };
  11603. Engine.prototype.getStencilFunctionReference = function () {
  11604. return this._stencilState.stencilFuncRef;
  11605. };
  11606. Engine.prototype.getStencilFunctionMask = function () {
  11607. return this._stencilState.stencilFuncMask;
  11608. };
  11609. Engine.prototype.setStencilFunction = function (stencilFunc) {
  11610. this._stencilState.stencilFunc = stencilFunc;
  11611. };
  11612. Engine.prototype.setStencilFunctionReference = function (reference) {
  11613. this._stencilState.stencilFuncRef = reference;
  11614. };
  11615. Engine.prototype.setStencilFunctionMask = function (mask) {
  11616. this._stencilState.stencilFuncMask = mask;
  11617. };
  11618. Engine.prototype.getStencilOperationFail = function () {
  11619. return this._stencilState.stencilOpStencilFail;
  11620. };
  11621. Engine.prototype.getStencilOperationDepthFail = function () {
  11622. return this._stencilState.stencilOpDepthFail;
  11623. };
  11624. Engine.prototype.getStencilOperationPass = function () {
  11625. return this._stencilState.stencilOpStencilDepthPass;
  11626. };
  11627. Engine.prototype.setStencilOperationFail = function (operation) {
  11628. this._stencilState.stencilOpStencilFail = operation;
  11629. };
  11630. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  11631. this._stencilState.stencilOpDepthFail = operation;
  11632. };
  11633. Engine.prototype.setStencilOperationPass = function (operation) {
  11634. this._stencilState.stencilOpStencilDepthPass = operation;
  11635. };
  11636. Engine.prototype.setDitheringState = function (value) {
  11637. if (value) {
  11638. this._gl.enable(this._gl.DITHER);
  11639. }
  11640. else {
  11641. this._gl.disable(this._gl.DITHER);
  11642. }
  11643. };
  11644. Engine.prototype.setRasterizerState = function (value) {
  11645. if (value) {
  11646. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  11647. }
  11648. else {
  11649. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  11650. }
  11651. };
  11652. /**
  11653. * stop executing a render loop function and remove it from the execution array
  11654. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  11655. */
  11656. Engine.prototype.stopRenderLoop = function (renderFunction) {
  11657. if (!renderFunction) {
  11658. this._activeRenderLoops = [];
  11659. return;
  11660. }
  11661. var index = this._activeRenderLoops.indexOf(renderFunction);
  11662. if (index >= 0) {
  11663. this._activeRenderLoops.splice(index, 1);
  11664. }
  11665. };
  11666. Engine.prototype._renderLoop = function () {
  11667. if (!this._contextWasLost) {
  11668. var shouldRender = true;
  11669. if (!this.renderEvenInBackground && this._windowIsBackground) {
  11670. shouldRender = false;
  11671. }
  11672. if (shouldRender) {
  11673. // Start new frame
  11674. this.beginFrame();
  11675. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  11676. var renderFunction = this._activeRenderLoops[index];
  11677. renderFunction();
  11678. }
  11679. // Present
  11680. this.endFrame();
  11681. }
  11682. }
  11683. if (this._activeRenderLoops.length > 0) {
  11684. // Register new frame
  11685. var requester = null;
  11686. if (this._vrDisplay && this._vrDisplay.isPresenting)
  11687. requester = this._vrDisplay;
  11688. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  11689. }
  11690. else {
  11691. this._renderingQueueLaunched = false;
  11692. }
  11693. };
  11694. /**
  11695. * Register and execute a render loop. The engine can have more than one render function.
  11696. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  11697. * @example
  11698. * engine.runRenderLoop(function () {
  11699. * scene.render()
  11700. * })
  11701. */
  11702. Engine.prototype.runRenderLoop = function (renderFunction) {
  11703. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  11704. return;
  11705. }
  11706. this._activeRenderLoops.push(renderFunction);
  11707. if (!this._renderingQueueLaunched) {
  11708. this._renderingQueueLaunched = true;
  11709. this._bindedRenderFunction = this._renderLoop.bind(this);
  11710. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  11711. }
  11712. };
  11713. /**
  11714. * Toggle full screen mode.
  11715. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  11716. * @param {any} options - an options object to be sent to the requestFullscreen function
  11717. */
  11718. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  11719. if (this.isFullscreen) {
  11720. BABYLON.Tools.ExitFullscreen();
  11721. }
  11722. else {
  11723. this._pointerLockRequested = requestPointerLock;
  11724. if (this._renderingCanvas) {
  11725. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  11726. }
  11727. }
  11728. };
  11729. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  11730. if (stencil === void 0) { stencil = false; }
  11731. this.applyStates();
  11732. var mode = 0;
  11733. if (backBuffer && color) {
  11734. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  11735. mode |= this._gl.COLOR_BUFFER_BIT;
  11736. }
  11737. if (depth) {
  11738. this._gl.clearDepth(1.0);
  11739. mode |= this._gl.DEPTH_BUFFER_BIT;
  11740. }
  11741. if (stencil) {
  11742. this._gl.clearStencil(0);
  11743. mode |= this._gl.STENCIL_BUFFER_BIT;
  11744. }
  11745. this._gl.clear(mode);
  11746. };
  11747. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  11748. var gl = this._gl;
  11749. // Save state
  11750. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  11751. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  11752. // Change state
  11753. gl.enable(gl.SCISSOR_TEST);
  11754. gl.scissor(x, y, width, height);
  11755. // Clear
  11756. this.clear(clearColor, true, true, true);
  11757. // Restore state
  11758. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  11759. if (curScissor === true) {
  11760. gl.enable(gl.SCISSOR_TEST);
  11761. }
  11762. else {
  11763. gl.disable(gl.SCISSOR_TEST);
  11764. }
  11765. };
  11766. /**
  11767. * Set the WebGL's viewport
  11768. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  11769. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  11770. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  11771. */
  11772. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  11773. var width = requiredWidth || this.getRenderWidth();
  11774. var height = requiredHeight || this.getRenderHeight();
  11775. var x = viewport.x || 0;
  11776. var y = viewport.y || 0;
  11777. this._cachedViewport = viewport;
  11778. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  11779. };
  11780. /**
  11781. * Directly set the WebGL Viewport
  11782. * The x, y, width & height are directly passed to the WebGL call
  11783. * @return the current viewport Object (if any) that is being replaced by this call. You can restore this viewport later on to go back to the original state.
  11784. */
  11785. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  11786. var currentViewport = this._cachedViewport;
  11787. this._cachedViewport = null;
  11788. this._gl.viewport(x, y, width, height);
  11789. return currentViewport;
  11790. };
  11791. Engine.prototype.beginFrame = function () {
  11792. this.onBeginFrameObservable.notifyObservers(this);
  11793. this._measureFps();
  11794. };
  11795. Engine.prototype.endFrame = function () {
  11796. //force a flush in case we are using a bad OS.
  11797. if (this._badOS) {
  11798. this.flushFramebuffer();
  11799. }
  11800. //submit frame to the vr device, if enabled
  11801. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  11802. // TODO: We should only submit the frame if we read frameData successfully.
  11803. this._vrDisplay.submitFrame();
  11804. }
  11805. this.onEndFrameObservable.notifyObservers(this);
  11806. };
  11807. /**
  11808. * resize the view according to the canvas' size.
  11809. * @example
  11810. * window.addEventListener("resize", function () {
  11811. * engine.resize();
  11812. * });
  11813. */
  11814. Engine.prototype.resize = function () {
  11815. // We're not resizing the size of the canvas while in VR mode & presenting
  11816. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  11817. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  11818. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  11819. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  11820. }
  11821. };
  11822. /**
  11823. * force a specific size of the canvas
  11824. * @param {number} width - the new canvas' width
  11825. * @param {number} height - the new canvas' height
  11826. */
  11827. Engine.prototype.setSize = function (width, height) {
  11828. if (!this._renderingCanvas) {
  11829. return;
  11830. }
  11831. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  11832. return;
  11833. }
  11834. this._renderingCanvas.width = width;
  11835. this._renderingCanvas.height = height;
  11836. for (var index = 0; index < this.scenes.length; index++) {
  11837. var scene = this.scenes[index];
  11838. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  11839. var cam = scene.cameras[camIndex];
  11840. cam._currentRenderId = 0;
  11841. }
  11842. }
  11843. if (this.onResizeObservable.hasObservers) {
  11844. this.onResizeObservable.notifyObservers(this);
  11845. }
  11846. };
  11847. // WebVR functions
  11848. Engine.prototype.isVRDevicePresent = function () {
  11849. return !!this._vrDisplay;
  11850. };
  11851. Engine.prototype.getVRDevice = function () {
  11852. return this._vrDisplay;
  11853. };
  11854. /**
  11855. * Initializes a webVR display and starts listening to display change events.
  11856. * The onVRDisplayChangedObservable will be notified upon these changes.
  11857. * @returns The onVRDisplayChangedObservable.
  11858. */
  11859. Engine.prototype.initWebVR = function () {
  11860. this.initWebVRAsync();
  11861. return this.onVRDisplayChangedObservable;
  11862. };
  11863. /**
  11864. * Initializes a webVR display and starts listening to display change events.
  11865. * The onVRDisplayChangedObservable will be notified upon these changes.
  11866. * @returns A promise containing a VRDisplay and if vr is supported.
  11867. */
  11868. Engine.prototype.initWebVRAsync = function () {
  11869. var _this = this;
  11870. var notifyObservers = function () {
  11871. var eventArgs = {
  11872. vrDisplay: _this._vrDisplay,
  11873. vrSupported: _this._vrSupported
  11874. };
  11875. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  11876. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  11877. };
  11878. if (!this._onVrDisplayConnect) {
  11879. this._onVrDisplayConnect = function (event) {
  11880. _this._vrDisplay = event.display;
  11881. notifyObservers();
  11882. };
  11883. this._onVrDisplayDisconnect = function () {
  11884. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  11885. _this._vrDisplay = undefined;
  11886. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  11887. notifyObservers();
  11888. };
  11889. this._onVrDisplayPresentChange = function () {
  11890. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  11891. };
  11892. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  11893. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  11894. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  11895. }
  11896. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  11897. this._webVRInitPromise.then(notifyObservers);
  11898. return this._webVRInitPromise;
  11899. };
  11900. Engine.prototype.enableVR = function () {
  11901. var _this = this;
  11902. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  11903. var onResolved = function () {
  11904. _this.onVRRequestPresentComplete.notifyObservers(true);
  11905. _this._onVRFullScreenTriggered();
  11906. };
  11907. var onRejected = function () {
  11908. _this.onVRRequestPresentComplete.notifyObservers(false);
  11909. };
  11910. this.onVRRequestPresentStart.notifyObservers(this);
  11911. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  11912. }
  11913. };
  11914. Engine.prototype.disableVR = function () {
  11915. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  11916. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  11917. }
  11918. };
  11919. Engine.prototype._getVRDisplaysAsync = function () {
  11920. var _this = this;
  11921. return new Promise(function (res, rej) {
  11922. if (navigator.getVRDisplays) {
  11923. navigator.getVRDisplays().then(function (devices) {
  11924. _this._vrSupported = true;
  11925. // note that devices may actually be an empty array. This is fine;
  11926. // we expect this._vrDisplay to be undefined in this case.
  11927. _this._vrDisplay = devices[0];
  11928. res({
  11929. vrDisplay: _this._vrDisplay,
  11930. vrSupported: _this._vrSupported
  11931. });
  11932. });
  11933. }
  11934. else {
  11935. _this._vrDisplay = undefined;
  11936. _this._vrSupported = false;
  11937. res({
  11938. vrDisplay: _this._vrDisplay,
  11939. vrSupported: _this._vrSupported
  11940. });
  11941. }
  11942. });
  11943. };
  11944. /**
  11945. * Binds the frame buffer to the specified texture.
  11946. * @param texture The texture to render to or null for the default canvas
  11947. * @param faceIndex The face of the texture to render to in case of cube texture
  11948. * @param requiredWidth The width of the target to render to
  11949. * @param requiredHeight The height of the target to render to
  11950. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  11951. * @param depthStencilTexture The depth stencil texture to use to render
  11952. */
  11953. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture) {
  11954. if (this._currentRenderTarget) {
  11955. this.unBindFramebuffer(this._currentRenderTarget);
  11956. }
  11957. this._currentRenderTarget = texture;
  11958. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  11959. var gl = this._gl;
  11960. if (texture.isCube) {
  11961. if (faceIndex === undefined) {
  11962. faceIndex = 0;
  11963. }
  11964. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  11965. if (depthStencilTexture) {
  11966. if (depthStencilTexture._generateStencilBuffer) {
  11967. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture, 0);
  11968. }
  11969. else {
  11970. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture, 0);
  11971. }
  11972. }
  11973. }
  11974. if (this._cachedViewport && !forceFullscreenViewport) {
  11975. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  11976. }
  11977. else {
  11978. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  11979. }
  11980. this.wipeCaches();
  11981. };
  11982. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  11983. if (this._currentFramebuffer !== framebuffer) {
  11984. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  11985. this._currentFramebuffer = framebuffer;
  11986. }
  11987. };
  11988. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  11989. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  11990. this._currentRenderTarget = null;
  11991. // If MSAA, we need to bitblt back to main texture
  11992. var gl = this._gl;
  11993. if (texture._MSAAFramebuffer) {
  11994. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  11995. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  11996. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  11997. }
  11998. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  11999. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  12000. gl.generateMipmap(gl.TEXTURE_2D);
  12001. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12002. }
  12003. if (onBeforeUnbind) {
  12004. if (texture._MSAAFramebuffer) {
  12005. // Bind the correct framebuffer
  12006. this.bindUnboundFramebuffer(texture._framebuffer);
  12007. }
  12008. onBeforeUnbind();
  12009. }
  12010. this.bindUnboundFramebuffer(null);
  12011. };
  12012. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  12013. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  12014. this._currentRenderTarget = null;
  12015. // If MSAA, we need to bitblt back to main texture
  12016. var gl = this._gl;
  12017. if (textures[0]._MSAAFramebuffer) {
  12018. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  12019. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  12020. var attachments = textures[0]._attachments;
  12021. if (!attachments) {
  12022. attachments = new Array(textures.length);
  12023. textures[0]._attachments = attachments;
  12024. }
  12025. for (var i = 0; i < textures.length; i++) {
  12026. var texture = textures[i];
  12027. for (var j = 0; j < attachments.length; j++) {
  12028. attachments[j] = gl.NONE;
  12029. }
  12030. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12031. gl.readBuffer(attachments[i]);
  12032. gl.drawBuffers(attachments);
  12033. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  12034. }
  12035. for (var i = 0; i < attachments.length; i++) {
  12036. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12037. }
  12038. gl.drawBuffers(attachments);
  12039. }
  12040. for (var i = 0; i < textures.length; i++) {
  12041. var texture = textures[i];
  12042. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  12043. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  12044. gl.generateMipmap(gl.TEXTURE_2D);
  12045. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12046. }
  12047. }
  12048. if (onBeforeUnbind) {
  12049. if (textures[0]._MSAAFramebuffer) {
  12050. // Bind the correct framebuffer
  12051. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  12052. }
  12053. onBeforeUnbind();
  12054. }
  12055. this.bindUnboundFramebuffer(null);
  12056. };
  12057. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  12058. if (texture.generateMipMaps) {
  12059. var gl = this._gl;
  12060. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12061. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  12062. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12063. }
  12064. };
  12065. Engine.prototype.flushFramebuffer = function () {
  12066. this._gl.flush();
  12067. };
  12068. Engine.prototype.restoreDefaultFramebuffer = function () {
  12069. if (this._currentRenderTarget) {
  12070. this.unBindFramebuffer(this._currentRenderTarget);
  12071. }
  12072. else {
  12073. this.bindUnboundFramebuffer(null);
  12074. }
  12075. if (this._cachedViewport) {
  12076. this.setViewport(this._cachedViewport);
  12077. }
  12078. this.wipeCaches();
  12079. };
  12080. // UBOs
  12081. Engine.prototype.createUniformBuffer = function (elements) {
  12082. var ubo = this._gl.createBuffer();
  12083. if (!ubo) {
  12084. throw new Error("Unable to create uniform buffer");
  12085. }
  12086. this.bindUniformBuffer(ubo);
  12087. if (elements instanceof Float32Array) {
  12088. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  12089. }
  12090. else {
  12091. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  12092. }
  12093. this.bindUniformBuffer(null);
  12094. ubo.references = 1;
  12095. return ubo;
  12096. };
  12097. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  12098. var ubo = this._gl.createBuffer();
  12099. if (!ubo) {
  12100. throw new Error("Unable to create dynamic uniform buffer");
  12101. }
  12102. this.bindUniformBuffer(ubo);
  12103. if (elements instanceof Float32Array) {
  12104. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  12105. }
  12106. else {
  12107. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  12108. }
  12109. this.bindUniformBuffer(null);
  12110. ubo.references = 1;
  12111. return ubo;
  12112. };
  12113. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  12114. this.bindUniformBuffer(uniformBuffer);
  12115. if (offset === undefined) {
  12116. offset = 0;
  12117. }
  12118. if (count === undefined) {
  12119. if (elements instanceof Float32Array) {
  12120. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  12121. }
  12122. else {
  12123. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  12124. }
  12125. }
  12126. else {
  12127. if (elements instanceof Float32Array) {
  12128. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  12129. }
  12130. else {
  12131. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  12132. }
  12133. }
  12134. this.bindUniformBuffer(null);
  12135. };
  12136. // VBOs
  12137. Engine.prototype._resetVertexBufferBinding = function () {
  12138. this.bindArrayBuffer(null);
  12139. this._cachedVertexBuffers = null;
  12140. };
  12141. Engine.prototype.createVertexBuffer = function (vertices) {
  12142. var vbo = this._gl.createBuffer();
  12143. if (!vbo) {
  12144. throw new Error("Unable to create vertex buffer");
  12145. }
  12146. this.bindArrayBuffer(vbo);
  12147. if (vertices instanceof Float32Array) {
  12148. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  12149. }
  12150. else {
  12151. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  12152. }
  12153. this._resetVertexBufferBinding();
  12154. vbo.references = 1;
  12155. return vbo;
  12156. };
  12157. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  12158. var vbo = this._gl.createBuffer();
  12159. if (!vbo) {
  12160. throw new Error("Unable to create dynamic vertex buffer");
  12161. }
  12162. this.bindArrayBuffer(vbo);
  12163. if (vertices instanceof Float32Array) {
  12164. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  12165. }
  12166. else {
  12167. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  12168. }
  12169. this._resetVertexBufferBinding();
  12170. vbo.references = 1;
  12171. return vbo;
  12172. };
  12173. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  12174. if (offset === void 0) { offset = 0; }
  12175. // Force cache update
  12176. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  12177. this.bindIndexBuffer(indexBuffer);
  12178. var arrayBuffer;
  12179. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  12180. arrayBuffer = indices;
  12181. }
  12182. else {
  12183. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  12184. }
  12185. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  12186. this._resetIndexBufferBinding();
  12187. };
  12188. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  12189. this.bindArrayBuffer(vertexBuffer);
  12190. if (offset === undefined) {
  12191. offset = 0;
  12192. }
  12193. if (count === undefined) {
  12194. if (vertices instanceof Float32Array) {
  12195. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  12196. }
  12197. else {
  12198. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  12199. }
  12200. }
  12201. else {
  12202. if (vertices instanceof Float32Array) {
  12203. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  12204. }
  12205. else {
  12206. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  12207. }
  12208. }
  12209. this._resetVertexBufferBinding();
  12210. };
  12211. Engine.prototype._resetIndexBufferBinding = function () {
  12212. this.bindIndexBuffer(null);
  12213. this._cachedIndexBuffer = null;
  12214. };
  12215. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  12216. var vbo = this._gl.createBuffer();
  12217. if (!vbo) {
  12218. throw new Error("Unable to create index buffer");
  12219. }
  12220. this.bindIndexBuffer(vbo);
  12221. // Check for 32 bits indices
  12222. var arrayBuffer;
  12223. var need32Bits = false;
  12224. if (indices instanceof Uint16Array) {
  12225. arrayBuffer = indices;
  12226. }
  12227. else {
  12228. //check 32 bit support
  12229. if (this._caps.uintIndices) {
  12230. if (indices instanceof Uint32Array) {
  12231. arrayBuffer = indices;
  12232. need32Bits = true;
  12233. }
  12234. else {
  12235. //number[] or Int32Array, check if 32 bit is necessary
  12236. for (var index = 0; index < indices.length; index++) {
  12237. if (indices[index] > 65535) {
  12238. need32Bits = true;
  12239. break;
  12240. }
  12241. }
  12242. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  12243. }
  12244. }
  12245. else {
  12246. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  12247. arrayBuffer = new Uint16Array(indices);
  12248. }
  12249. }
  12250. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  12251. this._resetIndexBufferBinding();
  12252. vbo.references = 1;
  12253. vbo.is32Bits = need32Bits;
  12254. return vbo;
  12255. };
  12256. Engine.prototype.bindArrayBuffer = function (buffer) {
  12257. if (!this._vaoRecordInProgress) {
  12258. this._unbindVertexArrayObject();
  12259. }
  12260. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  12261. };
  12262. Engine.prototype.bindUniformBuffer = function (buffer) {
  12263. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  12264. };
  12265. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  12266. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  12267. };
  12268. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  12269. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  12270. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  12271. };
  12272. ;
  12273. Engine.prototype.bindIndexBuffer = function (buffer) {
  12274. if (!this._vaoRecordInProgress) {
  12275. this._unbindVertexArrayObject();
  12276. }
  12277. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  12278. };
  12279. Engine.prototype.bindBuffer = function (buffer, target) {
  12280. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  12281. this._gl.bindBuffer(target, buffer);
  12282. this._currentBoundBuffer[target] = buffer;
  12283. }
  12284. };
  12285. Engine.prototype.updateArrayBuffer = function (data) {
  12286. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  12287. };
  12288. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  12289. var pointer = this._currentBufferPointers[indx];
  12290. var changed = false;
  12291. if (!pointer.active) {
  12292. changed = true;
  12293. pointer.active = true;
  12294. pointer.index = indx;
  12295. pointer.size = size;
  12296. pointer.type = type;
  12297. pointer.normalized = normalized;
  12298. pointer.stride = stride;
  12299. pointer.offset = offset;
  12300. pointer.buffer = buffer;
  12301. }
  12302. else {
  12303. if (pointer.buffer !== buffer) {
  12304. pointer.buffer = buffer;
  12305. changed = true;
  12306. }
  12307. if (pointer.size !== size) {
  12308. pointer.size = size;
  12309. changed = true;
  12310. }
  12311. if (pointer.type !== type) {
  12312. pointer.type = type;
  12313. changed = true;
  12314. }
  12315. if (pointer.normalized !== normalized) {
  12316. pointer.normalized = normalized;
  12317. changed = true;
  12318. }
  12319. if (pointer.stride !== stride) {
  12320. pointer.stride = stride;
  12321. changed = true;
  12322. }
  12323. if (pointer.offset !== offset) {
  12324. pointer.offset = offset;
  12325. changed = true;
  12326. }
  12327. }
  12328. if (changed || this._vaoRecordInProgress) {
  12329. this.bindArrayBuffer(buffer);
  12330. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  12331. }
  12332. };
  12333. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  12334. if (indexBuffer == null) {
  12335. return;
  12336. }
  12337. if (this._cachedIndexBuffer !== indexBuffer) {
  12338. this._cachedIndexBuffer = indexBuffer;
  12339. this.bindIndexBuffer(indexBuffer);
  12340. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  12341. }
  12342. };
  12343. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  12344. var attributes = effect.getAttributesNames();
  12345. if (!this._vaoRecordInProgress) {
  12346. this._unbindVertexArrayObject();
  12347. }
  12348. this.unbindAllAttributes();
  12349. for (var index = 0; index < attributes.length; index++) {
  12350. var order = effect.getAttributeLocation(index);
  12351. if (order >= 0) {
  12352. var vertexBuffer = vertexBuffers[attributes[index]];
  12353. if (!vertexBuffer) {
  12354. continue;
  12355. }
  12356. this._gl.enableVertexAttribArray(order);
  12357. if (!this._vaoRecordInProgress) {
  12358. this._vertexAttribArraysEnabled[order] = true;
  12359. }
  12360. var buffer = vertexBuffer.getBuffer();
  12361. if (buffer) {
  12362. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  12363. if (vertexBuffer.getIsInstanced()) {
  12364. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  12365. if (!this._vaoRecordInProgress) {
  12366. this._currentInstanceLocations.push(order);
  12367. this._currentInstanceBuffers.push(buffer);
  12368. }
  12369. }
  12370. }
  12371. }
  12372. }
  12373. };
  12374. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  12375. var vao = this._gl.createVertexArray();
  12376. this._vaoRecordInProgress = true;
  12377. this._gl.bindVertexArray(vao);
  12378. this._mustWipeVertexAttributes = true;
  12379. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  12380. this.bindIndexBuffer(indexBuffer);
  12381. this._vaoRecordInProgress = false;
  12382. this._gl.bindVertexArray(null);
  12383. return vao;
  12384. };
  12385. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  12386. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  12387. this._cachedVertexArrayObject = vertexArrayObject;
  12388. this._gl.bindVertexArray(vertexArrayObject);
  12389. this._cachedVertexBuffers = null;
  12390. this._cachedIndexBuffer = null;
  12391. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  12392. this._mustWipeVertexAttributes = true;
  12393. }
  12394. };
  12395. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  12396. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  12397. this._cachedVertexBuffers = vertexBuffer;
  12398. this._cachedEffectForVertexBuffers = effect;
  12399. var attributesCount = effect.getAttributesCount();
  12400. this._unbindVertexArrayObject();
  12401. this.unbindAllAttributes();
  12402. var offset = 0;
  12403. for (var index = 0; index < attributesCount; index++) {
  12404. if (index < vertexDeclaration.length) {
  12405. var order = effect.getAttributeLocation(index);
  12406. if (order >= 0) {
  12407. this._gl.enableVertexAttribArray(order);
  12408. this._vertexAttribArraysEnabled[order] = true;
  12409. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  12410. }
  12411. offset += vertexDeclaration[index] * 4;
  12412. }
  12413. }
  12414. }
  12415. this._bindIndexBufferWithCache(indexBuffer);
  12416. };
  12417. Engine.prototype._unbindVertexArrayObject = function () {
  12418. if (!this._cachedVertexArrayObject) {
  12419. return;
  12420. }
  12421. this._cachedVertexArrayObject = null;
  12422. this._gl.bindVertexArray(null);
  12423. };
  12424. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  12425. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  12426. this._cachedVertexBuffers = vertexBuffers;
  12427. this._cachedEffectForVertexBuffers = effect;
  12428. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  12429. }
  12430. this._bindIndexBufferWithCache(indexBuffer);
  12431. };
  12432. Engine.prototype.unbindInstanceAttributes = function () {
  12433. var boundBuffer;
  12434. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  12435. var instancesBuffer = this._currentInstanceBuffers[i];
  12436. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  12437. boundBuffer = instancesBuffer;
  12438. this.bindArrayBuffer(instancesBuffer);
  12439. }
  12440. var offsetLocation = this._currentInstanceLocations[i];
  12441. this._gl.vertexAttribDivisor(offsetLocation, 0);
  12442. }
  12443. this._currentInstanceBuffers.length = 0;
  12444. this._currentInstanceLocations.length = 0;
  12445. };
  12446. Engine.prototype.releaseVertexArrayObject = function (vao) {
  12447. this._gl.deleteVertexArray(vao);
  12448. };
  12449. Engine.prototype._releaseBuffer = function (buffer) {
  12450. buffer.references--;
  12451. if (buffer.references === 0) {
  12452. this._gl.deleteBuffer(buffer);
  12453. return true;
  12454. }
  12455. return false;
  12456. };
  12457. Engine.prototype.createInstancesBuffer = function (capacity) {
  12458. var buffer = this._gl.createBuffer();
  12459. if (!buffer) {
  12460. throw new Error("Unable to create instance buffer");
  12461. }
  12462. buffer.capacity = capacity;
  12463. this.bindArrayBuffer(buffer);
  12464. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  12465. return buffer;
  12466. };
  12467. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  12468. this._gl.deleteBuffer(buffer);
  12469. };
  12470. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  12471. this.bindArrayBuffer(instancesBuffer);
  12472. if (data) {
  12473. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  12474. }
  12475. if (offsetLocations[0].index !== undefined) {
  12476. var stride = 0;
  12477. for (var i = 0; i < offsetLocations.length; i++) {
  12478. var ai = offsetLocations[i];
  12479. stride += ai.attributeSize * 4;
  12480. }
  12481. for (var i = 0; i < offsetLocations.length; i++) {
  12482. var ai = offsetLocations[i];
  12483. if (!this._vertexAttribArraysEnabled[ai.index]) {
  12484. this._gl.enableVertexAttribArray(ai.index);
  12485. this._vertexAttribArraysEnabled[ai.index] = true;
  12486. }
  12487. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  12488. this._gl.vertexAttribDivisor(ai.index, 1);
  12489. this._currentInstanceLocations.push(ai.index);
  12490. this._currentInstanceBuffers.push(instancesBuffer);
  12491. }
  12492. }
  12493. else {
  12494. for (var index = 0; index < 4; index++) {
  12495. var offsetLocation = offsetLocations[index];
  12496. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  12497. this._gl.enableVertexAttribArray(offsetLocation);
  12498. this._vertexAttribArraysEnabled[offsetLocation] = true;
  12499. }
  12500. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  12501. this._gl.vertexAttribDivisor(offsetLocation, 1);
  12502. this._currentInstanceLocations.push(offsetLocation);
  12503. this._currentInstanceBuffers.push(instancesBuffer);
  12504. }
  12505. }
  12506. };
  12507. Engine.prototype.applyStates = function () {
  12508. this._depthCullingState.apply(this._gl);
  12509. this._stencilState.apply(this._gl);
  12510. this._alphaState.apply(this._gl);
  12511. };
  12512. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  12513. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  12514. };
  12515. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  12516. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  12517. };
  12518. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  12519. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  12520. };
  12521. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  12522. // Apply states
  12523. this.applyStates();
  12524. this._drawCalls.addCount(1, false);
  12525. // Render
  12526. var drawMode = this.DrawMode(fillMode);
  12527. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  12528. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  12529. if (instancesCount) {
  12530. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  12531. }
  12532. else {
  12533. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  12534. }
  12535. };
  12536. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  12537. // Apply states
  12538. this.applyStates();
  12539. this._drawCalls.addCount(1, false);
  12540. var drawMode = this.DrawMode(fillMode);
  12541. if (instancesCount) {
  12542. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  12543. }
  12544. else {
  12545. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  12546. }
  12547. };
  12548. Engine.prototype.DrawMode = function (fillMode) {
  12549. switch (fillMode) {
  12550. // Triangle views
  12551. case BABYLON.Material.TriangleFillMode:
  12552. return this._gl.TRIANGLES;
  12553. case BABYLON.Material.PointFillMode:
  12554. return this._gl.POINTS;
  12555. case BABYLON.Material.WireFrameFillMode:
  12556. return this._gl.LINES;
  12557. // Draw modes
  12558. case BABYLON.Material.PointListDrawMode:
  12559. return this._gl.POINTS;
  12560. case BABYLON.Material.LineListDrawMode:
  12561. return this._gl.LINES;
  12562. case BABYLON.Material.LineLoopDrawMode:
  12563. return this._gl.LINE_LOOP;
  12564. case BABYLON.Material.LineStripDrawMode:
  12565. return this._gl.LINE_STRIP;
  12566. case BABYLON.Material.TriangleStripDrawMode:
  12567. return this._gl.TRIANGLE_STRIP;
  12568. case BABYLON.Material.TriangleFanDrawMode:
  12569. return this._gl.TRIANGLE_FAN;
  12570. default:
  12571. return this._gl.TRIANGLES;
  12572. }
  12573. };
  12574. // Shaders
  12575. Engine.prototype._releaseEffect = function (effect) {
  12576. if (this._compiledEffects[effect._key]) {
  12577. delete this._compiledEffects[effect._key];
  12578. this._deleteProgram(effect.getProgram());
  12579. }
  12580. };
  12581. Engine.prototype._deleteProgram = function (program) {
  12582. if (program) {
  12583. program.__SPECTOR_rebuildProgram = null;
  12584. if (program.transformFeedback) {
  12585. this.deleteTransformFeedback(program.transformFeedback);
  12586. program.transformFeedback = null;
  12587. }
  12588. this._gl.deleteProgram(program);
  12589. }
  12590. };
  12591. /**
  12592. * @param baseName The base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  12593. * @param samplers An array of string used to represent textures
  12594. */
  12595. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  12596. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  12597. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  12598. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  12599. if (this._compiledEffects[name]) {
  12600. var compiledEffect = this._compiledEffects[name];
  12601. if (onCompiled && compiledEffect.isReady()) {
  12602. onCompiled(compiledEffect);
  12603. }
  12604. return compiledEffect;
  12605. }
  12606. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  12607. effect._key = name;
  12608. this._compiledEffects[name] = effect;
  12609. return effect;
  12610. };
  12611. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  12612. if (uniformsNames === void 0) { uniformsNames = []; }
  12613. if (samplers === void 0) { samplers = []; }
  12614. if (defines === void 0) { defines = ""; }
  12615. return this.createEffect({
  12616. vertex: "particles",
  12617. fragmentElement: fragmentName
  12618. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  12619. };
  12620. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  12621. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12622. context = context || this._gl;
  12623. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  12624. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  12625. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  12626. };
  12627. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  12628. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12629. context = context || this._gl;
  12630. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  12631. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n" : "";
  12632. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  12633. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  12634. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  12635. this.onAfterShaderCompilationObservable.notifyObservers(this);
  12636. return program;
  12637. };
  12638. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  12639. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12640. var shaderProgram = context.createProgram();
  12641. if (!shaderProgram) {
  12642. throw new Error("Unable to create program");
  12643. }
  12644. context.attachShader(shaderProgram, vertexShader);
  12645. context.attachShader(shaderProgram, fragmentShader);
  12646. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  12647. var transformFeedback = this.createTransformFeedback();
  12648. this.bindTransformFeedback(transformFeedback);
  12649. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  12650. shaderProgram.transformFeedback = transformFeedback;
  12651. }
  12652. context.linkProgram(shaderProgram);
  12653. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  12654. this.bindTransformFeedback(null);
  12655. }
  12656. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  12657. if (!linked) {
  12658. context.validateProgram(shaderProgram);
  12659. var error = context.getProgramInfoLog(shaderProgram);
  12660. if (error) {
  12661. throw new Error(error);
  12662. }
  12663. }
  12664. context.deleteShader(vertexShader);
  12665. context.deleteShader(fragmentShader);
  12666. return shaderProgram;
  12667. };
  12668. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  12669. var results = new Array();
  12670. for (var index = 0; index < uniformsNames.length; index++) {
  12671. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  12672. }
  12673. return results;
  12674. };
  12675. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  12676. var results = [];
  12677. for (var index = 0; index < attributesNames.length; index++) {
  12678. try {
  12679. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  12680. }
  12681. catch (e) {
  12682. results.push(-1);
  12683. }
  12684. }
  12685. return results;
  12686. };
  12687. Engine.prototype.enableEffect = function (effect) {
  12688. if (!effect) {
  12689. return;
  12690. }
  12691. // Use program
  12692. this.bindSamplers(effect);
  12693. this._currentEffect = effect;
  12694. if (effect.onBind) {
  12695. effect.onBind(effect);
  12696. }
  12697. effect.onBindObservable.notifyObservers(effect);
  12698. };
  12699. Engine.prototype.setIntArray = function (uniform, array) {
  12700. if (!uniform)
  12701. return;
  12702. this._gl.uniform1iv(uniform, array);
  12703. };
  12704. Engine.prototype.setIntArray2 = function (uniform, array) {
  12705. if (!uniform || array.length % 2 !== 0)
  12706. return;
  12707. this._gl.uniform2iv(uniform, array);
  12708. };
  12709. Engine.prototype.setIntArray3 = function (uniform, array) {
  12710. if (!uniform || array.length % 3 !== 0)
  12711. return;
  12712. this._gl.uniform3iv(uniform, array);
  12713. };
  12714. Engine.prototype.setIntArray4 = function (uniform, array) {
  12715. if (!uniform || array.length % 4 !== 0)
  12716. return;
  12717. this._gl.uniform4iv(uniform, array);
  12718. };
  12719. Engine.prototype.setFloatArray = function (uniform, array) {
  12720. if (!uniform)
  12721. return;
  12722. this._gl.uniform1fv(uniform, array);
  12723. };
  12724. Engine.prototype.setFloatArray2 = function (uniform, array) {
  12725. if (!uniform || array.length % 2 !== 0)
  12726. return;
  12727. this._gl.uniform2fv(uniform, array);
  12728. };
  12729. Engine.prototype.setFloatArray3 = function (uniform, array) {
  12730. if (!uniform || array.length % 3 !== 0)
  12731. return;
  12732. this._gl.uniform3fv(uniform, array);
  12733. };
  12734. Engine.prototype.setFloatArray4 = function (uniform, array) {
  12735. if (!uniform || array.length % 4 !== 0)
  12736. return;
  12737. this._gl.uniform4fv(uniform, array);
  12738. };
  12739. Engine.prototype.setArray = function (uniform, array) {
  12740. if (!uniform)
  12741. return;
  12742. this._gl.uniform1fv(uniform, array);
  12743. };
  12744. Engine.prototype.setArray2 = function (uniform, array) {
  12745. if (!uniform || array.length % 2 !== 0)
  12746. return;
  12747. this._gl.uniform2fv(uniform, array);
  12748. };
  12749. Engine.prototype.setArray3 = function (uniform, array) {
  12750. if (!uniform || array.length % 3 !== 0)
  12751. return;
  12752. this._gl.uniform3fv(uniform, array);
  12753. };
  12754. Engine.prototype.setArray4 = function (uniform, array) {
  12755. if (!uniform || array.length % 4 !== 0)
  12756. return;
  12757. this._gl.uniform4fv(uniform, array);
  12758. };
  12759. Engine.prototype.setMatrices = function (uniform, matrices) {
  12760. if (!uniform)
  12761. return;
  12762. this._gl.uniformMatrix4fv(uniform, false, matrices);
  12763. };
  12764. Engine.prototype.setMatrix = function (uniform, matrix) {
  12765. if (!uniform)
  12766. return;
  12767. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  12768. };
  12769. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  12770. if (!uniform)
  12771. return;
  12772. this._gl.uniformMatrix3fv(uniform, false, matrix);
  12773. };
  12774. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  12775. if (!uniform)
  12776. return;
  12777. this._gl.uniformMatrix2fv(uniform, false, matrix);
  12778. };
  12779. Engine.prototype.setInt = function (uniform, value) {
  12780. if (!uniform)
  12781. return;
  12782. this._gl.uniform1i(uniform, value);
  12783. };
  12784. Engine.prototype.setFloat = function (uniform, value) {
  12785. if (!uniform)
  12786. return;
  12787. this._gl.uniform1f(uniform, value);
  12788. };
  12789. Engine.prototype.setFloat2 = function (uniform, x, y) {
  12790. if (!uniform)
  12791. return;
  12792. this._gl.uniform2f(uniform, x, y);
  12793. };
  12794. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  12795. if (!uniform)
  12796. return;
  12797. this._gl.uniform3f(uniform, x, y, z);
  12798. };
  12799. Engine.prototype.setBool = function (uniform, bool) {
  12800. if (!uniform)
  12801. return;
  12802. this._gl.uniform1i(uniform, bool);
  12803. };
  12804. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  12805. if (!uniform)
  12806. return;
  12807. this._gl.uniform4f(uniform, x, y, z, w);
  12808. };
  12809. Engine.prototype.setColor3 = function (uniform, color3) {
  12810. if (!uniform)
  12811. return;
  12812. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  12813. };
  12814. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  12815. if (!uniform)
  12816. return;
  12817. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  12818. };
  12819. /**
  12820. * Sets a Color4 on a uniform variable
  12821. * @param uniform defines the uniform location
  12822. * @param color4 defines the value to be set
  12823. */
  12824. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  12825. if (!uniform)
  12826. return;
  12827. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  12828. };
  12829. // States
  12830. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  12831. if (zOffset === void 0) { zOffset = 0; }
  12832. if (reverseSide === void 0) { reverseSide = false; }
  12833. // Culling
  12834. if (this._depthCullingState.cull !== culling || force) {
  12835. this._depthCullingState.cull = culling;
  12836. }
  12837. // Cull face
  12838. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  12839. if (this._depthCullingState.cullFace !== cullFace || force) {
  12840. this._depthCullingState.cullFace = cullFace;
  12841. }
  12842. // Z offset
  12843. this.setZOffset(zOffset);
  12844. // Front face
  12845. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  12846. if (this._depthCullingState.frontFace !== frontFace || force) {
  12847. this._depthCullingState.frontFace = frontFace;
  12848. }
  12849. };
  12850. Engine.prototype.setZOffset = function (value) {
  12851. this._depthCullingState.zOffset = value;
  12852. };
  12853. Engine.prototype.getZOffset = function () {
  12854. return this._depthCullingState.zOffset;
  12855. };
  12856. Engine.prototype.setDepthBuffer = function (enable) {
  12857. this._depthCullingState.depthTest = enable;
  12858. };
  12859. Engine.prototype.getDepthWrite = function () {
  12860. return this._depthCullingState.depthMask;
  12861. };
  12862. Engine.prototype.setDepthWrite = function (enable) {
  12863. this._depthCullingState.depthMask = enable;
  12864. };
  12865. Engine.prototype.setColorWrite = function (enable) {
  12866. this._gl.colorMask(enable, enable, enable, enable);
  12867. this._colorWrite = enable;
  12868. };
  12869. Engine.prototype.getColorWrite = function () {
  12870. return this._colorWrite;
  12871. };
  12872. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  12873. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  12874. };
  12875. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  12876. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  12877. if (this._alphaMode === mode) {
  12878. return;
  12879. }
  12880. switch (mode) {
  12881. case Engine.ALPHA_DISABLE:
  12882. this._alphaState.alphaBlend = false;
  12883. break;
  12884. case Engine.ALPHA_PREMULTIPLIED:
  12885. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  12886. this._alphaState.alphaBlend = true;
  12887. break;
  12888. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  12889. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  12890. this._alphaState.alphaBlend = true;
  12891. break;
  12892. case Engine.ALPHA_COMBINE:
  12893. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  12894. this._alphaState.alphaBlend = true;
  12895. break;
  12896. case Engine.ALPHA_ONEONE:
  12897. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  12898. this._alphaState.alphaBlend = true;
  12899. break;
  12900. case Engine.ALPHA_ADD:
  12901. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  12902. this._alphaState.alphaBlend = true;
  12903. break;
  12904. case Engine.ALPHA_SUBTRACT:
  12905. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  12906. this._alphaState.alphaBlend = true;
  12907. break;
  12908. case Engine.ALPHA_MULTIPLY:
  12909. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  12910. this._alphaState.alphaBlend = true;
  12911. break;
  12912. case Engine.ALPHA_MAXIMIZED:
  12913. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  12914. this._alphaState.alphaBlend = true;
  12915. break;
  12916. case Engine.ALPHA_INTERPOLATE:
  12917. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  12918. this._alphaState.alphaBlend = true;
  12919. break;
  12920. case Engine.ALPHA_SCREENMODE:
  12921. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  12922. this._alphaState.alphaBlend = true;
  12923. break;
  12924. }
  12925. if (!noDepthWriteChange) {
  12926. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  12927. }
  12928. this._alphaMode = mode;
  12929. };
  12930. Engine.prototype.getAlphaMode = function () {
  12931. return this._alphaMode;
  12932. };
  12933. // Textures
  12934. Engine.prototype.wipeCaches = function (bruteForce) {
  12935. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  12936. return;
  12937. }
  12938. this._currentEffect = null;
  12939. // 6/8/2017: deltakosh: Should not be required anymore.
  12940. // This message is then mostly for the future myself who will scream out loud when seeing that it was actually required :)
  12941. if (bruteForce) {
  12942. this.resetTextureCache();
  12943. this._currentProgram = null;
  12944. this._stencilState.reset();
  12945. this._depthCullingState.reset();
  12946. this.setDepthFunctionToLessOrEqual();
  12947. this._alphaState.reset();
  12948. }
  12949. this._resetVertexBufferBinding();
  12950. this._cachedIndexBuffer = null;
  12951. this._cachedEffectForVertexBuffers = null;
  12952. this._unbindVertexArrayObject();
  12953. this.bindIndexBuffer(null);
  12954. };
  12955. /**
  12956. * Set the compressed texture format to use, based on the formats you have, and the formats
  12957. * supported by the hardware / browser.
  12958. *
  12959. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  12960. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  12961. * to API arguments needed to compressed textures. This puts the burden on the container
  12962. * generator to house the arcane code for determining these for current & future formats.
  12963. *
  12964. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  12965. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  12966. *
  12967. * Note: The result of this call is not taken into account when a texture is base64.
  12968. *
  12969. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  12970. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  12971. *
  12972. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  12973. * @returns The extension selected.
  12974. */
  12975. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  12976. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  12977. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  12978. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  12979. return this._textureFormatInUse = this._texturesSupported[i];
  12980. }
  12981. }
  12982. }
  12983. // actively set format to nothing, to allow this to be called more than once
  12984. // and possibly fail the 2nd time
  12985. this._textureFormatInUse = null;
  12986. return null;
  12987. };
  12988. Engine.prototype._createTexture = function () {
  12989. var texture = this._gl.createTexture();
  12990. if (!texture) {
  12991. throw new Error("Unable to create texture");
  12992. }
  12993. return texture;
  12994. };
  12995. /**
  12996. * Usually called from BABYLON.Texture.ts. Passed information to create a WebGLTexture.
  12997. * @param {string} urlArg- This contains one of the following:
  12998. * 1. A conventional http URL, e.g. 'http://...' or 'file://...'
  12999. * 2. A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  13000. * 3. An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  13001. *
  13002. * @param {boolean} noMipmap- When true, no mipmaps shall be generated. Ignored for compressed textures. They must be in the file.
  13003. * @param {boolean} invertY- When true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file.
  13004. * @param {Scene} scene- Needed for loading to the correct scene.
  13005. * @param {number} samplingMode- Mode with should be used sample / access the texture. Default: TRILINEAR
  13006. * @param {callback} onLoad- Optional callback to be called upon successful completion.
  13007. * @param {callback} onError- Optional callback to be called upon failure.
  13008. * @param {ArrayBuffer | HTMLImageElement} buffer- A source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  13009. * @param {WebGLTexture} fallback- An internal argument in case the function must be called again, due to etc1 not having alpha capabilities.
  13010. * @param {number} format- Internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures.
  13011. *
  13012. * @returns {WebGLTexture} for assignment back into BABYLON.Texture
  13013. */
  13014. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  13015. var _this = this;
  13016. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  13017. if (onLoad === void 0) { onLoad = null; }
  13018. if (onError === void 0) { onError = null; }
  13019. if (buffer === void 0) { buffer = null; }
  13020. if (fallBack === void 0) { fallBack = null; }
  13021. if (format === void 0) { format = null; }
  13022. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  13023. var fromData = url.substr(0, 5) === "data:";
  13024. var fromBlob = url.substr(0, 5) === "blob:";
  13025. var isBase64 = fromData && url.indexOf("base64") !== -1;
  13026. var texture = fallBack ? fallBack : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  13027. // establish the file extension, if possible
  13028. var lastDot = url.lastIndexOf('.');
  13029. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  13030. var isDDS = this.getCaps().s3tc && (extension.indexOf(".dds") === 0);
  13031. var isTGA = (extension.indexOf(".tga") === 0);
  13032. // determine if a ktx file should be substituted
  13033. var isKTX = false;
  13034. if (this._textureFormatInUse && !isBase64 && !fallBack) {
  13035. url = url.substring(0, lastDot) + this._textureFormatInUse;
  13036. isKTX = true;
  13037. }
  13038. if (scene) {
  13039. scene._addPendingData(texture);
  13040. }
  13041. texture.url = url;
  13042. texture.generateMipMaps = !noMipmap;
  13043. texture.samplingMode = samplingMode;
  13044. texture.invertY = invertY;
  13045. if (!this._doNotHandleContextLost) {
  13046. // Keep a link to the buffer only if we plan to handle context lost
  13047. texture._buffer = buffer;
  13048. }
  13049. var onLoadObserver = null;
  13050. if (onLoad && !fallBack) {
  13051. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  13052. }
  13053. if (!fallBack)
  13054. this._internalTexturesCache.push(texture);
  13055. var onerror = function (message, exception) {
  13056. if (scene) {
  13057. scene._removePendingData(texture);
  13058. }
  13059. if (onLoadObserver) {
  13060. texture.onLoadedObservable.remove(onLoadObserver);
  13061. }
  13062. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  13063. if (isKTX) {
  13064. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  13065. }
  13066. else if (BABYLON.Tools.UseFallbackTexture) {
  13067. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  13068. }
  13069. if (onError) {
  13070. onError(message || "Unknown error", exception);
  13071. }
  13072. };
  13073. var callback = null;
  13074. // processing for non-image formats
  13075. if (isKTX || isTGA || isDDS) {
  13076. if (isKTX) {
  13077. callback = function (data) {
  13078. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  13079. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  13080. ktx.uploadLevels(_this._gl, !noMipmap);
  13081. return false;
  13082. }, samplingMode);
  13083. };
  13084. }
  13085. else if (isTGA) {
  13086. callback = function (arrayBuffer) {
  13087. var data = new Uint8Array(arrayBuffer);
  13088. var header = BABYLON.TGATools.GetTGAHeader(data);
  13089. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  13090. BABYLON.TGATools.UploadContent(_this._gl, data);
  13091. return false;
  13092. }, samplingMode);
  13093. };
  13094. }
  13095. else if (isDDS) {
  13096. callback = function (data) {
  13097. var info = BABYLON.DDSTools.GetDDSInfo(data);
  13098. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  13099. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  13100. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  13101. return false;
  13102. }, samplingMode);
  13103. };
  13104. }
  13105. if (!buffer) {
  13106. this._loadFile(url, function (data) {
  13107. if (callback) {
  13108. callback(data);
  13109. }
  13110. }, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  13111. onerror("Unable to load " + (request ? request.responseURL : url, exception));
  13112. });
  13113. }
  13114. else {
  13115. if (callback) {
  13116. callback(buffer);
  13117. }
  13118. }
  13119. // image format processing
  13120. }
  13121. else {
  13122. var onload = function (img) {
  13123. if (fromBlob && !_this._doNotHandleContextLost) {
  13124. // We need to store the image if we need to rebuild the texture
  13125. // in case of a webgl context lost
  13126. texture._buffer = img;
  13127. }
  13128. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  13129. var gl = _this._gl;
  13130. var isPot = (img.width === potWidth && img.height === potHeight);
  13131. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  13132. if (isPot) {
  13133. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  13134. return false;
  13135. }
  13136. // Using shaders to rescale because canvas.drawImage is lossy
  13137. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  13138. _this._bindTextureDirectly(gl.TEXTURE_2D, source, true);
  13139. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  13140. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  13141. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  13142. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13143. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13144. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  13145. _this._releaseTexture(source);
  13146. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13147. continuationCallback();
  13148. });
  13149. return true;
  13150. }, samplingMode);
  13151. };
  13152. if (!fromData || isBase64)
  13153. if (buffer instanceof HTMLImageElement) {
  13154. onload(buffer);
  13155. }
  13156. else {
  13157. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  13158. }
  13159. else if (buffer instanceof Array || typeof buffer === "string" || buffer instanceof ArrayBuffer)
  13160. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  13161. else
  13162. onload(buffer);
  13163. }
  13164. return texture;
  13165. };
  13166. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  13167. var _this = this;
  13168. var rtt = this.createRenderTargetTexture({
  13169. width: destination.width,
  13170. height: destination.height,
  13171. }, {
  13172. generateMipMaps: false,
  13173. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  13174. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  13175. generateDepthBuffer: false,
  13176. generateStencilBuffer: false
  13177. });
  13178. if (!this._rescalePostProcess) {
  13179. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  13180. }
  13181. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  13182. _this._rescalePostProcess.onApply = function (effect) {
  13183. effect._bindTexture("textureSampler", source);
  13184. };
  13185. var hostingScene = scene;
  13186. if (!hostingScene) {
  13187. hostingScene = _this.scenes[_this.scenes.length - 1];
  13188. }
  13189. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  13190. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  13191. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  13192. _this.unBindFramebuffer(rtt);
  13193. _this._releaseTexture(rtt);
  13194. if (onComplete) {
  13195. onComplete();
  13196. }
  13197. });
  13198. };
  13199. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  13200. if (compression === void 0) { compression = null; }
  13201. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  13202. if (!texture) {
  13203. return;
  13204. }
  13205. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  13206. var internalFormat = this._getInternalFormat(format);
  13207. var textureType = this._getWebGLTextureType(type);
  13208. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13209. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  13210. if (!this._doNotHandleContextLost) {
  13211. texture._bufferView = data;
  13212. texture.format = format;
  13213. texture.type = type;
  13214. texture.invertY = invertY;
  13215. texture._compression = compression;
  13216. }
  13217. if (texture.width % 4 !== 0) {
  13218. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  13219. }
  13220. if (compression && data) {
  13221. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  13222. }
  13223. else {
  13224. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  13225. }
  13226. if (texture.generateMipMaps) {
  13227. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13228. }
  13229. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13230. // this.resetTextureCache();
  13231. texture.isReady = true;
  13232. };
  13233. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  13234. if (compression === void 0) { compression = null; }
  13235. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  13236. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  13237. texture.baseWidth = width;
  13238. texture.baseHeight = height;
  13239. texture.width = width;
  13240. texture.height = height;
  13241. texture.format = format;
  13242. texture.generateMipMaps = generateMipMaps;
  13243. texture.samplingMode = samplingMode;
  13244. texture.invertY = invertY;
  13245. texture._compression = compression;
  13246. texture.type = type;
  13247. if (!this._doNotHandleContextLost) {
  13248. texture._bufferView = data;
  13249. }
  13250. this.updateRawTexture(texture, data, format, invertY, compression, type);
  13251. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13252. // Filters
  13253. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  13254. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13255. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13256. if (generateMipMaps) {
  13257. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13258. }
  13259. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13260. this._internalTexturesCache.push(texture);
  13261. return texture;
  13262. };
  13263. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  13264. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  13265. texture.baseWidth = width;
  13266. texture.baseHeight = height;
  13267. if (generateMipMaps) {
  13268. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  13269. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  13270. }
  13271. // this.resetTextureCache();
  13272. texture.width = width;
  13273. texture.height = height;
  13274. texture.isReady = false;
  13275. texture.generateMipMaps = generateMipMaps;
  13276. texture.samplingMode = samplingMode;
  13277. this.updateTextureSamplingMode(samplingMode, texture);
  13278. this._internalTexturesCache.push(texture);
  13279. return texture;
  13280. };
  13281. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  13282. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  13283. if (texture.isCube) {
  13284. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  13285. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13286. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13287. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  13288. }
  13289. else if (texture.is3D) {
  13290. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  13291. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13292. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13293. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  13294. }
  13295. else {
  13296. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13297. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13298. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13299. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13300. }
  13301. texture.samplingMode = samplingMode;
  13302. };
  13303. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  13304. if (premulAlpha === void 0) { premulAlpha = false; }
  13305. if (!texture) {
  13306. return;
  13307. }
  13308. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13309. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  13310. if (premulAlpha) {
  13311. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  13312. }
  13313. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  13314. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  13315. if (texture.generateMipMaps) {
  13316. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13317. }
  13318. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13319. if (premulAlpha) {
  13320. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  13321. }
  13322. texture.isReady = true;
  13323. };
  13324. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  13325. if (!texture || texture._isDisabled) {
  13326. return;
  13327. }
  13328. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13329. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  13330. try {
  13331. // Testing video texture support
  13332. if (this._videoTextureSupported === undefined) {
  13333. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  13334. if (this._gl.getError() !== 0) {
  13335. this._videoTextureSupported = false;
  13336. }
  13337. else {
  13338. this._videoTextureSupported = true;
  13339. }
  13340. }
  13341. // Copy video through the current working canvas if video texture is not supported
  13342. if (!this._videoTextureSupported) {
  13343. if (!texture._workingCanvas) {
  13344. texture._workingCanvas = document.createElement("canvas");
  13345. var context = texture._workingCanvas.getContext("2d");
  13346. if (!context) {
  13347. throw new Error("Unable to get 2d context");
  13348. }
  13349. texture._workingContext = context;
  13350. texture._workingCanvas.width = texture.width;
  13351. texture._workingCanvas.height = texture.height;
  13352. }
  13353. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  13354. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  13355. }
  13356. else {
  13357. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  13358. }
  13359. if (texture.generateMipMaps) {
  13360. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13361. }
  13362. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13363. // this.resetTextureCache();
  13364. texture.isReady = true;
  13365. }
  13366. catch (ex) {
  13367. // Something unexpected
  13368. // Let's disable the texture
  13369. texture._isDisabled = true;
  13370. }
  13371. };
  13372. /**
  13373. * Updates a depth texture Comparison Mode and Function.
  13374. * If the comparison Function is equal to 0, the mode will be set to none.
  13375. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  13376. * @param texture The texture to set the comparison function for
  13377. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  13378. */
  13379. Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {
  13380. if (this.webGLVersion === 1) {
  13381. BABYLON.Tools.Error("WebGL 1 does not support texture comparison.");
  13382. return;
  13383. }
  13384. var gl = this._gl;
  13385. if (texture.isCube) {
  13386. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  13387. if (comparisonFunction === 0) {
  13388. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  13389. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  13390. }
  13391. else {
  13392. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  13393. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  13394. }
  13395. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  13396. }
  13397. else {
  13398. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13399. if (comparisonFunction === 0) {
  13400. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  13401. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  13402. }
  13403. else {
  13404. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  13405. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  13406. }
  13407. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13408. }
  13409. texture._comparisonFunction = comparisonFunction;
  13410. };
  13411. Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
  13412. var width = size.width || size;
  13413. var height = size.height || size;
  13414. internalTexture.baseWidth = width;
  13415. internalTexture.baseHeight = height;
  13416. internalTexture.width = width;
  13417. internalTexture.height = height;
  13418. internalTexture.isReady = true;
  13419. internalTexture.samples = 1;
  13420. internalTexture.generateMipMaps = false;
  13421. internalTexture._generateDepthBuffer = true;
  13422. internalTexture._generateStencilBuffer = generateStencil;
  13423. internalTexture.samplingMode = bilinearFiltering ? BABYLON.Texture.NEAREST_SAMPLINGMODE : BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  13424. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13425. internalTexture._comparisonFunction = comparisonFunction;
  13426. var gl = this._gl;
  13427. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  13428. var samplingParameters = getSamplingParameters(internalTexture.samplingMode, false, gl);
  13429. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  13430. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  13431. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13432. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13433. if (comparisonFunction === 0) {
  13434. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  13435. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  13436. }
  13437. else {
  13438. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  13439. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  13440. }
  13441. };
  13442. /**
  13443. * Creates a depth stencil texture.
  13444. * This is only available in WebGL 2 or with the depth texture extension available.
  13445. * @param size The size of face edge in the texture.
  13446. * @param options The options defining the texture.
  13447. * @returns The texture
  13448. */
  13449. Engine.prototype.createDepthStencilTexture = function (size, options) {
  13450. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);
  13451. if (!this._caps.depthTextureExtension) {
  13452. BABYLON.Tools.Error("Depth texture is not supported by your browser or hardware.");
  13453. return internalTexture;
  13454. }
  13455. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  13456. var gl = this._gl;
  13457. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  13458. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  13459. if (this.webGLVersion > 1) {
  13460. if (internalOptions.generateStencil) {
  13461. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  13462. }
  13463. else {
  13464. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  13465. }
  13466. }
  13467. else {
  13468. if (internalOptions.generateStencil) {
  13469. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  13470. }
  13471. else {
  13472. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  13473. }
  13474. }
  13475. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13476. return internalTexture;
  13477. };
  13478. /**
  13479. * Creates a depth stencil cube texture.
  13480. * This is only available in WebGL 2.
  13481. * @param size The size of face edge in the cube texture.
  13482. * @param options The options defining the cube texture.
  13483. * @returns The cube texture
  13484. */
  13485. Engine.prototype.createDepthStencilCubeTexture = function (size, options) {
  13486. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);
  13487. internalTexture.isCube = true;
  13488. if (this.webGLVersion === 1) {
  13489. BABYLON.Tools.Error("Depth cube texture is not supported by WebGL 1.");
  13490. return internalTexture;
  13491. }
  13492. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  13493. var gl = this._gl;
  13494. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  13495. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  13496. // Create the depth/stencil buffer
  13497. for (var face = 0; face < 6; face++) {
  13498. if (internalOptions.generateStencil) {
  13499. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH24_STENCIL8, size, size, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  13500. }
  13501. else {
  13502. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  13503. }
  13504. }
  13505. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13506. return internalTexture;
  13507. };
  13508. /**
  13509. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  13510. * @param renderTarget The render target to set the frame buffer for
  13511. */
  13512. Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {
  13513. // Create the framebuffer
  13514. var internalTexture = renderTarget.getInternalTexture();
  13515. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  13516. return;
  13517. }
  13518. var gl = this._gl;
  13519. var depthStencilTexture = renderTarget.depthStencilTexture;
  13520. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  13521. if (depthStencilTexture.isCube) {
  13522. if (depthStencilTexture._generateStencilBuffer) {
  13523. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture, 0);
  13524. }
  13525. else {
  13526. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture, 0);
  13527. }
  13528. }
  13529. else {
  13530. if (depthStencilTexture._generateStencilBuffer) {
  13531. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture, 0);
  13532. }
  13533. else {
  13534. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture, 0);
  13535. }
  13536. }
  13537. this.bindUnboundFramebuffer(null);
  13538. };
  13539. Engine.prototype.createRenderTargetTexture = function (size, options) {
  13540. var fullOptions = new RenderTargetCreationOptions();
  13541. if (options !== undefined && typeof options === "object") {
  13542. fullOptions.generateMipMaps = options.generateMipMaps;
  13543. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  13544. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  13545. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  13546. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  13547. fullOptions.format = options.format === undefined ? Engine.TEXTUREFORMAT_RGBA : options.format;
  13548. }
  13549. else {
  13550. fullOptions.generateMipMaps = options;
  13551. fullOptions.generateDepthBuffer = true;
  13552. fullOptions.generateStencilBuffer = false;
  13553. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13554. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  13555. fullOptions.format = Engine.TEXTUREFORMAT_RGBA;
  13556. }
  13557. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  13558. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  13559. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13560. }
  13561. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  13562. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  13563. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13564. }
  13565. var gl = this._gl;
  13566. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  13567. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13568. var width = size.width || size;
  13569. var height = size.height || size;
  13570. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  13571. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  13572. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13573. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  13574. }
  13575. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  13576. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  13577. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13578. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13579. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), width, height, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  13580. // Create the framebuffer
  13581. var framebuffer = gl.createFramebuffer();
  13582. this.bindUnboundFramebuffer(framebuffer);
  13583. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  13584. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  13585. if (fullOptions.generateMipMaps) {
  13586. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13587. }
  13588. // Unbind
  13589. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13590. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13591. this.bindUnboundFramebuffer(null);
  13592. texture._framebuffer = framebuffer;
  13593. texture.baseWidth = width;
  13594. texture.baseHeight = height;
  13595. texture.width = width;
  13596. texture.height = height;
  13597. texture.isReady = true;
  13598. texture.samples = 1;
  13599. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  13600. texture.samplingMode = fullOptions.samplingMode;
  13601. texture.type = fullOptions.type;
  13602. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  13603. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  13604. // this.resetTextureCache();
  13605. this._internalTexturesCache.push(texture);
  13606. return texture;
  13607. };
  13608. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  13609. var generateMipMaps = false;
  13610. var generateDepthBuffer = true;
  13611. var generateStencilBuffer = false;
  13612. var generateDepthTexture = false;
  13613. var textureCount = 1;
  13614. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  13615. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  13616. var types = [], samplingModes = [];
  13617. if (options !== undefined) {
  13618. generateMipMaps = options.generateMipMaps;
  13619. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  13620. generateStencilBuffer = options.generateStencilBuffer;
  13621. generateDepthTexture = options.generateDepthTexture;
  13622. textureCount = options.textureCount || 1;
  13623. if (options.types) {
  13624. types = options.types;
  13625. }
  13626. if (options.samplingModes) {
  13627. samplingModes = options.samplingModes;
  13628. }
  13629. }
  13630. var gl = this._gl;
  13631. // Create the framebuffer
  13632. var framebuffer = gl.createFramebuffer();
  13633. this.bindUnboundFramebuffer(framebuffer);
  13634. var width = size.width || size;
  13635. var height = size.height || size;
  13636. var textures = [];
  13637. var attachments = [];
  13638. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  13639. for (var i = 0; i < textureCount; i++) {
  13640. var samplingMode = samplingModes[i] || defaultSamplingMode;
  13641. var type = types[i] || defaultType;
  13642. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  13643. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  13644. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13645. }
  13646. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  13647. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  13648. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13649. }
  13650. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  13651. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  13652. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13653. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  13654. }
  13655. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  13656. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13657. textures.push(texture);
  13658. attachments.push(attachment);
  13659. gl.activeTexture(gl["TEXTURE" + i]);
  13660. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  13661. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  13662. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  13663. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13664. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13665. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  13666. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  13667. if (generateMipMaps) {
  13668. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13669. }
  13670. // Unbind
  13671. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13672. texture._framebuffer = framebuffer;
  13673. texture._depthStencilBuffer = depthStencilBuffer;
  13674. texture.baseWidth = width;
  13675. texture.baseHeight = height;
  13676. texture.width = width;
  13677. texture.height = height;
  13678. texture.isReady = true;
  13679. texture.samples = 1;
  13680. texture.generateMipMaps = generateMipMaps;
  13681. texture.samplingMode = samplingMode;
  13682. texture.type = type;
  13683. texture._generateDepthBuffer = generateDepthBuffer;
  13684. texture._generateStencilBuffer = generateStencilBuffer;
  13685. texture._attachments = attachments;
  13686. this._internalTexturesCache.push(texture);
  13687. }
  13688. if (generateDepthTexture && this._caps.depthTextureExtension) {
  13689. // Depth texture
  13690. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  13691. gl.activeTexture(gl.TEXTURE0);
  13692. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  13693. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  13694. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  13695. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13696. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13697. gl.texImage2D(gl.TEXTURE_2D, 0, this.webGLVersion < 2 ? gl.DEPTH_COMPONENT : gl.DEPTH_COMPONENT16, width, height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_SHORT, null);
  13698. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  13699. depthTexture._framebuffer = framebuffer;
  13700. depthTexture.baseWidth = width;
  13701. depthTexture.baseHeight = height;
  13702. depthTexture.width = width;
  13703. depthTexture.height = height;
  13704. depthTexture.isReady = true;
  13705. depthTexture.samples = 1;
  13706. depthTexture.generateMipMaps = generateMipMaps;
  13707. depthTexture.samplingMode = gl.NEAREST;
  13708. depthTexture._generateDepthBuffer = generateDepthBuffer;
  13709. depthTexture._generateStencilBuffer = generateStencilBuffer;
  13710. textures.push(depthTexture);
  13711. this._internalTexturesCache.push(depthTexture);
  13712. }
  13713. gl.drawBuffers(attachments);
  13714. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13715. this.bindUnboundFramebuffer(null);
  13716. this.resetTextureCache();
  13717. return textures;
  13718. };
  13719. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  13720. if (samples === void 0) { samples = 1; }
  13721. var depthStencilBuffer = null;
  13722. var gl = this._gl;
  13723. // Create the depth/stencil buffer
  13724. if (generateStencilBuffer) {
  13725. depthStencilBuffer = gl.createRenderbuffer();
  13726. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  13727. if (samples > 1) {
  13728. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  13729. }
  13730. else {
  13731. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  13732. }
  13733. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  13734. }
  13735. else if (generateDepthBuffer) {
  13736. depthStencilBuffer = gl.createRenderbuffer();
  13737. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  13738. if (samples > 1) {
  13739. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  13740. }
  13741. else {
  13742. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  13743. }
  13744. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  13745. }
  13746. return depthStencilBuffer;
  13747. };
  13748. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  13749. if (this.webGLVersion < 2 || !texture) {
  13750. return 1;
  13751. }
  13752. if (texture.samples === samples) {
  13753. return samples;
  13754. }
  13755. var gl = this._gl;
  13756. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  13757. // Dispose previous render buffers
  13758. if (texture._depthStencilBuffer) {
  13759. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  13760. texture._depthStencilBuffer = null;
  13761. }
  13762. if (texture._MSAAFramebuffer) {
  13763. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  13764. texture._MSAAFramebuffer = null;
  13765. }
  13766. if (texture._MSAARenderBuffer) {
  13767. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  13768. texture._MSAARenderBuffer = null;
  13769. }
  13770. if (samples > 1) {
  13771. var framebuffer = gl.createFramebuffer();
  13772. if (!framebuffer) {
  13773. throw new Error("Unable to create multi sampled framebuffer");
  13774. }
  13775. texture._MSAAFramebuffer = framebuffer;
  13776. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  13777. var colorRenderbuffer = gl.createRenderbuffer();
  13778. if (!colorRenderbuffer) {
  13779. throw new Error("Unable to create multi sampled framebuffer");
  13780. }
  13781. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  13782. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  13783. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  13784. texture._MSAARenderBuffer = colorRenderbuffer;
  13785. }
  13786. else {
  13787. this.bindUnboundFramebuffer(texture._framebuffer);
  13788. }
  13789. texture.samples = samples;
  13790. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  13791. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13792. this.bindUnboundFramebuffer(null);
  13793. return samples;
  13794. };
  13795. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  13796. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  13797. return 1;
  13798. }
  13799. if (textures[0].samples === samples) {
  13800. return samples;
  13801. }
  13802. var gl = this._gl;
  13803. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  13804. // Dispose previous render buffers
  13805. if (textures[0]._depthStencilBuffer) {
  13806. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  13807. textures[0]._depthStencilBuffer = null;
  13808. }
  13809. if (textures[0]._MSAAFramebuffer) {
  13810. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  13811. textures[0]._MSAAFramebuffer = null;
  13812. }
  13813. for (var i = 0; i < textures.length; i++) {
  13814. if (textures[i]._MSAARenderBuffer) {
  13815. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  13816. textures[i]._MSAARenderBuffer = null;
  13817. }
  13818. }
  13819. if (samples > 1) {
  13820. var framebuffer = gl.createFramebuffer();
  13821. if (!framebuffer) {
  13822. throw new Error("Unable to create multi sampled framebuffer");
  13823. }
  13824. this.bindUnboundFramebuffer(framebuffer);
  13825. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  13826. var attachments = [];
  13827. for (var i = 0; i < textures.length; i++) {
  13828. var texture = textures[i];
  13829. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13830. var colorRenderbuffer = gl.createRenderbuffer();
  13831. if (!colorRenderbuffer) {
  13832. throw new Error("Unable to create multi sampled framebuffer");
  13833. }
  13834. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  13835. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  13836. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  13837. texture._MSAAFramebuffer = framebuffer;
  13838. texture._MSAARenderBuffer = colorRenderbuffer;
  13839. texture.samples = samples;
  13840. texture._depthStencilBuffer = depthStencilBuffer;
  13841. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13842. attachments.push(attachment);
  13843. }
  13844. gl.drawBuffers(attachments);
  13845. }
  13846. else {
  13847. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  13848. }
  13849. this.bindUnboundFramebuffer(null);
  13850. return samples;
  13851. };
  13852. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  13853. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  13854. };
  13855. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  13856. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  13857. };
  13858. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  13859. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE, format: Engine.TEXTUREFORMAT_RGBA }, options);
  13860. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  13861. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  13862. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  13863. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13864. }
  13865. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  13866. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  13867. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13868. }
  13869. var gl = this._gl;
  13870. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  13871. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13872. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps, gl);
  13873. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  13874. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13875. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  13876. }
  13877. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  13878. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  13879. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13880. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13881. for (var face = 0; face < 6; face++) {
  13882. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), size, size, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  13883. }
  13884. // Create the framebuffer
  13885. var framebuffer = gl.createFramebuffer();
  13886. this.bindUnboundFramebuffer(framebuffer);
  13887. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  13888. // MipMaps
  13889. if (fullOptions.generateMipMaps) {
  13890. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13891. }
  13892. // Unbind
  13893. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13894. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13895. this.bindUnboundFramebuffer(null);
  13896. texture._framebuffer = framebuffer;
  13897. texture.width = size;
  13898. texture.height = size;
  13899. texture.isReady = true;
  13900. texture.isCube = true;
  13901. texture.samples = 1;
  13902. texture.generateMipMaps = fullOptions.generateMipMaps;
  13903. texture.samplingMode = fullOptions.samplingMode;
  13904. texture.type = fullOptions.type;
  13905. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  13906. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  13907. this._internalTexturesCache.push(texture);
  13908. return texture;
  13909. };
  13910. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension) {
  13911. var _this = this;
  13912. if (onLoad === void 0) { onLoad = null; }
  13913. if (onError === void 0) { onError = null; }
  13914. if (forcedExtension === void 0) { forcedExtension = null; }
  13915. var callback = function (loadData) {
  13916. if (!loadData) {
  13917. if (onLoad) {
  13918. onLoad(null);
  13919. }
  13920. return;
  13921. }
  13922. var texture = loadData.texture;
  13923. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  13924. texture._lodGenerationScale = scale;
  13925. texture._lodGenerationOffset = offset;
  13926. if (_this._caps.textureLOD) {
  13927. // Do not add extra process if texture lod is supported.
  13928. if (onLoad) {
  13929. onLoad(texture);
  13930. }
  13931. return;
  13932. }
  13933. var mipSlices = 3;
  13934. var gl = _this._gl;
  13935. var width = loadData.width;
  13936. if (!width) {
  13937. return;
  13938. }
  13939. var textures = [];
  13940. for (var i = 0; i < mipSlices; i++) {
  13941. //compute LOD from even spacing in smoothness (matching shader calculation)
  13942. var smoothness = i / (mipSlices - 1);
  13943. var roughness = 1 - smoothness;
  13944. var minLODIndex = offset; // roughness = 0
  13945. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  13946. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  13947. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  13948. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  13949. glTextureFromLod.isCube = true;
  13950. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  13951. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  13952. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  13953. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13954. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13955. if (loadData.isDDS) {
  13956. var info = loadData.info;
  13957. var data = loadData.data;
  13958. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  13959. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  13960. }
  13961. else {
  13962. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  13963. }
  13964. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13965. // Wrap in a base texture for easy binding.
  13966. var lodTexture = new BABYLON.BaseTexture(scene);
  13967. lodTexture.isCube = true;
  13968. lodTexture._texture = glTextureFromLod;
  13969. glTextureFromLod.isReady = true;
  13970. textures.push(lodTexture);
  13971. }
  13972. texture._lodTextureHigh = textures[2];
  13973. texture._lodTextureMid = textures[1];
  13974. texture._lodTextureLow = textures[0];
  13975. if (onLoad) {
  13976. onLoad(texture);
  13977. }
  13978. };
  13979. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension);
  13980. };
  13981. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension) {
  13982. var _this = this;
  13983. if (onLoad === void 0) { onLoad = null; }
  13984. if (onError === void 0) { onError = null; }
  13985. if (forcedExtension === void 0) { forcedExtension = null; }
  13986. var gl = this._gl;
  13987. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  13988. texture.isCube = true;
  13989. texture.url = rootUrl;
  13990. texture.generateMipMaps = !noMipmap;
  13991. if (!this._doNotHandleContextLost) {
  13992. texture._extension = forcedExtension;
  13993. texture._files = files;
  13994. }
  13995. var isKTX = false;
  13996. var isDDS = false;
  13997. var lastDot = rootUrl.lastIndexOf('.');
  13998. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  13999. if (this._textureFormatInUse) {
  14000. extension = this._textureFormatInUse;
  14001. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  14002. isKTX = true;
  14003. }
  14004. else {
  14005. isDDS = (extension === ".dds");
  14006. }
  14007. var onerror = function (request, exception) {
  14008. if (onError && request) {
  14009. onError(request.status + " " + request.statusText, exception);
  14010. }
  14011. };
  14012. if (isKTX) {
  14013. this._loadFile(rootUrl, function (data) {
  14014. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  14015. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  14016. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14017. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  14018. ktx.uploadLevels(_this._gl, !noMipmap);
  14019. _this.setCubeMapTextureParams(gl, loadMipmap);
  14020. texture.width = ktx.pixelWidth;
  14021. texture.height = ktx.pixelHeight;
  14022. texture.isReady = true;
  14023. }, undefined, undefined, true, onerror);
  14024. }
  14025. else if (isDDS) {
  14026. if (files && files.length === 6) {
  14027. this._cascadeLoadFiles(scene, function (imgs) {
  14028. var info;
  14029. var loadMipmap = false;
  14030. var width = 0;
  14031. for (var index = 0; index < imgs.length; index++) {
  14032. var data = imgs[index];
  14033. info = BABYLON.DDSTools.GetDDSInfo(data);
  14034. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  14035. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14036. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  14037. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6, -1, index);
  14038. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  14039. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  14040. }
  14041. texture.width = info.width;
  14042. texture.height = info.height;
  14043. texture.type = info.textureType;
  14044. width = info.width;
  14045. }
  14046. _this.setCubeMapTextureParams(gl, loadMipmap);
  14047. texture.isReady = true;
  14048. if (onLoad) {
  14049. onLoad({ isDDS: true, width: width, info: info, imgs: imgs, texture: texture });
  14050. }
  14051. }, files, onError);
  14052. }
  14053. else {
  14054. this._loadFile(rootUrl, function (data) {
  14055. var info = BABYLON.DDSTools.GetDDSInfo(data);
  14056. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  14057. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14058. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  14059. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  14060. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  14061. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  14062. }
  14063. _this.setCubeMapTextureParams(gl, loadMipmap);
  14064. texture.width = info.width;
  14065. texture.height = info.height;
  14066. texture.isReady = true;
  14067. texture.type = info.textureType;
  14068. if (onLoad) {
  14069. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  14070. }
  14071. }, undefined, undefined, true, onerror);
  14072. }
  14073. }
  14074. else {
  14075. if (!files) {
  14076. throw new Error("Cannot load cubemap because files were not defined");
  14077. }
  14078. cascadeLoadImgs(rootUrl, scene, function (imgs) {
  14079. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  14080. var height = width;
  14081. _this._prepareWorkingCanvas();
  14082. if (!_this._workingCanvas || !_this._workingContext) {
  14083. return;
  14084. }
  14085. _this._workingCanvas.width = width;
  14086. _this._workingCanvas.height = height;
  14087. var faces = [
  14088. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  14089. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  14090. ];
  14091. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14092. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  14093. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  14094. for (var index = 0; index < faces.length; index++) {
  14095. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  14096. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  14097. }
  14098. if (!noMipmap) {
  14099. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  14100. }
  14101. _this.setCubeMapTextureParams(gl, !noMipmap);
  14102. texture.width = width;
  14103. texture.height = height;
  14104. texture.isReady = true;
  14105. if (format) {
  14106. texture.format = format;
  14107. }
  14108. texture.onLoadedObservable.notifyObservers(texture);
  14109. texture.onLoadedObservable.clear();
  14110. if (onLoad) {
  14111. onLoad();
  14112. }
  14113. }, files, onError);
  14114. }
  14115. this._internalTexturesCache.push(texture);
  14116. return texture;
  14117. };
  14118. Engine.prototype.setCubeMapTextureParams = function (gl, loadMipmap) {
  14119. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  14120. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  14121. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14122. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14123. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14124. // this.resetTextureCache();
  14125. };
  14126. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  14127. if (compression === void 0) { compression = null; }
  14128. if (level === void 0) { level = 0; }
  14129. texture._bufferViewArray = data;
  14130. texture.format = format;
  14131. texture.type = type;
  14132. texture.invertY = invertY;
  14133. texture._compression = compression;
  14134. var gl = this._gl;
  14135. var textureType = this._getWebGLTextureType(type);
  14136. var internalFormat = this._getInternalFormat(format);
  14137. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  14138. var needConversion = false;
  14139. if (internalFormat === gl.RGB) {
  14140. internalFormat = gl.RGBA;
  14141. needConversion = true;
  14142. }
  14143. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14144. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14145. if (texture.width % 4 !== 0) {
  14146. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  14147. }
  14148. // Data are known to be in +X +Y +Z -X -Y -Z
  14149. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  14150. var faceData = data[faceIndex];
  14151. if (compression) {
  14152. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  14153. }
  14154. else {
  14155. if (needConversion) {
  14156. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  14157. }
  14158. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  14159. }
  14160. }
  14161. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  14162. if (isPot && texture.generateMipMaps && level === 0) {
  14163. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  14164. }
  14165. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14166. // this.resetTextureCache();
  14167. texture.isReady = true;
  14168. };
  14169. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  14170. if (compression === void 0) { compression = null; }
  14171. var gl = this._gl;
  14172. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  14173. texture.isCube = true;
  14174. texture.generateMipMaps = generateMipMaps;
  14175. texture.format = format;
  14176. texture.type = type;
  14177. if (!this._doNotHandleContextLost) {
  14178. texture._bufferViewArray = data;
  14179. }
  14180. var textureType = this._getWebGLTextureType(type);
  14181. var internalFormat = this._getInternalFormat(format);
  14182. if (internalFormat === gl.RGB) {
  14183. internalFormat = gl.RGBA;
  14184. }
  14185. var width = size;
  14186. var height = width;
  14187. texture.width = width;
  14188. texture.height = height;
  14189. // Double check on POT to generate Mips.
  14190. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  14191. if (!isPot) {
  14192. generateMipMaps = false;
  14193. }
  14194. // Upload data if needed. The texture won't be ready until then.
  14195. if (data) {
  14196. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  14197. }
  14198. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  14199. // Filters
  14200. if (data && generateMipMaps) {
  14201. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  14202. }
  14203. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  14204. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  14205. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  14206. }
  14207. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  14208. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  14209. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  14210. }
  14211. else {
  14212. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  14213. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  14214. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  14215. }
  14216. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14217. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14218. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14219. return texture;
  14220. };
  14221. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator, onLoad, onError, samplingMode, invertY) {
  14222. var _this = this;
  14223. if (onLoad === void 0) { onLoad = null; }
  14224. if (onError === void 0) { onError = null; }
  14225. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  14226. if (invertY === void 0) { invertY = false; }
  14227. var gl = this._gl;
  14228. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  14229. scene._addPendingData(texture);
  14230. texture.url = url;
  14231. this._internalTexturesCache.push(texture);
  14232. var onerror = function (request, exception) {
  14233. scene._removePendingData(texture);
  14234. if (onError && request) {
  14235. onError(request.status + " " + request.statusText, exception);
  14236. }
  14237. };
  14238. var internalCallback = function (data) {
  14239. var width = texture.width;
  14240. var faceDataArrays = callback(data);
  14241. if (!faceDataArrays) {
  14242. return;
  14243. }
  14244. if (mipmmapGenerator) {
  14245. var textureType = _this._getWebGLTextureType(type);
  14246. var internalFormat = _this._getInternalFormat(format);
  14247. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  14248. var needConversion = false;
  14249. if (internalFormat === gl.RGB) {
  14250. internalFormat = gl.RGBA;
  14251. needConversion = true;
  14252. }
  14253. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14254. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  14255. var mipData = mipmmapGenerator(faceDataArrays);
  14256. for (var level = 0; level < mipData.length; level++) {
  14257. var mipSize = width >> level;
  14258. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  14259. var mipFaceData = mipData[level][faceIndex];
  14260. if (needConversion) {
  14261. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  14262. }
  14263. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  14264. }
  14265. }
  14266. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14267. }
  14268. else {
  14269. texture.generateMipMaps = !noMipmap;
  14270. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  14271. }
  14272. texture.isReady = true;
  14273. // this.resetTextureCache();
  14274. scene._removePendingData(texture);
  14275. if (onLoad) {
  14276. onLoad();
  14277. }
  14278. };
  14279. this._loadFile(url, function (data) {
  14280. internalCallback(data);
  14281. }, undefined, scene.database, true, onerror);
  14282. return texture;
  14283. };
  14284. ;
  14285. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression) {
  14286. if (compression === void 0) { compression = null; }
  14287. var internalFormat = this._getInternalFormat(format);
  14288. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  14289. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14290. if (!this._doNotHandleContextLost) {
  14291. texture._bufferView = data;
  14292. texture.format = format;
  14293. texture.invertY = invertY;
  14294. texture._compression = compression;
  14295. }
  14296. if (texture.width % 4 !== 0) {
  14297. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  14298. }
  14299. if (compression && data) {
  14300. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  14301. }
  14302. else {
  14303. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalFormat, texture.width, texture.height, texture.depth, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  14304. }
  14305. if (texture.generateMipMaps) {
  14306. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  14307. }
  14308. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14309. // this.resetTextureCache();
  14310. texture.isReady = true;
  14311. };
  14312. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression) {
  14313. if (compression === void 0) { compression = null; }
  14314. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  14315. texture.baseWidth = width;
  14316. texture.baseHeight = height;
  14317. texture.baseDepth = depth;
  14318. texture.width = width;
  14319. texture.height = height;
  14320. texture.depth = depth;
  14321. texture.format = format;
  14322. texture.generateMipMaps = generateMipMaps;
  14323. texture.samplingMode = samplingMode;
  14324. texture.is3D = true;
  14325. if (!this._doNotHandleContextLost) {
  14326. texture._bufferView = data;
  14327. }
  14328. this.updateRawTexture3D(texture, data, format, invertY, compression);
  14329. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  14330. // Filters
  14331. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  14332. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  14333. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14334. if (generateMipMaps) {
  14335. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  14336. }
  14337. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14338. this._internalTexturesCache.push(texture);
  14339. return texture;
  14340. };
  14341. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  14342. var gl = this._gl;
  14343. if (!gl) {
  14344. return;
  14345. }
  14346. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  14347. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  14348. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  14349. if (!noMipmap && !isCompressed) {
  14350. gl.generateMipmap(gl.TEXTURE_2D);
  14351. }
  14352. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  14353. // this.resetTextureCache();
  14354. if (scene) {
  14355. scene._removePendingData(texture);
  14356. }
  14357. texture.onLoadedObservable.notifyObservers(texture);
  14358. texture.onLoadedObservable.clear();
  14359. };
  14360. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  14361. var _this = this;
  14362. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  14363. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  14364. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  14365. var gl = this._gl;
  14366. if (!gl) {
  14367. return;
  14368. }
  14369. if (!texture._webGLTexture) {
  14370. // this.resetTextureCache();
  14371. if (scene) {
  14372. scene._removePendingData(texture);
  14373. }
  14374. return;
  14375. }
  14376. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  14377. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14378. texture.baseWidth = width;
  14379. texture.baseHeight = height;
  14380. texture.width = potWidth;
  14381. texture.height = potHeight;
  14382. texture.isReady = true;
  14383. if (processFunction(potWidth, potHeight, function () {
  14384. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  14385. })) {
  14386. // Returning as texture needs extra async steps
  14387. return;
  14388. }
  14389. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  14390. };
  14391. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  14392. // Create new RGBA data container.
  14393. var rgbaData;
  14394. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  14395. rgbaData = new Float32Array(width * height * 4);
  14396. }
  14397. else {
  14398. rgbaData = new Uint32Array(width * height * 4);
  14399. }
  14400. // Convert each pixel.
  14401. for (var x = 0; x < width; x++) {
  14402. for (var y = 0; y < height; y++) {
  14403. var index = (y * width + x) * 3;
  14404. var newIndex = (y * width + x) * 4;
  14405. // Map Old Value to new value.
  14406. rgbaData[newIndex + 0] = rgbData[index + 0];
  14407. rgbaData[newIndex + 1] = rgbData[index + 1];
  14408. rgbaData[newIndex + 2] = rgbData[index + 2];
  14409. // Add fully opaque alpha channel.
  14410. rgbaData[newIndex + 3] = 1;
  14411. }
  14412. }
  14413. return rgbaData;
  14414. };
  14415. Engine.prototype._releaseFramebufferObjects = function (texture) {
  14416. var gl = this._gl;
  14417. if (texture._framebuffer) {
  14418. gl.deleteFramebuffer(texture._framebuffer);
  14419. texture._framebuffer = null;
  14420. }
  14421. if (texture._depthStencilBuffer) {
  14422. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  14423. texture._depthStencilBuffer = null;
  14424. }
  14425. if (texture._MSAAFramebuffer) {
  14426. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  14427. texture._MSAAFramebuffer = null;
  14428. }
  14429. if (texture._MSAARenderBuffer) {
  14430. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  14431. texture._MSAARenderBuffer = null;
  14432. }
  14433. };
  14434. Engine.prototype._releaseTexture = function (texture) {
  14435. var gl = this._gl;
  14436. this._releaseFramebufferObjects(texture);
  14437. gl.deleteTexture(texture._webGLTexture);
  14438. // Unbind channels
  14439. this.unbindAllTextures();
  14440. var index = this._internalTexturesCache.indexOf(texture);
  14441. if (index !== -1) {
  14442. this._internalTexturesCache.splice(index, 1);
  14443. }
  14444. // Integrated fixed lod samplers.
  14445. if (texture._lodTextureHigh) {
  14446. texture._lodTextureHigh.dispose();
  14447. }
  14448. if (texture._lodTextureMid) {
  14449. texture._lodTextureMid.dispose();
  14450. }
  14451. if (texture._lodTextureLow) {
  14452. texture._lodTextureLow.dispose();
  14453. }
  14454. };
  14455. Engine.prototype.setProgram = function (program) {
  14456. if (this._currentProgram !== program) {
  14457. this._gl.useProgram(program);
  14458. this._currentProgram = program;
  14459. }
  14460. };
  14461. Engine.prototype.bindSamplers = function (effect) {
  14462. this.setProgram(effect.getProgram());
  14463. var samplers = effect.getSamplers();
  14464. for (var index = 0; index < samplers.length; index++) {
  14465. var uniform = effect.getUniform(samplers[index]);
  14466. if (uniform) {
  14467. this._boundUniforms[index] = uniform;
  14468. }
  14469. }
  14470. this._currentEffect = null;
  14471. };
  14472. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  14473. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  14474. return;
  14475. }
  14476. // Remove
  14477. this._linkTrackers(internalTexture.previous, internalTexture.next);
  14478. // Bind last to it
  14479. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  14480. // Bind to dummy
  14481. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  14482. };
  14483. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  14484. if (!internalTexture) {
  14485. return -1;
  14486. }
  14487. internalTexture._initialSlot = channel;
  14488. if (this.disableTextureBindingOptimization) {
  14489. if (channel !== internalTexture._designatedSlot) {
  14490. this._textureCollisions.addCount(1, false);
  14491. }
  14492. }
  14493. else {
  14494. if (channel !== internalTexture._designatedSlot) {
  14495. if (internalTexture._designatedSlot > -1) {
  14496. return internalTexture._designatedSlot;
  14497. }
  14498. else {
  14499. // No slot for this texture, let's pick a new one (if we find a free slot)
  14500. if (this._nextFreeTextureSlots.length) {
  14501. return this._nextFreeTextureSlots[0];
  14502. }
  14503. // We need to recycle the oldest bound texture, sorry.
  14504. this._textureCollisions.addCount(1, false);
  14505. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  14506. }
  14507. }
  14508. }
  14509. return channel;
  14510. };
  14511. Engine.prototype._linkTrackers = function (previous, next) {
  14512. previous.next = next;
  14513. next.previous = previous;
  14514. };
  14515. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  14516. var currentSlot = internalTexture._designatedSlot;
  14517. if (currentSlot === -1) {
  14518. return -1;
  14519. }
  14520. internalTexture._designatedSlot = -1;
  14521. if (this.disableTextureBindingOptimization) {
  14522. return -1;
  14523. }
  14524. // Remove from bound list
  14525. this._linkTrackers(internalTexture.previous, internalTexture.next);
  14526. // Free the slot
  14527. this._boundTexturesCache[currentSlot] = null;
  14528. this._nextFreeTextureSlots.push(currentSlot);
  14529. return currentSlot;
  14530. };
  14531. Engine.prototype._activateCurrentTexture = function () {
  14532. if (this._currentTextureChannel !== this._activeChannel) {
  14533. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  14534. this._currentTextureChannel = this._activeChannel;
  14535. }
  14536. };
  14537. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate) {
  14538. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  14539. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  14540. this._activeChannel = texture._designatedSlot;
  14541. }
  14542. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  14543. var isTextureForRendering = texture && texture._initialSlot > -1;
  14544. if (currentTextureBound !== texture) {
  14545. if (currentTextureBound) {
  14546. this._removeDesignatedSlot(currentTextureBound);
  14547. }
  14548. this._activateCurrentTexture();
  14549. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  14550. this._boundTexturesCache[this._activeChannel] = texture;
  14551. if (texture) {
  14552. if (!this.disableTextureBindingOptimization) {
  14553. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  14554. if (slotIndex > -1) {
  14555. this._nextFreeTextureSlots.splice(slotIndex, 1);
  14556. }
  14557. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  14558. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  14559. }
  14560. texture._designatedSlot = this._activeChannel;
  14561. }
  14562. }
  14563. else if (forTextureDataUpdate) {
  14564. this._activateCurrentTexture();
  14565. }
  14566. if (isTextureForRendering && !forTextureDataUpdate) {
  14567. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  14568. }
  14569. };
  14570. Engine.prototype._bindTexture = function (channel, texture) {
  14571. if (channel < 0) {
  14572. return;
  14573. }
  14574. if (texture) {
  14575. channel = this._getCorrectTextureChannel(channel, texture);
  14576. }
  14577. this._activeChannel = channel;
  14578. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  14579. };
  14580. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  14581. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  14582. };
  14583. Engine.prototype.unbindAllTextures = function () {
  14584. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  14585. this._activeChannel = channel;
  14586. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14587. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14588. if (this.webGLVersion > 1) {
  14589. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14590. }
  14591. }
  14592. };
  14593. Engine.prototype.setTexture = function (channel, uniform, texture) {
  14594. if (channel < 0) {
  14595. return;
  14596. }
  14597. if (uniform) {
  14598. this._boundUniforms[channel] = uniform;
  14599. }
  14600. this._setTexture(channel, texture);
  14601. };
  14602. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  14603. var uniform = this._boundUniforms[sourceSlot];
  14604. if (uniform._currentState === destination) {
  14605. return;
  14606. }
  14607. this._gl.uniform1i(uniform, destination);
  14608. uniform._currentState = destination;
  14609. };
  14610. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray) {
  14611. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  14612. // Not ready?
  14613. if (!texture) {
  14614. if (this._boundTexturesCache[channel] != null) {
  14615. this._activeChannel = channel;
  14616. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14617. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14618. if (this.webGLVersion > 1) {
  14619. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14620. }
  14621. }
  14622. return false;
  14623. }
  14624. // Video
  14625. if (texture.video) {
  14626. this._activeChannel = channel;
  14627. texture.update();
  14628. }
  14629. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  14630. texture.delayLoad();
  14631. return false;
  14632. }
  14633. var internalTexture;
  14634. if (texture.isReady()) {
  14635. internalTexture = texture.getInternalTexture();
  14636. }
  14637. else if (texture.isCube) {
  14638. internalTexture = this.emptyCubeTexture;
  14639. }
  14640. else if (texture.is3D) {
  14641. internalTexture = this.emptyTexture3D;
  14642. }
  14643. else {
  14644. internalTexture = this.emptyTexture;
  14645. }
  14646. if (!isPartOfTextureArray) {
  14647. channel = this._getCorrectTextureChannel(channel, internalTexture);
  14648. }
  14649. if (this._boundTexturesCache[channel] === internalTexture) {
  14650. this._moveBoundTextureOnTop(internalTexture);
  14651. if (!isPartOfTextureArray) {
  14652. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  14653. }
  14654. return false;
  14655. }
  14656. this._activeChannel = channel;
  14657. if (internalTexture && internalTexture.is3D) {
  14658. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  14659. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  14660. internalTexture._cachedWrapU = texture.wrapU;
  14661. switch (texture.wrapU) {
  14662. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14663. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  14664. break;
  14665. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14666. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  14667. break;
  14668. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14669. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  14670. break;
  14671. }
  14672. }
  14673. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  14674. internalTexture._cachedWrapV = texture.wrapV;
  14675. switch (texture.wrapV) {
  14676. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14677. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  14678. break;
  14679. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14680. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  14681. break;
  14682. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14683. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  14684. break;
  14685. }
  14686. }
  14687. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  14688. internalTexture._cachedWrapR = texture.wrapR;
  14689. switch (texture.wrapR) {
  14690. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14691. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.REPEAT);
  14692. break;
  14693. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14694. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.CLAMP_TO_EDGE);
  14695. break;
  14696. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14697. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.MIRRORED_REPEAT);
  14698. break;
  14699. }
  14700. }
  14701. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  14702. }
  14703. else if (internalTexture && internalTexture.isCube) {
  14704. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  14705. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  14706. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  14707. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  14708. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  14709. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  14710. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  14711. }
  14712. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  14713. }
  14714. else {
  14715. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  14716. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  14717. internalTexture._cachedWrapU = texture.wrapU;
  14718. switch (texture.wrapU) {
  14719. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14720. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  14721. break;
  14722. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14723. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  14724. break;
  14725. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14726. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  14727. break;
  14728. }
  14729. }
  14730. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  14731. internalTexture._cachedWrapV = texture.wrapV;
  14732. switch (texture.wrapV) {
  14733. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14734. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  14735. break;
  14736. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14737. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  14738. break;
  14739. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14740. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  14741. break;
  14742. }
  14743. }
  14744. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  14745. }
  14746. return true;
  14747. };
  14748. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  14749. if (channel < 0 || !uniform) {
  14750. return;
  14751. }
  14752. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  14753. this._textureUnits = new Int32Array(textures.length);
  14754. }
  14755. for (var i = 0; i < textures.length; i++) {
  14756. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  14757. }
  14758. this._gl.uniform1iv(uniform, this._textureUnits);
  14759. for (var index = 0; index < textures.length; index++) {
  14760. this._setTexture(this._textureUnits[index], textures[index], true);
  14761. }
  14762. };
  14763. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  14764. var internalTexture = texture.getInternalTexture();
  14765. if (!internalTexture) {
  14766. return;
  14767. }
  14768. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  14769. var value = texture.anisotropicFilteringLevel;
  14770. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  14771. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  14772. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  14773. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  14774. }
  14775. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  14776. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  14777. internalTexture._cachedAnisotropicFilteringLevel = value;
  14778. }
  14779. };
  14780. Engine.prototype.readPixels = function (x, y, width, height) {
  14781. var data = new Uint8Array(height * width * 4);
  14782. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  14783. return data;
  14784. };
  14785. /**
  14786. * Add an externaly attached data from its key.
  14787. * This method call will fail and return false, if such key already exists.
  14788. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  14789. * @param key the unique key that identifies the data
  14790. * @param data the data object to associate to the key for this Engine instance
  14791. * @return true if no such key were already present and the data was added successfully, false otherwise
  14792. */
  14793. Engine.prototype.addExternalData = function (key, data) {
  14794. if (!this._externalData) {
  14795. this._externalData = new BABYLON.StringDictionary();
  14796. }
  14797. return this._externalData.add(key, data);
  14798. };
  14799. /**
  14800. * Get an externaly attached data from its key
  14801. * @param key the unique key that identifies the data
  14802. * @return the associated data, if present (can be null), or undefined if not present
  14803. */
  14804. Engine.prototype.getExternalData = function (key) {
  14805. if (!this._externalData) {
  14806. this._externalData = new BABYLON.StringDictionary();
  14807. }
  14808. return this._externalData.get(key);
  14809. };
  14810. /**
  14811. * Get an externaly attached data from its key, create it using a factory if it's not already present
  14812. * @param key the unique key that identifies the data
  14813. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  14814. * @return the associated data, can be null if the factory returned null.
  14815. */
  14816. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  14817. if (!this._externalData) {
  14818. this._externalData = new BABYLON.StringDictionary();
  14819. }
  14820. return this._externalData.getOrAddWithFactory(key, factory);
  14821. };
  14822. /**
  14823. * Remove an externaly attached data from the Engine instance
  14824. * @param key the unique key that identifies the data
  14825. * @return true if the data was successfully removed, false if it doesn't exist
  14826. */
  14827. Engine.prototype.removeExternalData = function (key) {
  14828. if (!this._externalData) {
  14829. this._externalData = new BABYLON.StringDictionary();
  14830. }
  14831. return this._externalData.remove(key);
  14832. };
  14833. Engine.prototype.unbindAllAttributes = function () {
  14834. if (this._mustWipeVertexAttributes) {
  14835. this._mustWipeVertexAttributes = false;
  14836. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  14837. this._gl.disableVertexAttribArray(i);
  14838. this._vertexAttribArraysEnabled[i] = false;
  14839. this._currentBufferPointers[i].active = false;
  14840. }
  14841. return;
  14842. }
  14843. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  14844. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  14845. continue;
  14846. }
  14847. this._gl.disableVertexAttribArray(i);
  14848. this._vertexAttribArraysEnabled[i] = false;
  14849. this._currentBufferPointers[i].active = false;
  14850. }
  14851. };
  14852. Engine.prototype.releaseEffects = function () {
  14853. for (var name in this._compiledEffects) {
  14854. this._deleteProgram(this._compiledEffects[name]._program);
  14855. }
  14856. this._compiledEffects = {};
  14857. };
  14858. // Dispose
  14859. Engine.prototype.dispose = function () {
  14860. this.hideLoadingUI();
  14861. this.stopRenderLoop();
  14862. // Release postProcesses
  14863. while (this.postProcesses.length) {
  14864. this.postProcesses[0].dispose();
  14865. }
  14866. // Empty texture
  14867. if (this._emptyTexture) {
  14868. this._releaseTexture(this._emptyTexture);
  14869. this._emptyTexture = null;
  14870. }
  14871. if (this._emptyCubeTexture) {
  14872. this._releaseTexture(this._emptyCubeTexture);
  14873. this._emptyCubeTexture = null;
  14874. }
  14875. // Rescale PP
  14876. if (this._rescalePostProcess) {
  14877. this._rescalePostProcess.dispose();
  14878. }
  14879. // Release scenes
  14880. while (this.scenes.length) {
  14881. this.scenes[0].dispose();
  14882. }
  14883. // Release audio engine
  14884. if (Engine.audioEngine) {
  14885. Engine.audioEngine.dispose();
  14886. }
  14887. // Release effects
  14888. this.releaseEffects();
  14889. // Unbind
  14890. this.unbindAllAttributes();
  14891. if (this._dummyFramebuffer) {
  14892. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  14893. }
  14894. //WebVR
  14895. this.disableVR();
  14896. // Events
  14897. if (BABYLON.Tools.IsWindowObjectExist()) {
  14898. window.removeEventListener("blur", this._onBlur);
  14899. window.removeEventListener("focus", this._onFocus);
  14900. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  14901. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  14902. if (this._renderingCanvas) {
  14903. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  14904. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  14905. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasPointerOut);
  14906. if (!this._doNotHandleContextLost) {
  14907. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  14908. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  14909. }
  14910. }
  14911. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  14912. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  14913. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  14914. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  14915. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  14916. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  14917. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  14918. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  14919. if (this._onVrDisplayConnect) {
  14920. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  14921. if (this._onVrDisplayDisconnect) {
  14922. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  14923. }
  14924. if (this._onVrDisplayPresentChange) {
  14925. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  14926. }
  14927. this._onVrDisplayConnect = null;
  14928. this._onVrDisplayDisconnect = null;
  14929. }
  14930. }
  14931. // Remove from Instances
  14932. var index = Engine.Instances.indexOf(this);
  14933. if (index >= 0) {
  14934. Engine.Instances.splice(index, 1);
  14935. }
  14936. this._workingCanvas = null;
  14937. this._workingContext = null;
  14938. this._currentBufferPointers = [];
  14939. this._renderingCanvas = null;
  14940. this._currentProgram = null;
  14941. this._bindedRenderFunction = null;
  14942. this.onResizeObservable.clear();
  14943. this.onCanvasBlurObservable.clear();
  14944. this.onCanvasFocusObservable.clear();
  14945. this.onCanvasPointerOutObservable.clear();
  14946. this.onBeginFrameObservable.clear();
  14947. this.onEndFrameObservable.clear();
  14948. BABYLON.Effect.ResetCache();
  14949. // Abort active requests
  14950. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  14951. var request = _a[_i];
  14952. request.abort();
  14953. }
  14954. };
  14955. // Loading screen
  14956. Engine.prototype.displayLoadingUI = function () {
  14957. if (!BABYLON.Tools.IsWindowObjectExist()) {
  14958. return;
  14959. }
  14960. var loadingScreen = this.loadingScreen;
  14961. if (loadingScreen) {
  14962. loadingScreen.displayLoadingUI();
  14963. }
  14964. };
  14965. Engine.prototype.hideLoadingUI = function () {
  14966. if (!BABYLON.Tools.IsWindowObjectExist()) {
  14967. return;
  14968. }
  14969. var loadingScreen = this.loadingScreen;
  14970. if (loadingScreen) {
  14971. loadingScreen.hideLoadingUI();
  14972. }
  14973. };
  14974. Object.defineProperty(Engine.prototype, "loadingScreen", {
  14975. get: function () {
  14976. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  14977. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  14978. return this._loadingScreen;
  14979. },
  14980. set: function (loadingScreen) {
  14981. this._loadingScreen = loadingScreen;
  14982. },
  14983. enumerable: true,
  14984. configurable: true
  14985. });
  14986. Object.defineProperty(Engine.prototype, "loadingUIText", {
  14987. set: function (text) {
  14988. this.loadingScreen.loadingUIText = text;
  14989. },
  14990. enumerable: true,
  14991. configurable: true
  14992. });
  14993. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  14994. set: function (color) {
  14995. this.loadingScreen.loadingUIBackgroundColor = color;
  14996. },
  14997. enumerable: true,
  14998. configurable: true
  14999. });
  15000. Engine.prototype.attachContextLostEvent = function (callback) {
  15001. if (this._renderingCanvas) {
  15002. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  15003. }
  15004. };
  15005. Engine.prototype.attachContextRestoredEvent = function (callback) {
  15006. if (this._renderingCanvas) {
  15007. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  15008. }
  15009. };
  15010. Engine.prototype.getVertexShaderSource = function (program) {
  15011. var shaders = this._gl.getAttachedShaders(program);
  15012. if (!shaders) {
  15013. return null;
  15014. }
  15015. return this._gl.getShaderSource(shaders[0]);
  15016. };
  15017. Engine.prototype.getFragmentShaderSource = function (program) {
  15018. var shaders = this._gl.getAttachedShaders(program);
  15019. if (!shaders) {
  15020. return null;
  15021. }
  15022. return this._gl.getShaderSource(shaders[1]);
  15023. };
  15024. Engine.prototype.getError = function () {
  15025. return this._gl.getError();
  15026. };
  15027. // FPS
  15028. Engine.prototype.getFps = function () {
  15029. return this._fps;
  15030. };
  15031. Engine.prototype.getDeltaTime = function () {
  15032. return this._deltaTime;
  15033. };
  15034. Engine.prototype._measureFps = function () {
  15035. this._performanceMonitor.sampleFrame();
  15036. this._fps = this._performanceMonitor.averageFPS;
  15037. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  15038. };
  15039. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  15040. if (faceIndex === void 0) { faceIndex = -1; }
  15041. var gl = this._gl;
  15042. if (!this._dummyFramebuffer) {
  15043. var dummy = gl.createFramebuffer();
  15044. if (!dummy) {
  15045. throw new Error("Unable to create dummy framebuffer");
  15046. }
  15047. this._dummyFramebuffer = dummy;
  15048. }
  15049. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  15050. if (faceIndex > -1) {
  15051. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  15052. }
  15053. else {
  15054. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15055. }
  15056. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  15057. var buffer;
  15058. switch (readType) {
  15059. case gl.UNSIGNED_BYTE:
  15060. buffer = new Uint8Array(4 * width * height);
  15061. readType = gl.UNSIGNED_BYTE;
  15062. break;
  15063. default:
  15064. buffer = new Float32Array(4 * width * height);
  15065. readType = gl.FLOAT;
  15066. break;
  15067. }
  15068. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  15069. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  15070. return buffer;
  15071. };
  15072. Engine.prototype._canRenderToFloatFramebuffer = function () {
  15073. if (this._webGLVersion > 1) {
  15074. return this._caps.colorBufferFloat;
  15075. }
  15076. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  15077. };
  15078. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  15079. if (this._webGLVersion > 1) {
  15080. return this._caps.colorBufferFloat;
  15081. }
  15082. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  15083. };
  15084. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  15085. Engine.prototype._canRenderToFramebuffer = function (type) {
  15086. var gl = this._gl;
  15087. //clear existing errors
  15088. while (gl.getError() !== gl.NO_ERROR) { }
  15089. var successful = true;
  15090. var texture = gl.createTexture();
  15091. gl.bindTexture(gl.TEXTURE_2D, texture);
  15092. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  15093. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15094. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15095. var fb = gl.createFramebuffer();
  15096. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  15097. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  15098. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  15099. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  15100. successful = successful && (gl.getError() === gl.NO_ERROR);
  15101. //try render by clearing frame buffer's color buffer
  15102. if (successful) {
  15103. gl.clear(gl.COLOR_BUFFER_BIT);
  15104. successful = successful && (gl.getError() === gl.NO_ERROR);
  15105. }
  15106. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  15107. if (successful) {
  15108. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  15109. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  15110. var readFormat = gl.RGBA;
  15111. var readType = gl.UNSIGNED_BYTE;
  15112. var buffer = new Uint8Array(4);
  15113. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  15114. successful = successful && (gl.getError() === gl.NO_ERROR);
  15115. }
  15116. //clean up
  15117. gl.deleteTexture(texture);
  15118. gl.deleteFramebuffer(fb);
  15119. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  15120. //clear accumulated errors
  15121. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  15122. return successful;
  15123. };
  15124. Engine.prototype._getWebGLTextureType = function (type) {
  15125. if (type === Engine.TEXTURETYPE_FLOAT) {
  15126. return this._gl.FLOAT;
  15127. }
  15128. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  15129. // Add Half Float Constant.
  15130. return this._gl.HALF_FLOAT_OES;
  15131. }
  15132. return this._gl.UNSIGNED_BYTE;
  15133. };
  15134. ;
  15135. Engine.prototype._getInternalFormat = function (format) {
  15136. var internalFormat = this._gl.RGBA;
  15137. switch (format) {
  15138. case Engine.TEXTUREFORMAT_ALPHA:
  15139. internalFormat = this._gl.ALPHA;
  15140. break;
  15141. case Engine.TEXTUREFORMAT_LUMINANCE:
  15142. internalFormat = this._gl.LUMINANCE;
  15143. break;
  15144. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  15145. internalFormat = this._gl.LUMINANCE_ALPHA;
  15146. break;
  15147. case Engine.TEXTUREFORMAT_RGB:
  15148. case Engine.TEXTUREFORMAT_RGB32F:
  15149. internalFormat = this._gl.RGB;
  15150. break;
  15151. case Engine.TEXTUREFORMAT_RGBA:
  15152. case Engine.TEXTUREFORMAT_RGBA32F:
  15153. internalFormat = this._gl.RGBA;
  15154. break;
  15155. case Engine.TEXTUREFORMAT_R32F:
  15156. internalFormat = this._gl.RED;
  15157. break;
  15158. case Engine.TEXTUREFORMAT_RG32F:
  15159. internalFormat = this._gl.RG;
  15160. break;
  15161. }
  15162. return internalFormat;
  15163. };
  15164. /** @ignore */
  15165. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  15166. if (this._webGLVersion === 1) {
  15167. if (format) {
  15168. switch (format) {
  15169. case Engine.TEXTUREFORMAT_LUMINANCE:
  15170. return this._gl.LUMINANCE;
  15171. }
  15172. }
  15173. return this._gl.RGBA;
  15174. }
  15175. if (type === Engine.TEXTURETYPE_FLOAT) {
  15176. if (format) {
  15177. switch (format) {
  15178. case Engine.TEXTUREFORMAT_R32F:
  15179. return this._gl.R32F;
  15180. case Engine.TEXTUREFORMAT_RG32F:
  15181. return this._gl.RG32F;
  15182. case Engine.TEXTUREFORMAT_RGB32F:
  15183. return this._gl.RGB32F;
  15184. }
  15185. }
  15186. return this._gl.RGBA32F;
  15187. }
  15188. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  15189. return this._gl.RGBA16F;
  15190. }
  15191. if (format) {
  15192. switch (format) {
  15193. case Engine.TEXTUREFORMAT_LUMINANCE:
  15194. return this._gl.LUMINANCE;
  15195. }
  15196. }
  15197. return this._gl.RGBA;
  15198. };
  15199. ;
  15200. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  15201. if (type === Engine.TEXTURETYPE_FLOAT) {
  15202. return this._gl.RGBA32F;
  15203. }
  15204. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  15205. return this._gl.RGBA16F;
  15206. }
  15207. return this._gl.RGBA8;
  15208. };
  15209. ;
  15210. Engine.prototype.createQuery = function () {
  15211. return this._gl.createQuery();
  15212. };
  15213. Engine.prototype.deleteQuery = function (query) {
  15214. this._gl.deleteQuery(query);
  15215. return this;
  15216. };
  15217. Engine.prototype.isQueryResultAvailable = function (query) {
  15218. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  15219. };
  15220. Engine.prototype.getQueryResult = function (query) {
  15221. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  15222. };
  15223. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  15224. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  15225. this._gl.beginQuery(glAlgorithm, query);
  15226. return this;
  15227. };
  15228. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  15229. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  15230. this._gl.endQuery(glAlgorithm);
  15231. return this;
  15232. };
  15233. /* Time queries */
  15234. Engine.prototype._createTimeQuery = function () {
  15235. var timerQuery = this._caps.timerQuery;
  15236. if (timerQuery.createQueryEXT) {
  15237. return timerQuery.createQueryEXT();
  15238. }
  15239. return this.createQuery();
  15240. };
  15241. Engine.prototype._deleteTimeQuery = function (query) {
  15242. var timerQuery = this._caps.timerQuery;
  15243. if (timerQuery.deleteQueryEXT) {
  15244. timerQuery.deleteQueryEXT(query);
  15245. return;
  15246. }
  15247. this.deleteQuery(query);
  15248. };
  15249. Engine.prototype._getTimeQueryResult = function (query) {
  15250. var timerQuery = this._caps.timerQuery;
  15251. if (timerQuery.getQueryObjectEXT) {
  15252. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  15253. }
  15254. return this.getQueryResult(query);
  15255. };
  15256. Engine.prototype._getTimeQueryAvailability = function (query) {
  15257. var timerQuery = this._caps.timerQuery;
  15258. if (timerQuery.getQueryObjectEXT) {
  15259. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  15260. }
  15261. return this.isQueryResultAvailable(query);
  15262. };
  15263. Engine.prototype.startTimeQuery = function () {
  15264. var timerQuery = this._caps.timerQuery;
  15265. if (!timerQuery) {
  15266. return null;
  15267. }
  15268. var token = new BABYLON._TimeToken();
  15269. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  15270. if (this._caps.canUseTimestampForTimerQuery) {
  15271. token._startTimeQuery = this._createTimeQuery();
  15272. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  15273. }
  15274. else {
  15275. if (this._currentNonTimestampToken) {
  15276. return this._currentNonTimestampToken;
  15277. }
  15278. token._timeElapsedQuery = this._createTimeQuery();
  15279. if (timerQuery.beginQueryEXT) {
  15280. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  15281. }
  15282. else {
  15283. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  15284. }
  15285. this._currentNonTimestampToken = token;
  15286. }
  15287. return token;
  15288. };
  15289. Engine.prototype.endTimeQuery = function (token) {
  15290. var timerQuery = this._caps.timerQuery;
  15291. if (!timerQuery || !token) {
  15292. return -1;
  15293. }
  15294. if (this._caps.canUseTimestampForTimerQuery) {
  15295. if (!token._startTimeQuery) {
  15296. return -1;
  15297. }
  15298. if (!token._endTimeQuery) {
  15299. token._endTimeQuery = this._createTimeQuery();
  15300. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  15301. }
  15302. }
  15303. else if (!token._timeElapsedQueryEnded) {
  15304. if (!token._timeElapsedQuery) {
  15305. return -1;
  15306. }
  15307. if (timerQuery.endQueryEXT) {
  15308. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  15309. }
  15310. else {
  15311. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  15312. }
  15313. token._timeElapsedQueryEnded = true;
  15314. }
  15315. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  15316. var available = false;
  15317. if (token._endTimeQuery) {
  15318. available = this._getTimeQueryAvailability(token._endTimeQuery);
  15319. }
  15320. else if (token._timeElapsedQuery) {
  15321. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  15322. }
  15323. if (available && !disjoint) {
  15324. var result = 0;
  15325. if (this._caps.canUseTimestampForTimerQuery) {
  15326. if (!token._startTimeQuery || !token._endTimeQuery) {
  15327. return -1;
  15328. }
  15329. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  15330. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  15331. result = timeEnd - timeStart;
  15332. this._deleteTimeQuery(token._startTimeQuery);
  15333. this._deleteTimeQuery(token._endTimeQuery);
  15334. token._startTimeQuery = null;
  15335. token._endTimeQuery = null;
  15336. }
  15337. else {
  15338. if (!token._timeElapsedQuery) {
  15339. return -1;
  15340. }
  15341. result = this._getTimeQueryResult(token._timeElapsedQuery);
  15342. this._deleteTimeQuery(token._timeElapsedQuery);
  15343. token._timeElapsedQuery = null;
  15344. token._timeElapsedQueryEnded = false;
  15345. this._currentNonTimestampToken = null;
  15346. }
  15347. return result;
  15348. }
  15349. return -1;
  15350. };
  15351. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  15352. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  15353. };
  15354. // Transform feedback
  15355. Engine.prototype.createTransformFeedback = function () {
  15356. return this._gl.createTransformFeedback();
  15357. };
  15358. Engine.prototype.deleteTransformFeedback = function (value) {
  15359. this._gl.deleteTransformFeedback(value);
  15360. };
  15361. Engine.prototype.bindTransformFeedback = function (value) {
  15362. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  15363. };
  15364. Engine.prototype.beginTransformFeedback = function (usePoints) {
  15365. if (usePoints === void 0) { usePoints = true; }
  15366. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  15367. };
  15368. Engine.prototype.endTransformFeedback = function () {
  15369. this._gl.endTransformFeedback();
  15370. };
  15371. Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  15372. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  15373. };
  15374. Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  15375. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  15376. };
  15377. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  15378. var _this = this;
  15379. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  15380. this._activeRequests.push(request);
  15381. request.onCompleteObservable.add(function (request) {
  15382. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  15383. });
  15384. return request;
  15385. };
  15386. /** @ignore */
  15387. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  15388. var _this = this;
  15389. return new Promise(function (resolve, reject) {
  15390. _this._loadFile(url, function (data) {
  15391. resolve(data);
  15392. }, undefined, database, useArrayBuffer, function (request, exception) {
  15393. reject(exception);
  15394. });
  15395. });
  15396. };
  15397. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  15398. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  15399. var onload = function (data) {
  15400. loadedFiles[index] = data;
  15401. loadedFiles._internalCount++;
  15402. if (loadedFiles._internalCount === 6) {
  15403. onfinish(loadedFiles);
  15404. }
  15405. };
  15406. var onerror = function (request, exception) {
  15407. if (onErrorCallBack && request) {
  15408. onErrorCallBack(request.status + " " + request.statusText, exception);
  15409. }
  15410. };
  15411. this._loadFile(url, onload, undefined, undefined, true, onerror);
  15412. };
  15413. Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
  15414. if (onError === void 0) { onError = null; }
  15415. var loadedFiles = [];
  15416. loadedFiles._internalCount = 0;
  15417. for (var index = 0; index < 6; index++) {
  15418. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  15419. }
  15420. };
  15421. // Statics
  15422. Engine.isSupported = function () {
  15423. try {
  15424. var tempcanvas = document.createElement("canvas");
  15425. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  15426. return gl != null && !!window.WebGLRenderingContext;
  15427. }
  15428. catch (e) {
  15429. return false;
  15430. }
  15431. };
  15432. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  15433. Engine.ExceptionList = [
  15434. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  15435. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  15436. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  15437. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  15438. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  15439. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  15440. ];
  15441. Engine.Instances = new Array();
  15442. // Const statics
  15443. Engine._ALPHA_DISABLE = 0;
  15444. Engine._ALPHA_ADD = 1;
  15445. Engine._ALPHA_COMBINE = 2;
  15446. Engine._ALPHA_SUBTRACT = 3;
  15447. Engine._ALPHA_MULTIPLY = 4;
  15448. Engine._ALPHA_MAXIMIZED = 5;
  15449. Engine._ALPHA_ONEONE = 6;
  15450. Engine._ALPHA_PREMULTIPLIED = 7;
  15451. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  15452. Engine._ALPHA_INTERPOLATE = 9;
  15453. Engine._ALPHA_SCREENMODE = 10;
  15454. Engine._DELAYLOADSTATE_NONE = 0;
  15455. Engine._DELAYLOADSTATE_LOADED = 1;
  15456. Engine._DELAYLOADSTATE_LOADING = 2;
  15457. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  15458. Engine._TEXTUREFORMAT_ALPHA = 0;
  15459. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  15460. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  15461. Engine._TEXTUREFORMAT_RGB = 4;
  15462. Engine._TEXTUREFORMAT_RGBA = 5;
  15463. Engine._TEXTUREFORMAT_R32F = 6;
  15464. Engine._TEXTUREFORMAT_RG32F = 7;
  15465. Engine._TEXTUREFORMAT_RGB32F = 8;
  15466. Engine._TEXTUREFORMAT_RGBA32F = 9;
  15467. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  15468. Engine._TEXTURETYPE_FLOAT = 1;
  15469. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  15470. // Depht or Stencil test Constants.
  15471. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  15472. Engine._ALWAYS = 0x0207; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will always pass. i.e. Pixels will be drawn in the order they are drawn.
  15473. Engine._LESS = 0x0201; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value.
  15474. Engine._EQUAL = 0x0202; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value.
  15475. Engine._LEQUAL = 0x0203; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than or equal to the stored value.
  15476. Engine._GREATER = 0x0204; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value.
  15477. Engine._GEQUAL = 0x0206; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than or equal to the stored value.
  15478. Engine._NOTEQUAL = 0x0205; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is not equal to the stored value.
  15479. // Stencil Actions Constants.
  15480. Engine._KEEP = 0x1E00;
  15481. Engine._REPLACE = 0x1E01;
  15482. Engine._INCR = 0x1E02;
  15483. Engine._DECR = 0x1E03;
  15484. Engine._INVERT = 0x150A;
  15485. Engine._INCR_WRAP = 0x8507;
  15486. Engine._DECR_WRAP = 0x8508;
  15487. // Texture rescaling mode
  15488. Engine._SCALEMODE_FLOOR = 1;
  15489. Engine._SCALEMODE_NEAREST = 2;
  15490. Engine._SCALEMODE_CEILING = 3;
  15491. // Updatable statics so stick with vars here
  15492. Engine.CollisionsEpsilon = 0.001;
  15493. Engine.CodeRepository = "src/";
  15494. Engine.ShadersRepository = "src/Shaders/";
  15495. return Engine;
  15496. }());
  15497. BABYLON.Engine = Engine;
  15498. })(BABYLON || (BABYLON = {}));
  15499. //# sourceMappingURL=babylon.engine.js.map
  15500. var BABYLON;
  15501. (function (BABYLON) {
  15502. /**
  15503. * Node is the basic class for all scene objects (Mesh, Light Camera).
  15504. */
  15505. var Node = /** @class */ (function () {
  15506. /**
  15507. * Creates a new Node
  15508. * @param {string} name - the name and id to be given to this node
  15509. * @param {BABYLON.Scene} the scene this node will be added to
  15510. */
  15511. function Node(name, scene) {
  15512. if (scene === void 0) { scene = null; }
  15513. /**
  15514. * Gets or sets a string used to store user defined state for the node
  15515. */
  15516. this.state = "";
  15517. /**
  15518. * Gets or sets an object used to store user defined information for the node
  15519. */
  15520. this.metadata = null;
  15521. /**
  15522. * Gets or sets a boolean used to define if the node must be serialized
  15523. */
  15524. this.doNotSerialize = false;
  15525. /** @ignore */
  15526. this._isDisposed = false;
  15527. /**
  15528. * Gets a list of {BABYLON.Animation} associated with the node
  15529. */
  15530. this.animations = new Array();
  15531. this._ranges = {};
  15532. this._isEnabled = true;
  15533. this._isReady = true;
  15534. /** @ignore */
  15535. this._currentRenderId = -1;
  15536. this._parentRenderId = -1;
  15537. this._animationPropertiesOverride = null;
  15538. /**
  15539. * An event triggered when the mesh is disposed
  15540. * @type {BABYLON.Observable}
  15541. */
  15542. this.onDisposeObservable = new BABYLON.Observable();
  15543. // Behaviors
  15544. this._behaviors = new Array();
  15545. this.name = name;
  15546. this.id = name;
  15547. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  15548. this.uniqueId = this._scene.getUniqueId();
  15549. this._initCache();
  15550. }
  15551. /**
  15552. * Gets a boolean indicating if the node has been disposed
  15553. * @returns true if the node was disposed
  15554. */
  15555. Node.prototype.isDisposed = function () {
  15556. return this._isDisposed;
  15557. };
  15558. Object.defineProperty(Node.prototype, "parent", {
  15559. get: function () {
  15560. return this._parentNode;
  15561. },
  15562. /**
  15563. * Gets or sets the parent of the node
  15564. */
  15565. set: function (parent) {
  15566. if (this._parentNode === parent) {
  15567. return;
  15568. }
  15569. // Remove self from list of children of parent
  15570. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  15571. var index = this._parentNode._children.indexOf(this);
  15572. if (index !== -1) {
  15573. this._parentNode._children.splice(index, 1);
  15574. }
  15575. }
  15576. // Store new parent
  15577. this._parentNode = parent;
  15578. // Add as child to new parent
  15579. if (this._parentNode) {
  15580. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  15581. this._parentNode._children = new Array();
  15582. }
  15583. this._parentNode._children.push(this);
  15584. }
  15585. },
  15586. enumerable: true,
  15587. configurable: true
  15588. });
  15589. Object.defineProperty(Node.prototype, "animationPropertiesOverride", {
  15590. /**
  15591. * Gets or sets the animation properties override
  15592. */
  15593. get: function () {
  15594. return this._animationPropertiesOverride;
  15595. },
  15596. set: function (value) {
  15597. this._animationPropertiesOverride = value;
  15598. },
  15599. enumerable: true,
  15600. configurable: true
  15601. });
  15602. /**
  15603. * Gets a string idenfifying the name of the class
  15604. * @returns "Node" string
  15605. */
  15606. Node.prototype.getClassName = function () {
  15607. return "Node";
  15608. };
  15609. Object.defineProperty(Node.prototype, "onDispose", {
  15610. /**
  15611. * Sets a callback that will be raised when the node will be disposed
  15612. */
  15613. set: function (callback) {
  15614. if (this._onDisposeObserver) {
  15615. this.onDisposeObservable.remove(this._onDisposeObserver);
  15616. }
  15617. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  15618. },
  15619. enumerable: true,
  15620. configurable: true
  15621. });
  15622. /**
  15623. * Gets the scene of the node
  15624. * @returns a {BABYLON.Scene}
  15625. */
  15626. Node.prototype.getScene = function () {
  15627. return this._scene;
  15628. };
  15629. /**
  15630. * Gets the engine of the node
  15631. * @returns a {BABYLON.Engine}
  15632. */
  15633. Node.prototype.getEngine = function () {
  15634. return this._scene.getEngine();
  15635. };
  15636. /**
  15637. * Attach a behavior to the node
  15638. * @see http://doc.babylonjs.com/features/behaviour
  15639. * @param behavior defines the behavior to attach
  15640. * @returns the current Node
  15641. */
  15642. Node.prototype.addBehavior = function (behavior) {
  15643. var _this = this;
  15644. var index = this._behaviors.indexOf(behavior);
  15645. if (index !== -1) {
  15646. return this;
  15647. }
  15648. behavior.init();
  15649. if (this._scene.isLoading) {
  15650. // We defer the attach when the scene will be loaded
  15651. var observer = this._scene.onDataLoadedObservable.add(function () {
  15652. behavior.attach(_this);
  15653. setTimeout(function () {
  15654. // Need to use a timeout to avoid removing an observer while iterating the list of observers
  15655. _this._scene.onDataLoadedObservable.remove(observer);
  15656. }, 0);
  15657. });
  15658. }
  15659. else {
  15660. behavior.attach(this);
  15661. }
  15662. this._behaviors.push(behavior);
  15663. return this;
  15664. };
  15665. /**
  15666. * Remove an attached behavior
  15667. * @see http://doc.babylonjs.com/features/behaviour
  15668. * @param behavior defines the behavior to attach
  15669. * @returns the current Node
  15670. */
  15671. Node.prototype.removeBehavior = function (behavior) {
  15672. var index = this._behaviors.indexOf(behavior);
  15673. if (index === -1) {
  15674. return this;
  15675. }
  15676. this._behaviors[index].detach();
  15677. this._behaviors.splice(index, 1);
  15678. return this;
  15679. };
  15680. Object.defineProperty(Node.prototype, "behaviors", {
  15681. /**
  15682. * Gets the list of attached behaviors
  15683. * @see http://doc.babylonjs.com/features/behaviour
  15684. */
  15685. get: function () {
  15686. return this._behaviors;
  15687. },
  15688. enumerable: true,
  15689. configurable: true
  15690. });
  15691. /**
  15692. * Gets an attached behavior by name
  15693. * @param name defines the name of the behavior to look for
  15694. * @see http://doc.babylonjs.com/features/behaviour
  15695. * @returns null if behavior was not found else the requested behavior
  15696. */
  15697. Node.prototype.getBehaviorByName = function (name) {
  15698. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  15699. var behavior = _a[_i];
  15700. if (behavior.name === name) {
  15701. return behavior;
  15702. }
  15703. }
  15704. return null;
  15705. };
  15706. /**
  15707. * Returns the world matrix of the node
  15708. * @returns a matrix containing the node's world matrix
  15709. */
  15710. Node.prototype.getWorldMatrix = function () {
  15711. return BABYLON.Matrix.Identity();
  15712. };
  15713. // override it in derived class if you add new variables to the cache
  15714. // and call the parent class method
  15715. /** @ignore */
  15716. Node.prototype._initCache = function () {
  15717. this._cache = {};
  15718. this._cache.parent = undefined;
  15719. };
  15720. /** @ignore */
  15721. Node.prototype.updateCache = function (force) {
  15722. if (!force && this.isSynchronized())
  15723. return;
  15724. this._cache.parent = this.parent;
  15725. this._updateCache();
  15726. };
  15727. // override it in derived class if you add new variables to the cache
  15728. // and call the parent class method if !ignoreParentClass
  15729. /** @ignore */
  15730. Node.prototype._updateCache = function (ignoreParentClass) {
  15731. };
  15732. // override it in derived class if you add new variables to the cache
  15733. /** @ignore */
  15734. Node.prototype._isSynchronized = function () {
  15735. return true;
  15736. };
  15737. /** @ignore */
  15738. Node.prototype._markSyncedWithParent = function () {
  15739. if (this.parent) {
  15740. this._parentRenderId = this.parent._currentRenderId;
  15741. }
  15742. };
  15743. /** @ignore */
  15744. Node.prototype.isSynchronizedWithParent = function () {
  15745. if (!this.parent) {
  15746. return true;
  15747. }
  15748. if (this._parentRenderId !== this.parent._currentRenderId) {
  15749. return false;
  15750. }
  15751. return this.parent.isSynchronized();
  15752. };
  15753. /** @ignore */
  15754. Node.prototype.isSynchronized = function (updateCache) {
  15755. var check = this.hasNewParent();
  15756. check = check || !this.isSynchronizedWithParent();
  15757. check = check || !this._isSynchronized();
  15758. if (updateCache)
  15759. this.updateCache(true);
  15760. return !check;
  15761. };
  15762. /** @ignore */
  15763. Node.prototype.hasNewParent = function (update) {
  15764. if (this._cache.parent === this.parent)
  15765. return false;
  15766. if (update)
  15767. this._cache.parent = this.parent;
  15768. return true;
  15769. };
  15770. /**
  15771. * Is this node ready to be used/rendered
  15772. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  15773. * @return true if the node is ready
  15774. */
  15775. Node.prototype.isReady = function (completeCheck) {
  15776. if (completeCheck === void 0) { completeCheck = false; }
  15777. return this._isReady;
  15778. };
  15779. /**
  15780. * Is this node enabled?
  15781. * If the node has a parent, all ancestors will be checked and false will be returned if any are false (not enabled), otherwise will return true
  15782. * @param checkAncestors indicates if this method should check the ancestors. The default is to check the ancestors. If set to false, the method will return the value of this node without checking ancestors
  15783. * @return whether this node (and its parent) is enabled
  15784. * @see setEnabled
  15785. */
  15786. Node.prototype.isEnabled = function (checkAncestors) {
  15787. if (checkAncestors === void 0) { checkAncestors = true; }
  15788. if (checkAncestors === false) {
  15789. return this._isEnabled;
  15790. }
  15791. if (this._isEnabled === false) {
  15792. return false;
  15793. }
  15794. if (this.parent !== undefined && this.parent !== null) {
  15795. return this.parent.isEnabled(checkAncestors);
  15796. }
  15797. return true;
  15798. };
  15799. /**
  15800. * Set the enabled state of this node
  15801. * @param value defines the new enabled state
  15802. * @see isEnabled
  15803. */
  15804. Node.prototype.setEnabled = function (value) {
  15805. this._isEnabled = value;
  15806. };
  15807. /**
  15808. * Is this node a descendant of the given node?
  15809. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  15810. * @param ancestor defines the parent node to inspect
  15811. * @see parent
  15812. * @returns a boolean indicating if this node is a descendant of the given node
  15813. */
  15814. Node.prototype.isDescendantOf = function (ancestor) {
  15815. if (this.parent) {
  15816. if (this.parent === ancestor) {
  15817. return true;
  15818. }
  15819. return this.parent.isDescendantOf(ancestor);
  15820. }
  15821. return false;
  15822. };
  15823. /** @ignore */
  15824. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  15825. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  15826. if (!this._children) {
  15827. return;
  15828. }
  15829. for (var index = 0; index < this._children.length; index++) {
  15830. var item = this._children[index];
  15831. if (!predicate || predicate(item)) {
  15832. results.push(item);
  15833. }
  15834. if (!directDescendantsOnly) {
  15835. item._getDescendants(results, false, predicate);
  15836. }
  15837. }
  15838. };
  15839. /**
  15840. * Will return all nodes that have this node as ascendant
  15841. * @param directDescendantsOnly defines if true only direct descendants of 'this' will be considered, if false direct and also indirect (children of children, an so on in a recursive manner) descendants of 'this' will be considered
  15842. * @param predicate defines an optional predicate that will be called on every evaluated child, the predicate must return true for a given child to be part of the result, otherwise it will be ignored
  15843. * @return all children nodes of all types
  15844. */
  15845. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  15846. var results = new Array();
  15847. this._getDescendants(results, directDescendantsOnly, predicate);
  15848. return results;
  15849. };
  15850. /**
  15851. * Get all child-meshes of this node
  15852. * @param directDescendantsOnly defines if true only direct descendants of 'this' will be considered, if false direct and also indirect (children of children, an so on in a recursive manner) descendants of 'this' will be considered
  15853. * @param predicate defines an optional predicate that will be called on every evaluated child, the predicate must return true for a given child to be part of the result, otherwise it will be ignored
  15854. * @returns an array of {BABYLON.AbstractMesh}
  15855. */
  15856. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  15857. var results = [];
  15858. this._getDescendants(results, directDescendantsOnly, function (node) {
  15859. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  15860. });
  15861. return results;
  15862. };
  15863. /**
  15864. * Get all child-transformNodes of this node
  15865. * @param directDescendantsOnly defines if true only direct descendants of 'this' will be considered, if false direct and also indirect (children of children, an so on in a recursive manner) descendants of 'this' will be considered
  15866. * @param predicate defines an optional predicate that will be called on every evaluated child, the predicate must return true for a given child to be part of the result, otherwise it will be ignored
  15867. * @returns an array of {BABYLON.TransformNode}
  15868. */
  15869. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  15870. var results = [];
  15871. this._getDescendants(results, directDescendantsOnly, function (node) {
  15872. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  15873. });
  15874. return results;
  15875. };
  15876. /**
  15877. * Get all direct children of this node
  15878. * @param predicate defines an optional predicate that will be called on every evaluated child, the predicate must return true for a given child to be part of the result, otherwise it will be ignored
  15879. * @returns an array of {BABYLON.Node}
  15880. */
  15881. Node.prototype.getChildren = function (predicate) {
  15882. return this.getDescendants(true, predicate);
  15883. };
  15884. /** @ignore */
  15885. Node.prototype._setReady = function (state) {
  15886. if (state === this._isReady) {
  15887. return;
  15888. }
  15889. if (!state) {
  15890. this._isReady = false;
  15891. return;
  15892. }
  15893. this._isReady = true;
  15894. if (this.onReady) {
  15895. this.onReady(this);
  15896. }
  15897. };
  15898. /**
  15899. * Get an animation by name
  15900. * @param name defines the name of the animation to look for
  15901. * @returns null if not found else the requested animation
  15902. */
  15903. Node.prototype.getAnimationByName = function (name) {
  15904. for (var i = 0; i < this.animations.length; i++) {
  15905. var animation = this.animations[i];
  15906. if (animation.name === name) {
  15907. return animation;
  15908. }
  15909. }
  15910. return null;
  15911. };
  15912. /**
  15913. * Creates an animation range for this node
  15914. * @param name defines the name of the range
  15915. * @param from defines the starting key
  15916. * @param to defines the end key
  15917. */
  15918. Node.prototype.createAnimationRange = function (name, from, to) {
  15919. // check name not already in use
  15920. if (!this._ranges[name]) {
  15921. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  15922. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  15923. if (this.animations[i]) {
  15924. this.animations[i].createRange(name, from, to);
  15925. }
  15926. }
  15927. }
  15928. };
  15929. /**
  15930. * Delete a specific animation range
  15931. * @param name defines the name of the range to delete
  15932. * @param deleteFrames defines if animation frames from the range must be deleted as well
  15933. */
  15934. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  15935. if (deleteFrames === void 0) { deleteFrames = true; }
  15936. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  15937. if (this.animations[i]) {
  15938. this.animations[i].deleteRange(name, deleteFrames);
  15939. }
  15940. }
  15941. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  15942. };
  15943. /**
  15944. * Get an animation range by name
  15945. * @param name defines the name of the animation range to look for
  15946. * @returns null if not found else the requested animation range
  15947. */
  15948. Node.prototype.getAnimationRange = function (name) {
  15949. return this._ranges[name];
  15950. };
  15951. /**
  15952. * Will start the animation sequence
  15953. * @param name defines the range frames for animation sequence
  15954. * @param loop defines if the animation should loop (false by default)
  15955. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  15956. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  15957. * @returns the object created for this animation. If range does not exist, it will return null
  15958. */
  15959. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  15960. var range = this.getAnimationRange(name);
  15961. if (!range) {
  15962. return null;
  15963. }
  15964. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  15965. };
  15966. /**
  15967. * Serialize animation ranges into a JSON compatible object
  15968. * @returns serialization object
  15969. */
  15970. Node.prototype.serializeAnimationRanges = function () {
  15971. var serializationRanges = [];
  15972. for (var name in this._ranges) {
  15973. var localRange = this._ranges[name];
  15974. if (!localRange) {
  15975. continue;
  15976. }
  15977. var range = {};
  15978. range.name = name;
  15979. range.from = localRange.from;
  15980. range.to = localRange.to;
  15981. serializationRanges.push(range);
  15982. }
  15983. return serializationRanges;
  15984. };
  15985. /**
  15986. * Computes the world matrix of the node
  15987. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  15988. * @returns the world matrix
  15989. */
  15990. Node.prototype.computeWorldMatrix = function (force) {
  15991. return BABYLON.Matrix.Identity();
  15992. };
  15993. /**
  15994. * Releases resources associated with this node.
  15995. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  15996. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  15997. */
  15998. Node.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  15999. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  16000. if (!doNotRecurse) {
  16001. var nodes = this.getDescendants(true);
  16002. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  16003. var node = nodes_1[_i];
  16004. node.dispose(doNotRecurse, disposeMaterialAndTextures);
  16005. }
  16006. }
  16007. else {
  16008. var transformNodes = this.getChildTransformNodes(true);
  16009. for (var _a = 0, transformNodes_1 = transformNodes; _a < transformNodes_1.length; _a++) {
  16010. var transformNode = transformNodes_1[_a];
  16011. transformNode.parent = null;
  16012. transformNode.computeWorldMatrix(true);
  16013. }
  16014. }
  16015. this.parent = null;
  16016. // Callback
  16017. this.onDisposeObservable.notifyObservers(this);
  16018. this.onDisposeObservable.clear();
  16019. // Behaviors
  16020. for (var _b = 0, _c = this._behaviors; _b < _c.length; _b++) {
  16021. var behavior = _c[_b];
  16022. behavior.detach();
  16023. }
  16024. this._behaviors = [];
  16025. this._isDisposed = true;
  16026. };
  16027. /**
  16028. * Parse animation range data from a serialization object and store them into a given node
  16029. * @param node defines where to store the animation ranges
  16030. * @param parsedNode defines the serialization object to read data from
  16031. * @param scene defines the hosting scene
  16032. */
  16033. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  16034. if (parsedNode.ranges) {
  16035. for (var index = 0; index < parsedNode.ranges.length; index++) {
  16036. var data = parsedNode.ranges[index];
  16037. node.createAnimationRange(data.name, data.from, data.to);
  16038. }
  16039. }
  16040. };
  16041. __decorate([
  16042. BABYLON.serialize()
  16043. ], Node.prototype, "name", void 0);
  16044. __decorate([
  16045. BABYLON.serialize()
  16046. ], Node.prototype, "id", void 0);
  16047. __decorate([
  16048. BABYLON.serialize()
  16049. ], Node.prototype, "uniqueId", void 0);
  16050. __decorate([
  16051. BABYLON.serialize()
  16052. ], Node.prototype, "state", void 0);
  16053. __decorate([
  16054. BABYLON.serialize()
  16055. ], Node.prototype, "metadata", void 0);
  16056. return Node;
  16057. }());
  16058. BABYLON.Node = Node;
  16059. })(BABYLON || (BABYLON = {}));
  16060. //# sourceMappingURL=babylon.node.js.map
  16061. var BABYLON;
  16062. (function (BABYLON) {
  16063. var BoundingSphere = /** @class */ (function () {
  16064. function BoundingSphere(minimum, maximum) {
  16065. this.minimum = minimum;
  16066. this.maximum = maximum;
  16067. this._tempRadiusVector = BABYLON.Vector3.Zero();
  16068. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  16069. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  16070. this.radius = distance * 0.5;
  16071. this.centerWorld = BABYLON.Vector3.Zero();
  16072. this._update(BABYLON.Matrix.Identity());
  16073. }
  16074. // Methods
  16075. BoundingSphere.prototype._update = function (world) {
  16076. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  16077. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  16078. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  16079. };
  16080. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  16081. for (var i = 0; i < 6; i++) {
  16082. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  16083. return false;
  16084. }
  16085. return true;
  16086. };
  16087. BoundingSphere.prototype.intersectsPoint = function (point) {
  16088. var x = this.centerWorld.x - point.x;
  16089. var y = this.centerWorld.y - point.y;
  16090. var z = this.centerWorld.z - point.z;
  16091. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  16092. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  16093. return false;
  16094. return true;
  16095. };
  16096. // Statics
  16097. BoundingSphere.Intersects = function (sphere0, sphere1) {
  16098. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  16099. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  16100. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  16101. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  16102. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  16103. return false;
  16104. return true;
  16105. };
  16106. return BoundingSphere;
  16107. }());
  16108. BABYLON.BoundingSphere = BoundingSphere;
  16109. })(BABYLON || (BABYLON = {}));
  16110. //# sourceMappingURL=babylon.boundingSphere.js.map
  16111. var BABYLON;
  16112. (function (BABYLON) {
  16113. var BoundingBox = /** @class */ (function () {
  16114. function BoundingBox(minimum, maximum) {
  16115. this.minimum = minimum;
  16116. this.maximum = maximum;
  16117. this.vectors = new Array();
  16118. this.vectorsWorld = new Array();
  16119. // Bounding vectors
  16120. this.vectors.push(this.minimum.clone());
  16121. this.vectors.push(this.maximum.clone());
  16122. this.vectors.push(this.minimum.clone());
  16123. this.vectors[2].x = this.maximum.x;
  16124. this.vectors.push(this.minimum.clone());
  16125. this.vectors[3].y = this.maximum.y;
  16126. this.vectors.push(this.minimum.clone());
  16127. this.vectors[4].z = this.maximum.z;
  16128. this.vectors.push(this.maximum.clone());
  16129. this.vectors[5].z = this.minimum.z;
  16130. this.vectors.push(this.maximum.clone());
  16131. this.vectors[6].x = this.minimum.x;
  16132. this.vectors.push(this.maximum.clone());
  16133. this.vectors[7].y = this.minimum.y;
  16134. // OBB
  16135. this.center = this.maximum.add(this.minimum).scale(0.5);
  16136. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  16137. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  16138. // World
  16139. for (var index = 0; index < this.vectors.length; index++) {
  16140. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  16141. }
  16142. this.minimumWorld = BABYLON.Vector3.Zero();
  16143. this.maximumWorld = BABYLON.Vector3.Zero();
  16144. this.centerWorld = BABYLON.Vector3.Zero();
  16145. this.extendSizeWorld = BABYLON.Vector3.Zero();
  16146. this._update(BABYLON.Matrix.Identity());
  16147. }
  16148. // Methods
  16149. BoundingBox.prototype.getWorldMatrix = function () {
  16150. return this._worldMatrix;
  16151. };
  16152. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  16153. this._worldMatrix.copyFrom(matrix);
  16154. return this;
  16155. };
  16156. BoundingBox.prototype._update = function (world) {
  16157. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  16158. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  16159. for (var index = 0; index < this.vectors.length; index++) {
  16160. var v = this.vectorsWorld[index];
  16161. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  16162. if (v.x < this.minimumWorld.x)
  16163. this.minimumWorld.x = v.x;
  16164. if (v.y < this.minimumWorld.y)
  16165. this.minimumWorld.y = v.y;
  16166. if (v.z < this.minimumWorld.z)
  16167. this.minimumWorld.z = v.z;
  16168. if (v.x > this.maximumWorld.x)
  16169. this.maximumWorld.x = v.x;
  16170. if (v.y > this.maximumWorld.y)
  16171. this.maximumWorld.y = v.y;
  16172. if (v.z > this.maximumWorld.z)
  16173. this.maximumWorld.z = v.z;
  16174. }
  16175. // Extend
  16176. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  16177. this.extendSizeWorld.scaleInPlace(0.5);
  16178. // OBB
  16179. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  16180. this.centerWorld.scaleInPlace(0.5);
  16181. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  16182. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  16183. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  16184. this._worldMatrix = world;
  16185. };
  16186. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  16187. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  16188. };
  16189. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  16190. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  16191. };
  16192. BoundingBox.prototype.intersectsPoint = function (point) {
  16193. var delta = -BABYLON.Epsilon;
  16194. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  16195. return false;
  16196. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  16197. return false;
  16198. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  16199. return false;
  16200. return true;
  16201. };
  16202. BoundingBox.prototype.intersectsSphere = function (sphere) {
  16203. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  16204. };
  16205. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  16206. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  16207. return false;
  16208. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  16209. return false;
  16210. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  16211. return false;
  16212. return true;
  16213. };
  16214. // Statics
  16215. BoundingBox.Intersects = function (box0, box1) {
  16216. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  16217. return false;
  16218. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  16219. return false;
  16220. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  16221. return false;
  16222. return true;
  16223. };
  16224. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  16225. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  16226. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  16227. return (num <= (sphereRadius * sphereRadius));
  16228. };
  16229. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  16230. for (var p = 0; p < 6; p++) {
  16231. for (var i = 0; i < 8; i++) {
  16232. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  16233. return false;
  16234. }
  16235. }
  16236. }
  16237. return true;
  16238. };
  16239. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  16240. for (var p = 0; p < 6; p++) {
  16241. var inCount = 8;
  16242. for (var i = 0; i < 8; i++) {
  16243. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  16244. --inCount;
  16245. }
  16246. else {
  16247. break;
  16248. }
  16249. }
  16250. if (inCount === 0)
  16251. return false;
  16252. }
  16253. return true;
  16254. };
  16255. return BoundingBox;
  16256. }());
  16257. BABYLON.BoundingBox = BoundingBox;
  16258. })(BABYLON || (BABYLON = {}));
  16259. //# sourceMappingURL=babylon.boundingBox.js.map
  16260. var BABYLON;
  16261. (function (BABYLON) {
  16262. var computeBoxExtents = function (axis, box) {
  16263. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  16264. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  16265. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  16266. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  16267. var r = r0 + r1 + r2;
  16268. return {
  16269. min: p - r,
  16270. max: p + r
  16271. };
  16272. };
  16273. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  16274. var axisOverlap = function (axis, box0, box1) {
  16275. var result0 = computeBoxExtents(axis, box0);
  16276. var result1 = computeBoxExtents(axis, box1);
  16277. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  16278. };
  16279. var BoundingInfo = /** @class */ (function () {
  16280. function BoundingInfo(minimum, maximum) {
  16281. this.minimum = minimum;
  16282. this.maximum = maximum;
  16283. this._isLocked = false;
  16284. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  16285. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  16286. }
  16287. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  16288. get: function () {
  16289. return this._isLocked;
  16290. },
  16291. set: function (value) {
  16292. this._isLocked = value;
  16293. },
  16294. enumerable: true,
  16295. configurable: true
  16296. });
  16297. // Methods
  16298. BoundingInfo.prototype.update = function (world) {
  16299. if (this._isLocked) {
  16300. return;
  16301. }
  16302. this.boundingBox._update(world);
  16303. this.boundingSphere._update(world);
  16304. };
  16305. /**
  16306. * Recreate the bounding info to be centered around a specific point given a specific extend.
  16307. * @param center New center of the bounding info
  16308. * @param extend New extend of the bounding info
  16309. */
  16310. BoundingInfo.prototype.centerOn = function (center, extend) {
  16311. this.minimum = center.subtract(extend);
  16312. this.maximum = center.add(extend);
  16313. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  16314. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  16315. return this;
  16316. };
  16317. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  16318. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  16319. return false;
  16320. return this.boundingBox.isInFrustum(frustumPlanes);
  16321. };
  16322. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  16323. /**
  16324. * Gets the world distance between the min and max points of the bounding box
  16325. */
  16326. get: function () {
  16327. var boundingBox = this.boundingBox;
  16328. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  16329. return size.length();
  16330. },
  16331. enumerable: true,
  16332. configurable: true
  16333. });
  16334. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  16335. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  16336. };
  16337. BoundingInfo.prototype._checkCollision = function (collider) {
  16338. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  16339. };
  16340. BoundingInfo.prototype.intersectsPoint = function (point) {
  16341. if (!this.boundingSphere.centerWorld) {
  16342. return false;
  16343. }
  16344. if (!this.boundingSphere.intersectsPoint(point)) {
  16345. return false;
  16346. }
  16347. if (!this.boundingBox.intersectsPoint(point)) {
  16348. return false;
  16349. }
  16350. return true;
  16351. };
  16352. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  16353. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  16354. return false;
  16355. }
  16356. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  16357. return false;
  16358. }
  16359. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  16360. return false;
  16361. }
  16362. if (!precise) {
  16363. return true;
  16364. }
  16365. var box0 = this.boundingBox;
  16366. var box1 = boundingInfo.boundingBox;
  16367. if (!axisOverlap(box0.directions[0], box0, box1))
  16368. return false;
  16369. if (!axisOverlap(box0.directions[1], box0, box1))
  16370. return false;
  16371. if (!axisOverlap(box0.directions[2], box0, box1))
  16372. return false;
  16373. if (!axisOverlap(box1.directions[0], box0, box1))
  16374. return false;
  16375. if (!axisOverlap(box1.directions[1], box0, box1))
  16376. return false;
  16377. if (!axisOverlap(box1.directions[2], box0, box1))
  16378. return false;
  16379. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  16380. return false;
  16381. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  16382. return false;
  16383. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  16384. return false;
  16385. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  16386. return false;
  16387. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  16388. return false;
  16389. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  16390. return false;
  16391. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  16392. return false;
  16393. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  16394. return false;
  16395. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  16396. return false;
  16397. return true;
  16398. };
  16399. return BoundingInfo;
  16400. }());
  16401. BABYLON.BoundingInfo = BoundingInfo;
  16402. })(BABYLON || (BABYLON = {}));
  16403. //# sourceMappingURL=babylon.boundingInfo.js.map
  16404. var BABYLON;
  16405. (function (BABYLON) {
  16406. var TransformNode = /** @class */ (function (_super) {
  16407. __extends(TransformNode, _super);
  16408. function TransformNode(name, scene, isPure) {
  16409. if (scene === void 0) { scene = null; }
  16410. if (isPure === void 0) { isPure = true; }
  16411. var _this = _super.call(this, name, scene) || this;
  16412. // Properties
  16413. _this._rotation = BABYLON.Vector3.Zero();
  16414. _this._scaling = BABYLON.Vector3.One();
  16415. _this._isDirty = false;
  16416. _this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_NONE;
  16417. _this.scalingDeterminant = 1;
  16418. _this.infiniteDistance = false;
  16419. _this.position = BABYLON.Vector3.Zero();
  16420. _this._localWorld = BABYLON.Matrix.Zero();
  16421. _this._worldMatrix = BABYLON.Matrix.Zero();
  16422. _this._worldMatrixDeterminant = 0;
  16423. _this._absolutePosition = BABYLON.Vector3.Zero();
  16424. _this._pivotMatrix = BABYLON.Matrix.Identity();
  16425. _this._postMultiplyPivotMatrix = false;
  16426. _this._isWorldMatrixFrozen = false;
  16427. /**
  16428. * An event triggered after the world matrix is updated
  16429. * @type {BABYLON.Observable}
  16430. */
  16431. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  16432. _this._nonUniformScaling = false;
  16433. if (isPure) {
  16434. _this.getScene().addTransformNode(_this);
  16435. }
  16436. return _this;
  16437. }
  16438. /**
  16439. * Gets a string idenfifying the name of the class
  16440. * @returns "TransformNode" string
  16441. */
  16442. TransformNode.prototype.getClassName = function () {
  16443. return "TransformNode";
  16444. };
  16445. Object.defineProperty(TransformNode.prototype, "rotation", {
  16446. /**
  16447. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  16448. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  16449. * Default : (0.0, 0.0, 0.0)
  16450. */
  16451. get: function () {
  16452. return this._rotation;
  16453. },
  16454. set: function (newRotation) {
  16455. this._rotation = newRotation;
  16456. },
  16457. enumerable: true,
  16458. configurable: true
  16459. });
  16460. Object.defineProperty(TransformNode.prototype, "scaling", {
  16461. /**
  16462. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  16463. * Default : (1.0, 1.0, 1.0)
  16464. */
  16465. get: function () {
  16466. return this._scaling;
  16467. },
  16468. /**
  16469. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  16470. * Default : (1.0, 1.0, 1.0)
  16471. */
  16472. set: function (newScaling) {
  16473. this._scaling = newScaling;
  16474. },
  16475. enumerable: true,
  16476. configurable: true
  16477. });
  16478. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  16479. /**
  16480. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  16481. * It's null by default.
  16482. * If set, only the rotationQuaternion is then used to compute the mesh rotation and its property `.rotation\ is then ignored and set to (0.0, 0.0, 0.0)
  16483. */
  16484. get: function () {
  16485. return this._rotationQuaternion;
  16486. },
  16487. set: function (quaternion) {
  16488. this._rotationQuaternion = quaternion;
  16489. //reset the rotation vector.
  16490. if (quaternion && this.rotation.length()) {
  16491. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  16492. }
  16493. },
  16494. enumerable: true,
  16495. configurable: true
  16496. });
  16497. /**
  16498. * Returns the latest update of the World matrix
  16499. * Returns a Matrix.
  16500. */
  16501. TransformNode.prototype.getWorldMatrix = function () {
  16502. if (this._currentRenderId !== this.getScene().getRenderId()) {
  16503. this.computeWorldMatrix();
  16504. }
  16505. return this._worldMatrix;
  16506. };
  16507. /**
  16508. * Returns the latest update of the World matrix determinant.
  16509. */
  16510. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  16511. return this._worldMatrixDeterminant;
  16512. };
  16513. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  16514. /**
  16515. * Returns directly the latest state of the mesh World matrix.
  16516. * A Matrix is returned.
  16517. */
  16518. get: function () {
  16519. return this._worldMatrix;
  16520. },
  16521. enumerable: true,
  16522. configurable: true
  16523. });
  16524. /**
  16525. * Copies the paramater passed Matrix into the mesh Pose matrix.
  16526. * Returns the AbstractMesh.
  16527. */
  16528. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  16529. this._poseMatrix.copyFrom(matrix);
  16530. return this;
  16531. };
  16532. /**
  16533. * Returns the mesh Pose matrix.
  16534. * Returned object : Matrix
  16535. */
  16536. TransformNode.prototype.getPoseMatrix = function () {
  16537. return this._poseMatrix;
  16538. };
  16539. TransformNode.prototype._isSynchronized = function () {
  16540. if (this._isDirty) {
  16541. return false;
  16542. }
  16543. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE)
  16544. return false;
  16545. if (this._cache.pivotMatrixUpdated) {
  16546. return false;
  16547. }
  16548. if (this.infiniteDistance) {
  16549. return false;
  16550. }
  16551. if (!this._cache.position.equals(this.position))
  16552. return false;
  16553. if (this.rotationQuaternion) {
  16554. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  16555. return false;
  16556. }
  16557. if (!this._cache.rotation.equals(this.rotation))
  16558. return false;
  16559. if (!this._cache.scaling.equals(this.scaling))
  16560. return false;
  16561. return true;
  16562. };
  16563. TransformNode.prototype._initCache = function () {
  16564. _super.prototype._initCache.call(this);
  16565. this._cache.localMatrixUpdated = false;
  16566. this._cache.position = BABYLON.Vector3.Zero();
  16567. this._cache.scaling = BABYLON.Vector3.Zero();
  16568. this._cache.rotation = BABYLON.Vector3.Zero();
  16569. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  16570. this._cache.billboardMode = -1;
  16571. };
  16572. TransformNode.prototype.markAsDirty = function (property) {
  16573. if (property === "rotation") {
  16574. this.rotationQuaternion = null;
  16575. }
  16576. this._currentRenderId = Number.MAX_VALUE;
  16577. this._isDirty = true;
  16578. return this;
  16579. };
  16580. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  16581. /**
  16582. * Returns the current mesh absolute position.
  16583. * Retuns a Vector3.
  16584. */
  16585. get: function () {
  16586. return this._absolutePosition;
  16587. },
  16588. enumerable: true,
  16589. configurable: true
  16590. });
  16591. /**
  16592. * Sets a new matrix to apply before all other transformation
  16593. * @param matrix defines the transform matrix
  16594. * @returns the current TransformNode
  16595. */
  16596. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  16597. return this.setPivotMatrix(matrix, false);
  16598. };
  16599. /**
  16600. * Sets a new pivot matrix to the current node
  16601. * @param matrix defines the new pivot matrix to use
  16602. * @param postMultiplyPivotMatrix defines if the pivot matrix must be cancelled in the world matrix. When this parameter is set to true (default), the inverse of the pivot matrix is also applied at the end to cancel the transformation effect
  16603. * @returns the current TransformNode
  16604. */
  16605. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  16606. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  16607. this._pivotMatrix = matrix.clone();
  16608. this._cache.pivotMatrixUpdated = true;
  16609. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  16610. if (this._postMultiplyPivotMatrix) {
  16611. if (!this._pivotMatrixInverse) {
  16612. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  16613. }
  16614. else {
  16615. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  16616. }
  16617. }
  16618. return this;
  16619. };
  16620. /**
  16621. * Returns the mesh pivot matrix.
  16622. * Default : Identity.
  16623. * A Matrix is returned.
  16624. */
  16625. TransformNode.prototype.getPivotMatrix = function () {
  16626. return this._pivotMatrix;
  16627. };
  16628. /**
  16629. * Prevents the World matrix to be computed any longer.
  16630. * Returns the AbstractMesh.
  16631. */
  16632. TransformNode.prototype.freezeWorldMatrix = function () {
  16633. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  16634. this.computeWorldMatrix(true);
  16635. this._isWorldMatrixFrozen = true;
  16636. return this;
  16637. };
  16638. /**
  16639. * Allows back the World matrix computation.
  16640. * Returns the AbstractMesh.
  16641. */
  16642. TransformNode.prototype.unfreezeWorldMatrix = function () {
  16643. this._isWorldMatrixFrozen = false;
  16644. this.computeWorldMatrix(true);
  16645. return this;
  16646. };
  16647. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  16648. /**
  16649. * True if the World matrix has been frozen.
  16650. * Returns a boolean.
  16651. */
  16652. get: function () {
  16653. return this._isWorldMatrixFrozen;
  16654. },
  16655. enumerable: true,
  16656. configurable: true
  16657. });
  16658. /**
  16659. * Retuns the mesh absolute position in the World.
  16660. * Returns a Vector3.
  16661. */
  16662. TransformNode.prototype.getAbsolutePosition = function () {
  16663. this.computeWorldMatrix();
  16664. return this._absolutePosition;
  16665. };
  16666. /**
  16667. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  16668. * Returns the AbstractMesh.
  16669. */
  16670. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  16671. if (!absolutePosition) {
  16672. return this;
  16673. }
  16674. var absolutePositionX;
  16675. var absolutePositionY;
  16676. var absolutePositionZ;
  16677. if (absolutePosition.x === undefined) {
  16678. if (arguments.length < 3) {
  16679. return this;
  16680. }
  16681. absolutePositionX = arguments[0];
  16682. absolutePositionY = arguments[1];
  16683. absolutePositionZ = arguments[2];
  16684. }
  16685. else {
  16686. absolutePositionX = absolutePosition.x;
  16687. absolutePositionY = absolutePosition.y;
  16688. absolutePositionZ = absolutePosition.z;
  16689. }
  16690. if (this.parent) {
  16691. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  16692. invertParentWorldMatrix.invert();
  16693. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  16694. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  16695. }
  16696. else {
  16697. this.position.x = absolutePositionX;
  16698. this.position.y = absolutePositionY;
  16699. this.position.z = absolutePositionZ;
  16700. }
  16701. return this;
  16702. };
  16703. /**
  16704. * Sets the mesh position in its local space.
  16705. * Returns the AbstractMesh.
  16706. */
  16707. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  16708. this.computeWorldMatrix();
  16709. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  16710. return this;
  16711. };
  16712. /**
  16713. * Returns the mesh position in the local space from the current World matrix values.
  16714. * Returns a new Vector3.
  16715. */
  16716. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  16717. this.computeWorldMatrix();
  16718. var invLocalWorldMatrix = this._localWorld.clone();
  16719. invLocalWorldMatrix.invert();
  16720. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  16721. };
  16722. /**
  16723. * Translates the mesh along the passed Vector3 in its local space.
  16724. * Returns the AbstractMesh.
  16725. */
  16726. TransformNode.prototype.locallyTranslate = function (vector3) {
  16727. this.computeWorldMatrix(true);
  16728. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  16729. return this;
  16730. };
  16731. /**
  16732. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  16733. * @param targetPoint the position (must be in same space as current mesh) to look at
  16734. * @param yawCor optional yaw (y-axis) correction in radians
  16735. * @param pitchCor optional pitch (x-axis) correction in radians
  16736. * @param rollCor optional roll (z-axis) correction in radians
  16737. * @param space the choosen space of the target
  16738. * @returns the TransformNode.
  16739. */
  16740. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  16741. if (yawCor === void 0) { yawCor = 0; }
  16742. if (pitchCor === void 0) { pitchCor = 0; }
  16743. if (rollCor === void 0) { rollCor = 0; }
  16744. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  16745. var dv = BABYLON.AbstractMesh._lookAtVectorCache;
  16746. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  16747. targetPoint.subtractToRef(pos, dv);
  16748. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  16749. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  16750. var pitch = Math.atan2(dv.y, len);
  16751. if (this.rotationQuaternion) {
  16752. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  16753. }
  16754. else {
  16755. this.rotation.x = pitch + pitchCor;
  16756. this.rotation.y = yaw + yawCor;
  16757. this.rotation.z = rollCor;
  16758. }
  16759. return this;
  16760. };
  16761. /**
  16762. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  16763. * This Vector3 is expressed in the World space.
  16764. */
  16765. TransformNode.prototype.getDirection = function (localAxis) {
  16766. var result = BABYLON.Vector3.Zero();
  16767. this.getDirectionToRef(localAxis, result);
  16768. return result;
  16769. };
  16770. /**
  16771. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  16772. * localAxis is expressed in the mesh local space.
  16773. * result is computed in the Wordl space from the mesh World matrix.
  16774. * Returns the AbstractMesh.
  16775. */
  16776. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  16777. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  16778. return this;
  16779. };
  16780. /**
  16781. * Sets a new pivot point to the current node
  16782. * @param point defines the new pivot point to use
  16783. * @param space defines if the point is in world or local space (local by default)
  16784. * @returns the current TransformNode
  16785. */
  16786. TransformNode.prototype.setPivotPoint = function (point, space) {
  16787. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  16788. if (this.getScene().getRenderId() == 0) {
  16789. this.computeWorldMatrix(true);
  16790. }
  16791. var wm = this.getWorldMatrix();
  16792. if (space == BABYLON.Space.WORLD) {
  16793. var tmat = BABYLON.Tmp.Matrix[0];
  16794. wm.invertToRef(tmat);
  16795. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  16796. }
  16797. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  16798. };
  16799. /**
  16800. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  16801. */
  16802. TransformNode.prototype.getPivotPoint = function () {
  16803. var point = BABYLON.Vector3.Zero();
  16804. this.getPivotPointToRef(point);
  16805. return point;
  16806. };
  16807. /**
  16808. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  16809. * Returns the AbstractMesh.
  16810. */
  16811. TransformNode.prototype.getPivotPointToRef = function (result) {
  16812. result.x = -this._pivotMatrix.m[12];
  16813. result.y = -this._pivotMatrix.m[13];
  16814. result.z = -this._pivotMatrix.m[14];
  16815. return this;
  16816. };
  16817. /**
  16818. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  16819. */
  16820. TransformNode.prototype.getAbsolutePivotPoint = function () {
  16821. var point = BABYLON.Vector3.Zero();
  16822. this.getAbsolutePivotPointToRef(point);
  16823. return point;
  16824. };
  16825. /**
  16826. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  16827. * Returns the AbstractMesh.
  16828. */
  16829. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  16830. result.x = this._pivotMatrix.m[12];
  16831. result.y = this._pivotMatrix.m[13];
  16832. result.z = this._pivotMatrix.m[14];
  16833. this.getPivotPointToRef(result);
  16834. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  16835. return this;
  16836. };
  16837. /**
  16838. * Defines the passed node as the parent of the current node.
  16839. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  16840. * Returns the TransformNode.
  16841. */
  16842. TransformNode.prototype.setParent = function (node) {
  16843. if (node === null) {
  16844. var rotation = BABYLON.Tmp.Quaternion[0];
  16845. var position = BABYLON.Tmp.Vector3[0];
  16846. var scale = BABYLON.Tmp.Vector3[1];
  16847. if (this.parent && this.parent.computeWorldMatrix) {
  16848. this.parent.computeWorldMatrix(true);
  16849. }
  16850. this.computeWorldMatrix(true);
  16851. this.getWorldMatrix().decompose(scale, rotation, position);
  16852. if (this.rotationQuaternion) {
  16853. this.rotationQuaternion.copyFrom(rotation);
  16854. }
  16855. else {
  16856. rotation.toEulerAnglesToRef(this.rotation);
  16857. }
  16858. this.scaling.x = scale.x;
  16859. this.scaling.y = scale.y;
  16860. this.scaling.z = scale.z;
  16861. this.position.x = position.x;
  16862. this.position.y = position.y;
  16863. this.position.z = position.z;
  16864. }
  16865. else {
  16866. var rotation = BABYLON.Tmp.Quaternion[0];
  16867. var position = BABYLON.Tmp.Vector3[0];
  16868. var scale = BABYLON.Tmp.Vector3[1];
  16869. var diffMatrix = BABYLON.Tmp.Matrix[0];
  16870. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  16871. this.computeWorldMatrix(true);
  16872. node.computeWorldMatrix(true);
  16873. node.getWorldMatrix().invertToRef(invParentMatrix);
  16874. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  16875. diffMatrix.decompose(scale, rotation, position);
  16876. if (this.rotationQuaternion) {
  16877. this.rotationQuaternion.copyFrom(rotation);
  16878. }
  16879. else {
  16880. rotation.toEulerAnglesToRef(this.rotation);
  16881. }
  16882. this.position.x = position.x;
  16883. this.position.y = position.y;
  16884. this.position.z = position.z;
  16885. this.scaling.x = scale.x;
  16886. this.scaling.y = scale.y;
  16887. this.scaling.z = scale.z;
  16888. }
  16889. this.parent = node;
  16890. return this;
  16891. };
  16892. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  16893. get: function () {
  16894. return this._nonUniformScaling;
  16895. },
  16896. enumerable: true,
  16897. configurable: true
  16898. });
  16899. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  16900. if (this._nonUniformScaling === value) {
  16901. return false;
  16902. }
  16903. this._nonUniformScaling = true;
  16904. return true;
  16905. };
  16906. /**
  16907. * Attach the current TransformNode to another TransformNode associated with a bone
  16908. * @param bone Bone affecting the TransformNode
  16909. * @param affectedTransformNode TransformNode associated with the bone
  16910. */
  16911. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  16912. this._transformToBoneReferal = affectedTransformNode;
  16913. this.parent = bone;
  16914. if (bone.getWorldMatrix().determinant() < 0) {
  16915. this.scalingDeterminant *= -1;
  16916. }
  16917. return this;
  16918. };
  16919. TransformNode.prototype.detachFromBone = function () {
  16920. if (!this.parent) {
  16921. return this;
  16922. }
  16923. if (this.parent.getWorldMatrix().determinant() < 0) {
  16924. this.scalingDeterminant *= -1;
  16925. }
  16926. this._transformToBoneReferal = null;
  16927. this.parent = null;
  16928. return this;
  16929. };
  16930. /**
  16931. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  16932. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  16933. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  16934. * The passed axis is also normalized.
  16935. * Returns the AbstractMesh.
  16936. */
  16937. TransformNode.prototype.rotate = function (axis, amount, space) {
  16938. axis.normalize();
  16939. if (!this.rotationQuaternion) {
  16940. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  16941. this.rotation = BABYLON.Vector3.Zero();
  16942. }
  16943. var rotationQuaternion;
  16944. if (!space || space === BABYLON.Space.LOCAL) {
  16945. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  16946. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  16947. }
  16948. else {
  16949. if (this.parent) {
  16950. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  16951. invertParentWorldMatrix.invert();
  16952. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  16953. }
  16954. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  16955. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  16956. }
  16957. return this;
  16958. };
  16959. /**
  16960. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  16961. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  16962. * The passed axis is also normalized.
  16963. * Returns the AbstractMesh.
  16964. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  16965. */
  16966. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  16967. axis.normalize();
  16968. if (!this.rotationQuaternion) {
  16969. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  16970. this.rotation.copyFromFloats(0, 0, 0);
  16971. }
  16972. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  16973. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  16974. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  16975. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  16976. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  16977. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  16978. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  16979. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  16980. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  16981. return this;
  16982. };
  16983. /**
  16984. * Translates the mesh along the axis vector for the passed distance in the given space.
  16985. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  16986. * Returns the AbstractMesh.
  16987. */
  16988. TransformNode.prototype.translate = function (axis, distance, space) {
  16989. var displacementVector = axis.scale(distance);
  16990. if (!space || space === BABYLON.Space.LOCAL) {
  16991. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  16992. this.setPositionWithLocalVector(tempV3);
  16993. }
  16994. else {
  16995. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  16996. }
  16997. return this;
  16998. };
  16999. /**
  17000. * Adds a rotation step to the mesh current rotation.
  17001. * x, y, z are Euler angles expressed in radians.
  17002. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  17003. * This means this rotation is made in the mesh local space only.
  17004. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  17005. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  17006. * ```javascript
  17007. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  17008. * ```
  17009. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  17010. * Under the hood, only quaternions are used. So it's a little faster is you use .rotationQuaternion because it doesn't need to translate them back to Euler angles.
  17011. * Returns the AbstractMesh.
  17012. */
  17013. TransformNode.prototype.addRotation = function (x, y, z) {
  17014. var rotationQuaternion;
  17015. if (this.rotationQuaternion) {
  17016. rotationQuaternion = this.rotationQuaternion;
  17017. }
  17018. else {
  17019. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  17020. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  17021. }
  17022. var accumulation = BABYLON.Tmp.Quaternion[0];
  17023. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  17024. rotationQuaternion.multiplyInPlace(accumulation);
  17025. if (!this.rotationQuaternion) {
  17026. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  17027. }
  17028. return this;
  17029. };
  17030. /**
  17031. * Computes the mesh World matrix and returns it.
  17032. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  17033. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  17034. * If the parameter `force`is set to `true`, the actual computation is done.
  17035. * Returns the mesh World Matrix.
  17036. */
  17037. TransformNode.prototype.computeWorldMatrix = function (force) {
  17038. if (this._isWorldMatrixFrozen) {
  17039. return this._worldMatrix;
  17040. }
  17041. if (!force && this.isSynchronized(true)) {
  17042. return this._worldMatrix;
  17043. }
  17044. this._cache.position.copyFrom(this.position);
  17045. this._cache.scaling.copyFrom(this.scaling);
  17046. this._cache.pivotMatrixUpdated = false;
  17047. this._cache.billboardMode = this.billboardMode;
  17048. this._currentRenderId = this.getScene().getRenderId();
  17049. this._isDirty = false;
  17050. // Scaling
  17051. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  17052. // Rotation
  17053. //rotate, if quaternion is set and rotation was used
  17054. if (this.rotationQuaternion) {
  17055. var len = this.rotation.length();
  17056. if (len) {
  17057. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  17058. this.rotation.copyFromFloats(0, 0, 0);
  17059. }
  17060. }
  17061. if (this.rotationQuaternion) {
  17062. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  17063. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  17064. }
  17065. else {
  17066. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  17067. this._cache.rotation.copyFrom(this.rotation);
  17068. }
  17069. // Translation
  17070. var camera = this.getScene().activeCamera;
  17071. if (this.infiniteDistance && !this.parent && camera) {
  17072. var cameraWorldMatrix = camera.getWorldMatrix();
  17073. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  17074. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  17075. }
  17076. else {
  17077. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  17078. }
  17079. // Composing transformations
  17080. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  17081. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  17082. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  17083. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE && camera) {
  17084. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_ALL) !== BABYLON.AbstractMesh.BILLBOARDMODE_ALL) {
  17085. // Need to decompose each rotation here
  17086. var currentPosition = BABYLON.Tmp.Vector3[3];
  17087. if (this.parent && this.parent.getWorldMatrix) {
  17088. if (this._transformToBoneReferal) {
  17089. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  17090. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  17091. }
  17092. else {
  17093. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  17094. }
  17095. }
  17096. else {
  17097. currentPosition.copyFrom(this.position);
  17098. }
  17099. currentPosition.subtractInPlace(camera.globalPosition);
  17100. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  17101. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_X) === BABYLON.AbstractMesh.BILLBOARDMODE_X) {
  17102. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  17103. }
  17104. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Y) === BABYLON.AbstractMesh.BILLBOARDMODE_Y) {
  17105. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  17106. }
  17107. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Z) === BABYLON.AbstractMesh.BILLBOARDMODE_Z) {
  17108. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  17109. }
  17110. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  17111. }
  17112. else {
  17113. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  17114. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  17115. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  17116. }
  17117. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  17118. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  17119. }
  17120. // Local world
  17121. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  17122. // Parent
  17123. if (this.parent && this.parent.getWorldMatrix) {
  17124. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE) {
  17125. if (this._transformToBoneReferal) {
  17126. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  17127. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  17128. }
  17129. else {
  17130. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  17131. }
  17132. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  17133. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  17134. this._worldMatrix.copyFrom(this._localWorld);
  17135. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  17136. }
  17137. else {
  17138. if (this._transformToBoneReferal) {
  17139. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  17140. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  17141. }
  17142. else {
  17143. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  17144. }
  17145. }
  17146. this._markSyncedWithParent();
  17147. }
  17148. else {
  17149. this._worldMatrix.copyFrom(this._localWorld);
  17150. }
  17151. // Post multiply inverse of pivotMatrix
  17152. if (this._postMultiplyPivotMatrix) {
  17153. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  17154. }
  17155. // Normal matrix
  17156. if (this.scaling.isNonUniform) {
  17157. this._updateNonUniformScalingState(true);
  17158. }
  17159. else if (this.parent && this.parent._nonUniformScaling) {
  17160. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  17161. }
  17162. else {
  17163. this._updateNonUniformScalingState(false);
  17164. }
  17165. this._afterComputeWorldMatrix();
  17166. // Absolute position
  17167. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  17168. // Callbacks
  17169. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  17170. if (!this._poseMatrix) {
  17171. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  17172. }
  17173. // Cache the determinant
  17174. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  17175. return this._worldMatrix;
  17176. };
  17177. TransformNode.prototype._afterComputeWorldMatrix = function () {
  17178. };
  17179. /**
  17180. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  17181. * @param func: callback function to add
  17182. *
  17183. * Returns the TransformNode.
  17184. */
  17185. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  17186. this.onAfterWorldMatrixUpdateObservable.add(func);
  17187. return this;
  17188. };
  17189. /**
  17190. * Removes a registered callback function.
  17191. * Returns the TransformNode.
  17192. */
  17193. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  17194. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  17195. return this;
  17196. };
  17197. /**
  17198. * Clone the current transform node
  17199. * Returns the new transform node
  17200. * @param name Name of the new clone
  17201. * @param newParent New parent for the clone
  17202. * @param doNotCloneChildren Do not clone children hierarchy
  17203. */
  17204. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  17205. var _this = this;
  17206. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  17207. result.name = name;
  17208. result.id = name;
  17209. if (newParent) {
  17210. result.parent = newParent;
  17211. }
  17212. if (!doNotCloneChildren) {
  17213. // Children
  17214. var directDescendants = this.getDescendants(true);
  17215. for (var index = 0; index < directDescendants.length; index++) {
  17216. var child = directDescendants[index];
  17217. if (child.clone) {
  17218. child.clone(name + "." + child.name, result);
  17219. }
  17220. }
  17221. }
  17222. return result;
  17223. };
  17224. TransformNode.prototype.serialize = function (currentSerializationObject) {
  17225. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  17226. serializationObject.type = this.getClassName();
  17227. // Parent
  17228. if (this.parent) {
  17229. serializationObject.parentId = this.parent.id;
  17230. }
  17231. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  17232. serializationObject.tags = BABYLON.Tags.GetTags(this);
  17233. }
  17234. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  17235. serializationObject.isEnabled = this.isEnabled();
  17236. // Parent
  17237. if (this.parent) {
  17238. serializationObject.parentId = this.parent.id;
  17239. }
  17240. return serializationObject;
  17241. };
  17242. // Statics
  17243. /**
  17244. * Returns a new TransformNode object parsed from the source provided.
  17245. * The parameter `parsedMesh` is the source.
  17246. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  17247. */
  17248. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  17249. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  17250. if (BABYLON.Tags) {
  17251. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  17252. }
  17253. if (parsedTransformNode.localMatrix) {
  17254. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  17255. }
  17256. else if (parsedTransformNode.pivotMatrix) {
  17257. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  17258. }
  17259. transformNode.setEnabled(parsedTransformNode.isEnabled);
  17260. // Parent
  17261. if (parsedTransformNode.parentId) {
  17262. transformNode._waitingParentId = parsedTransformNode.parentId;
  17263. }
  17264. return transformNode;
  17265. };
  17266. /**
  17267. * Releases resources associated with this transform node.
  17268. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  17269. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  17270. */
  17271. TransformNode.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  17272. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  17273. // Animations
  17274. this.getScene().stopAnimation(this);
  17275. // Remove from scene
  17276. this.getScene().removeTransformNode(this);
  17277. this.onAfterWorldMatrixUpdateObservable.clear();
  17278. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  17279. };
  17280. // Statics
  17281. TransformNode.BILLBOARDMODE_NONE = 0;
  17282. TransformNode.BILLBOARDMODE_X = 1;
  17283. TransformNode.BILLBOARDMODE_Y = 2;
  17284. TransformNode.BILLBOARDMODE_Z = 4;
  17285. TransformNode.BILLBOARDMODE_ALL = 7;
  17286. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  17287. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  17288. __decorate([
  17289. BABYLON.serializeAsVector3()
  17290. ], TransformNode.prototype, "_rotation", void 0);
  17291. __decorate([
  17292. BABYLON.serializeAsQuaternion()
  17293. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  17294. __decorate([
  17295. BABYLON.serializeAsVector3()
  17296. ], TransformNode.prototype, "_scaling", void 0);
  17297. __decorate([
  17298. BABYLON.serialize()
  17299. ], TransformNode.prototype, "billboardMode", void 0);
  17300. __decorate([
  17301. BABYLON.serialize()
  17302. ], TransformNode.prototype, "scalingDeterminant", void 0);
  17303. __decorate([
  17304. BABYLON.serialize()
  17305. ], TransformNode.prototype, "infiniteDistance", void 0);
  17306. __decorate([
  17307. BABYLON.serializeAsVector3()
  17308. ], TransformNode.prototype, "position", void 0);
  17309. return TransformNode;
  17310. }(BABYLON.Node));
  17311. BABYLON.TransformNode = TransformNode;
  17312. })(BABYLON || (BABYLON = {}));
  17313. //# sourceMappingURL=babylon.transformNode.js.map
  17314. var BABYLON;
  17315. (function (BABYLON) {
  17316. var AbstractMesh = /** @class */ (function (_super) {
  17317. __extends(AbstractMesh, _super);
  17318. // Constructor
  17319. function AbstractMesh(name, scene) {
  17320. if (scene === void 0) { scene = null; }
  17321. var _this = _super.call(this, name, scene, false) || this;
  17322. _this._facetNb = 0; // facet number
  17323. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  17324. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  17325. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  17326. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  17327. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  17328. _this._subDiv = {
  17329. max: 1,
  17330. X: 1,
  17331. Y: 1,
  17332. Z: 1
  17333. };
  17334. _this._facetDepthSort = false; // is the facet depth sort to be computed
  17335. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  17336. // Events
  17337. /**
  17338. * An event triggered when this mesh collides with another one
  17339. * @type {BABYLON.Observable}
  17340. */
  17341. _this.onCollideObservable = new BABYLON.Observable();
  17342. /**
  17343. * An event triggered when the collision's position changes
  17344. * @type {BABYLON.Observable}
  17345. */
  17346. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  17347. /**
  17348. * An event triggered when material is changed
  17349. * @type {BABYLON.Observable}
  17350. */
  17351. _this.onMaterialChangedObservable = new BABYLON.Observable();
  17352. // Properties
  17353. _this.definedFacingForward = true; // orientation for POV movement & rotation
  17354. /**
  17355. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  17356. * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  17357. * or
  17358. * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE (Default Value) which is mapped to GL_ANY_SAMPLES_PASSED_CONSERVATIVE which is a false positive algorithm that is faster than GL_ANY_SAMPLES_PASSED but less accurate.
  17359. * for more info check WebGl documentations
  17360. */
  17361. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  17362. /**
  17363. * This property is responsible for starting the occlusion query within the Mesh or not, this property is also used to determine what should happen when the occlusionRetryCount is reached. It has supports 3 values:
  17364. * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  17365. * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  17366. * OCCLUSION_TYPE_STRICT: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken restore the last state of the mesh occlusion if the mesh was visible then show the mesh if was hidden then hide don't show.
  17367. */
  17368. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  17369. /**
  17370. * This number indicates the number of allowed retries before stop the occlusion query, this is useful if the occlusion query is taking long time before to the query result is retireved, the query result indicates if the object is visible within the scene or not and based on that Babylon.Js engine decideds to show or hide the object.
  17371. * The default value is -1 which means don't break the query and wait till the result.
  17372. */
  17373. _this.occlusionRetryCount = -1;
  17374. _this._occlusionInternalRetryCounter = 0;
  17375. _this._isOccluded = false;
  17376. _this._isOcclusionQueryInProgress = false;
  17377. _this._visibility = 1.0;
  17378. _this.alphaIndex = Number.MAX_VALUE;
  17379. _this.isVisible = true;
  17380. _this.isPickable = true;
  17381. _this.showBoundingBox = false;
  17382. _this.showSubMeshesBoundingBox = false;
  17383. _this.isBlocker = false;
  17384. _this.enablePointerMoveEvents = false;
  17385. _this.renderingGroupId = 0;
  17386. _this._receiveShadows = false;
  17387. _this.renderOutline = false;
  17388. _this.outlineColor = BABYLON.Color3.Red();
  17389. _this.outlineWidth = 0.02;
  17390. _this.renderOverlay = false;
  17391. _this.overlayColor = BABYLON.Color3.Red();
  17392. _this.overlayAlpha = 0.5;
  17393. _this._hasVertexAlpha = false;
  17394. _this._useVertexColors = true;
  17395. _this._computeBonesUsingShaders = true;
  17396. _this._numBoneInfluencers = 4;
  17397. _this._applyFog = true;
  17398. _this.useOctreeForRenderingSelection = true;
  17399. _this.useOctreeForPicking = true;
  17400. _this.useOctreeForCollisions = true;
  17401. _this._layerMask = 0x0FFFFFFF;
  17402. /**
  17403. * True if the mesh must be rendered in any case.
  17404. */
  17405. _this.alwaysSelectAsActiveMesh = false;
  17406. /**
  17407. * This scene's action manager
  17408. * @type {BABYLON.ActionManager}
  17409. */
  17410. _this.actionManager = null;
  17411. // Physics
  17412. _this.physicsImpostor = null;
  17413. // Collisions
  17414. _this._checkCollisions = false;
  17415. _this._collisionMask = -1;
  17416. _this._collisionGroup = -1;
  17417. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  17418. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  17419. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  17420. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  17421. // Edges
  17422. _this.edgesWidth = 1;
  17423. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  17424. // Cache
  17425. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  17426. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  17427. _this._renderId = 0;
  17428. _this._intersectionsInProgress = new Array();
  17429. _this._unIndexed = false;
  17430. _this._lightSources = new Array();
  17431. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  17432. if (collidedMesh === void 0) { collidedMesh = null; }
  17433. //TODO move this to the collision coordinator!
  17434. if (_this.getScene().workerCollisions)
  17435. newPosition.multiplyInPlace(_this._collider._radius);
  17436. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  17437. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  17438. _this.position.addInPlace(_this._diffPositionForCollisions);
  17439. }
  17440. if (collidedMesh) {
  17441. _this.onCollideObservable.notifyObservers(collidedMesh);
  17442. }
  17443. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  17444. };
  17445. _this.getScene().addMesh(_this);
  17446. _this._resyncLightSources();
  17447. return _this;
  17448. }
  17449. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  17450. get: function () {
  17451. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  17452. },
  17453. enumerable: true,
  17454. configurable: true
  17455. });
  17456. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  17457. get: function () {
  17458. return BABYLON.TransformNode.BILLBOARDMODE_X;
  17459. },
  17460. enumerable: true,
  17461. configurable: true
  17462. });
  17463. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  17464. get: function () {
  17465. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  17466. },
  17467. enumerable: true,
  17468. configurable: true
  17469. });
  17470. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  17471. get: function () {
  17472. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  17473. },
  17474. enumerable: true,
  17475. configurable: true
  17476. });
  17477. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  17478. get: function () {
  17479. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  17480. },
  17481. enumerable: true,
  17482. configurable: true
  17483. });
  17484. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  17485. /**
  17486. * Read-only : the number of facets in the mesh
  17487. */
  17488. get: function () {
  17489. return this._facetNb;
  17490. },
  17491. enumerable: true,
  17492. configurable: true
  17493. });
  17494. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  17495. /**
  17496. * The number (integer) of subdivisions per axis in the partioning space
  17497. */
  17498. get: function () {
  17499. return this._partitioningSubdivisions;
  17500. },
  17501. set: function (nb) {
  17502. this._partitioningSubdivisions = nb;
  17503. },
  17504. enumerable: true,
  17505. configurable: true
  17506. });
  17507. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  17508. /**
  17509. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  17510. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  17511. */
  17512. get: function () {
  17513. return this._partitioningBBoxRatio;
  17514. },
  17515. set: function (ratio) {
  17516. this._partitioningBBoxRatio = ratio;
  17517. },
  17518. enumerable: true,
  17519. configurable: true
  17520. });
  17521. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  17522. /**
  17523. * Boolean : must the facet be depth sorted on next call to `updateFacetData()` ?
  17524. * Works only for updatable meshes.
  17525. * Doesn't work with multi-materials.
  17526. */
  17527. get: function () {
  17528. return this._facetDepthSort;
  17529. },
  17530. set: function (sort) {
  17531. this._facetDepthSort = sort;
  17532. },
  17533. enumerable: true,
  17534. configurable: true
  17535. });
  17536. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  17537. /**
  17538. * The location (Vector3) where the facet depth sort must be computed from.
  17539. * By default, the active camera position.
  17540. * Used only when facet depth sort is enabled.
  17541. */
  17542. get: function () {
  17543. return this._facetDepthSortFrom;
  17544. },
  17545. set: function (location) {
  17546. this._facetDepthSortFrom = location;
  17547. },
  17548. enumerable: true,
  17549. configurable: true
  17550. });
  17551. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  17552. /**
  17553. * Read-only boolean : is the feature facetData enabled ?
  17554. */
  17555. get: function () {
  17556. return this._facetDataEnabled;
  17557. },
  17558. enumerable: true,
  17559. configurable: true
  17560. });
  17561. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  17562. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  17563. return false;
  17564. }
  17565. this._markSubMeshesAsMiscDirty();
  17566. return true;
  17567. };
  17568. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  17569. set: function (callback) {
  17570. if (this._onCollideObserver) {
  17571. this.onCollideObservable.remove(this._onCollideObserver);
  17572. }
  17573. this._onCollideObserver = this.onCollideObservable.add(callback);
  17574. },
  17575. enumerable: true,
  17576. configurable: true
  17577. });
  17578. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  17579. set: function (callback) {
  17580. if (this._onCollisionPositionChangeObserver) {
  17581. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  17582. }
  17583. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  17584. },
  17585. enumerable: true,
  17586. configurable: true
  17587. });
  17588. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  17589. /**
  17590. * Property isOccluded : Gets or sets whether the mesh is occluded or not, it is used also to set the intial state of the mesh to be occluded or not.
  17591. */
  17592. get: function () {
  17593. return this._isOccluded;
  17594. },
  17595. set: function (value) {
  17596. this._isOccluded = value;
  17597. },
  17598. enumerable: true,
  17599. configurable: true
  17600. });
  17601. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  17602. /**
  17603. * Flag to check the progress status of the query
  17604. */
  17605. get: function () {
  17606. return this._isOcclusionQueryInProgress;
  17607. },
  17608. enumerable: true,
  17609. configurable: true
  17610. });
  17611. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  17612. /**
  17613. * Gets or sets mesh visibility between 0 and 1 (defult is 1)
  17614. */
  17615. get: function () {
  17616. return this._visibility;
  17617. },
  17618. /**
  17619. * Gets or sets mesh visibility between 0 and 1 (defult is 1)
  17620. */
  17621. set: function (value) {
  17622. if (this._visibility === value) {
  17623. return;
  17624. }
  17625. this._visibility = value;
  17626. this._markSubMeshesAsMiscDirty();
  17627. },
  17628. enumerable: true,
  17629. configurable: true
  17630. });
  17631. Object.defineProperty(AbstractMesh.prototype, "material", {
  17632. get: function () {
  17633. return this._material;
  17634. },
  17635. set: function (value) {
  17636. if (this._material === value) {
  17637. return;
  17638. }
  17639. this._material = value;
  17640. if (this.onMaterialChangedObservable.hasObservers) {
  17641. this.onMaterialChangedObservable.notifyObservers(this);
  17642. }
  17643. if (!this.subMeshes) {
  17644. return;
  17645. }
  17646. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17647. var subMesh = _a[_i];
  17648. subMesh.setEffect(null);
  17649. }
  17650. },
  17651. enumerable: true,
  17652. configurable: true
  17653. });
  17654. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  17655. get: function () {
  17656. return this._receiveShadows;
  17657. },
  17658. set: function (value) {
  17659. if (this._receiveShadows === value) {
  17660. return;
  17661. }
  17662. this._receiveShadows = value;
  17663. this._markSubMeshesAsLightDirty();
  17664. },
  17665. enumerable: true,
  17666. configurable: true
  17667. });
  17668. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  17669. get: function () {
  17670. return this._hasVertexAlpha;
  17671. },
  17672. set: function (value) {
  17673. if (this._hasVertexAlpha === value) {
  17674. return;
  17675. }
  17676. this._hasVertexAlpha = value;
  17677. this._markSubMeshesAsAttributesDirty();
  17678. this._markSubMeshesAsMiscDirty();
  17679. },
  17680. enumerable: true,
  17681. configurable: true
  17682. });
  17683. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  17684. get: function () {
  17685. return this._useVertexColors;
  17686. },
  17687. set: function (value) {
  17688. if (this._useVertexColors === value) {
  17689. return;
  17690. }
  17691. this._useVertexColors = value;
  17692. this._markSubMeshesAsAttributesDirty();
  17693. },
  17694. enumerable: true,
  17695. configurable: true
  17696. });
  17697. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  17698. get: function () {
  17699. return this._computeBonesUsingShaders;
  17700. },
  17701. set: function (value) {
  17702. if (this._computeBonesUsingShaders === value) {
  17703. return;
  17704. }
  17705. this._computeBonesUsingShaders = value;
  17706. this._markSubMeshesAsAttributesDirty();
  17707. },
  17708. enumerable: true,
  17709. configurable: true
  17710. });
  17711. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  17712. get: function () {
  17713. return this._numBoneInfluencers;
  17714. },
  17715. set: function (value) {
  17716. if (this._numBoneInfluencers === value) {
  17717. return;
  17718. }
  17719. this._numBoneInfluencers = value;
  17720. this._markSubMeshesAsAttributesDirty();
  17721. },
  17722. enumerable: true,
  17723. configurable: true
  17724. });
  17725. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  17726. get: function () {
  17727. return this._applyFog;
  17728. },
  17729. set: function (value) {
  17730. if (this._applyFog === value) {
  17731. return;
  17732. }
  17733. this._applyFog = value;
  17734. this._markSubMeshesAsMiscDirty();
  17735. },
  17736. enumerable: true,
  17737. configurable: true
  17738. });
  17739. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  17740. get: function () {
  17741. return this._layerMask;
  17742. },
  17743. set: function (value) {
  17744. if (value === this._layerMask) {
  17745. return;
  17746. }
  17747. this._layerMask = value;
  17748. this._resyncLightSources();
  17749. },
  17750. enumerable: true,
  17751. configurable: true
  17752. });
  17753. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  17754. get: function () {
  17755. return this._collisionMask;
  17756. },
  17757. set: function (mask) {
  17758. this._collisionMask = !isNaN(mask) ? mask : -1;
  17759. },
  17760. enumerable: true,
  17761. configurable: true
  17762. });
  17763. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  17764. get: function () {
  17765. return this._collisionGroup;
  17766. },
  17767. set: function (mask) {
  17768. this._collisionGroup = !isNaN(mask) ? mask : -1;
  17769. },
  17770. enumerable: true,
  17771. configurable: true
  17772. });
  17773. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  17774. get: function () {
  17775. return null;
  17776. },
  17777. enumerable: true,
  17778. configurable: true
  17779. });
  17780. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  17781. get: function () {
  17782. return this._skeleton;
  17783. },
  17784. set: function (value) {
  17785. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  17786. this._skeleton._unregisterMeshWithPoseMatrix(this);
  17787. }
  17788. if (value && value.needInitialSkinMatrix) {
  17789. value._registerMeshWithPoseMatrix(this);
  17790. }
  17791. this._skeleton = value;
  17792. if (!this._skeleton) {
  17793. this._bonesTransformMatrices = null;
  17794. }
  17795. this._markSubMeshesAsAttributesDirty();
  17796. },
  17797. enumerable: true,
  17798. configurable: true
  17799. });
  17800. /**
  17801. * Returns the string "AbstractMesh"
  17802. */
  17803. AbstractMesh.prototype.getClassName = function () {
  17804. return "AbstractMesh";
  17805. };
  17806. /**
  17807. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  17808. */
  17809. AbstractMesh.prototype.toString = function (fullDetails) {
  17810. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  17811. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  17812. if (this._skeleton) {
  17813. ret += ", skeleton: " + this._skeleton.name;
  17814. }
  17815. if (fullDetails) {
  17816. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  17817. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  17818. }
  17819. return ret;
  17820. };
  17821. AbstractMesh.prototype._rebuild = function () {
  17822. if (this._occlusionQuery) {
  17823. this._occlusionQuery = null;
  17824. }
  17825. if (this._edgesRenderer) {
  17826. this._edgesRenderer._rebuild();
  17827. }
  17828. if (!this.subMeshes) {
  17829. return;
  17830. }
  17831. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17832. var subMesh = _a[_i];
  17833. subMesh._rebuild();
  17834. }
  17835. };
  17836. AbstractMesh.prototype._resyncLightSources = function () {
  17837. this._lightSources.length = 0;
  17838. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  17839. var light = _a[_i];
  17840. if (!light.isEnabled()) {
  17841. continue;
  17842. }
  17843. if (light.canAffectMesh(this)) {
  17844. this._lightSources.push(light);
  17845. }
  17846. }
  17847. this._markSubMeshesAsLightDirty();
  17848. };
  17849. AbstractMesh.prototype._resyncLighSource = function (light) {
  17850. var isIn = light.isEnabled() && light.canAffectMesh(this);
  17851. var index = this._lightSources.indexOf(light);
  17852. if (index === -1) {
  17853. if (!isIn) {
  17854. return;
  17855. }
  17856. this._lightSources.push(light);
  17857. }
  17858. else {
  17859. if (isIn) {
  17860. return;
  17861. }
  17862. this._lightSources.splice(index, 1);
  17863. }
  17864. this._markSubMeshesAsLightDirty();
  17865. };
  17866. AbstractMesh.prototype._removeLightSource = function (light) {
  17867. var index = this._lightSources.indexOf(light);
  17868. if (index === -1) {
  17869. return;
  17870. }
  17871. this._lightSources.splice(index, 1);
  17872. this._markSubMeshesAsLightDirty();
  17873. };
  17874. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  17875. if (!this.subMeshes) {
  17876. return;
  17877. }
  17878. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17879. var subMesh = _a[_i];
  17880. if (subMesh._materialDefines) {
  17881. func(subMesh._materialDefines);
  17882. }
  17883. }
  17884. };
  17885. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  17886. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  17887. };
  17888. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  17889. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  17890. };
  17891. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  17892. if (!this.subMeshes) {
  17893. return;
  17894. }
  17895. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17896. var subMesh = _a[_i];
  17897. var material = subMesh.getMaterial();
  17898. if (material) {
  17899. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  17900. }
  17901. }
  17902. };
  17903. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  17904. /**
  17905. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  17906. * Default : (1.0, 1.0, 1.0)
  17907. */
  17908. get: function () {
  17909. return this._scaling;
  17910. },
  17911. /**
  17912. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  17913. * Default : (1.0, 1.0, 1.0)
  17914. */
  17915. set: function (newScaling) {
  17916. this._scaling = newScaling;
  17917. if (this.physicsImpostor) {
  17918. this.physicsImpostor.forceUpdate();
  17919. }
  17920. },
  17921. enumerable: true,
  17922. configurable: true
  17923. });
  17924. // Methods
  17925. /**
  17926. * Disables the mesh edger rendering mode.
  17927. * Returns the AbstractMesh.
  17928. */
  17929. AbstractMesh.prototype.disableEdgesRendering = function () {
  17930. if (this._edgesRenderer) {
  17931. this._edgesRenderer.dispose();
  17932. this._edgesRenderer = null;
  17933. }
  17934. return this;
  17935. };
  17936. /**
  17937. * Enables the edge rendering mode on the mesh.
  17938. * This mode makes the mesh edges visible.
  17939. * Returns the AbstractMesh.
  17940. */
  17941. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  17942. if (epsilon === void 0) { epsilon = 0.95; }
  17943. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  17944. this.disableEdgesRendering();
  17945. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  17946. return this;
  17947. };
  17948. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  17949. /**
  17950. * Returns true if the mesh is blocked. Used by the class Mesh.
  17951. * Returns the boolean `false` by default.
  17952. */
  17953. get: function () {
  17954. return false;
  17955. },
  17956. enumerable: true,
  17957. configurable: true
  17958. });
  17959. /**
  17960. * Returns the mesh itself by default, used by the class Mesh.
  17961. * Returned type : AbstractMesh
  17962. */
  17963. AbstractMesh.prototype.getLOD = function (camera) {
  17964. return this;
  17965. };
  17966. /**
  17967. * Returns 0 by default, used by the class Mesh.
  17968. * Returns an integer.
  17969. */
  17970. AbstractMesh.prototype.getTotalVertices = function () {
  17971. return 0;
  17972. };
  17973. /**
  17974. * Returns null by default, used by the class Mesh.
  17975. * Returned type : integer array
  17976. */
  17977. AbstractMesh.prototype.getIndices = function () {
  17978. return null;
  17979. };
  17980. /**
  17981. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  17982. * Returned type : float array or Float32Array
  17983. */
  17984. AbstractMesh.prototype.getVerticesData = function (kind) {
  17985. return null;
  17986. };
  17987. /**
  17988. * Sets the vertex data of the mesh geometry for the requested `kind`.
  17989. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  17990. * The `data` are either a numeric array either a Float32Array.
  17991. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  17992. * The parameter `stride` is an optional positive integer, it is usually automatically deducted from the `kind` (3 for positions or normals, 2 for UV, etc).
  17993. * Note that a new underlying VertexBuffer object is created each call.
  17994. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  17995. *
  17996. * Possible `kind` values :
  17997. * - BABYLON.VertexBuffer.PositionKind
  17998. * - BABYLON.VertexBuffer.UVKind
  17999. * - BABYLON.VertexBuffer.UV2Kind
  18000. * - BABYLON.VertexBuffer.UV3Kind
  18001. * - BABYLON.VertexBuffer.UV4Kind
  18002. * - BABYLON.VertexBuffer.UV5Kind
  18003. * - BABYLON.VertexBuffer.UV6Kind
  18004. * - BABYLON.VertexBuffer.ColorKind
  18005. * - BABYLON.VertexBuffer.MatricesIndicesKind
  18006. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  18007. * - BABYLON.VertexBuffer.MatricesWeightsKind
  18008. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  18009. *
  18010. * Returns the Mesh.
  18011. */
  18012. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  18013. return this;
  18014. };
  18015. /**
  18016. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  18017. * If the mesh has no geometry, it is simply returned as it is.
  18018. * The `data` are either a numeric array either a Float32Array.
  18019. * No new underlying VertexBuffer object is created.
  18020. * If the `kind` is the `PositionKind` and if `updateExtends` is true, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  18021. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  18022. *
  18023. * Possible `kind` values :
  18024. * - BABYLON.VertexBuffer.PositionKind
  18025. * - BABYLON.VertexBuffer.UVKind
  18026. * - BABYLON.VertexBuffer.UV2Kind
  18027. * - BABYLON.VertexBuffer.UV3Kind
  18028. * - BABYLON.VertexBuffer.UV4Kind
  18029. * - BABYLON.VertexBuffer.UV5Kind
  18030. * - BABYLON.VertexBuffer.UV6Kind
  18031. * - BABYLON.VertexBuffer.ColorKind
  18032. * - BABYLON.VertexBuffer.MatricesIndicesKind
  18033. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  18034. * - BABYLON.VertexBuffer.MatricesWeightsKind
  18035. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  18036. *
  18037. * Returns the Mesh.
  18038. */
  18039. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  18040. return this;
  18041. };
  18042. /**
  18043. * Sets the mesh indices.
  18044. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  18045. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  18046. * This method creates a new index buffer each call.
  18047. * Returns the Mesh.
  18048. */
  18049. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  18050. return this;
  18051. };
  18052. /** Returns false by default, used by the class Mesh.
  18053. * Returns a boolean
  18054. */
  18055. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  18056. return false;
  18057. };
  18058. /**
  18059. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  18060. * Returns a BoundingInfo
  18061. */
  18062. AbstractMesh.prototype.getBoundingInfo = function () {
  18063. if (this._masterMesh) {
  18064. return this._masterMesh.getBoundingInfo();
  18065. }
  18066. if (!this._boundingInfo) {
  18067. // this._boundingInfo is being created here
  18068. this._updateBoundingInfo();
  18069. }
  18070. // cannot be null.
  18071. return this._boundingInfo;
  18072. };
  18073. /**
  18074. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units).
  18075. * @param includeDescendants Take the hierarchy's bounding box instead of the mesh's bounding box.
  18076. */
  18077. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  18078. if (includeDescendants === void 0) { includeDescendants = true; }
  18079. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  18080. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  18081. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  18082. if (maxDimension === 0) {
  18083. return this;
  18084. }
  18085. var scale = 1 / maxDimension;
  18086. this.scaling.scaleInPlace(scale);
  18087. return this;
  18088. };
  18089. /**
  18090. * Sets a mesh new object BoundingInfo.
  18091. * Returns the AbstractMesh.
  18092. */
  18093. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  18094. this._boundingInfo = boundingInfo;
  18095. return this;
  18096. };
  18097. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  18098. get: function () {
  18099. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  18100. },
  18101. enumerable: true,
  18102. configurable: true
  18103. });
  18104. AbstractMesh.prototype._preActivate = function () {
  18105. };
  18106. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  18107. };
  18108. AbstractMesh.prototype._activate = function (renderId) {
  18109. this._renderId = renderId;
  18110. };
  18111. /**
  18112. * Returns the latest update of the World matrix
  18113. * Returns a Matrix.
  18114. */
  18115. AbstractMesh.prototype.getWorldMatrix = function () {
  18116. if (this._masterMesh) {
  18117. return this._masterMesh.getWorldMatrix();
  18118. }
  18119. return _super.prototype.getWorldMatrix.call(this);
  18120. };
  18121. /**
  18122. * Returns the latest update of the World matrix determinant.
  18123. */
  18124. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  18125. if (this._masterMesh) {
  18126. return this._masterMesh._getWorldMatrixDeterminant();
  18127. }
  18128. return _super.prototype._getWorldMatrixDeterminant.call(this);
  18129. };
  18130. // ================================== Point of View Movement =================================
  18131. /**
  18132. * Perform relative position change from the point of view of behind the front of the mesh.
  18133. * This is performed taking into account the meshes current rotation, so you do not have to care.
  18134. * Supports definition of mesh facing forward or backward.
  18135. * @param {number} amountRight
  18136. * @param {number} amountUp
  18137. * @param {number} amountForward
  18138. *
  18139. * Returns the AbstractMesh.
  18140. */
  18141. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  18142. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  18143. return this;
  18144. };
  18145. /**
  18146. * Calculate relative position change from the point of view of behind the front of the mesh.
  18147. * This is performed taking into account the meshes current rotation, so you do not have to care.
  18148. * Supports definition of mesh facing forward or backward.
  18149. * @param {number} amountRight
  18150. * @param {number} amountUp
  18151. * @param {number} amountForward
  18152. *
  18153. * Returns a new Vector3.
  18154. */
  18155. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  18156. var rotMatrix = new BABYLON.Matrix();
  18157. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  18158. rotQuaternion.toRotationMatrix(rotMatrix);
  18159. var translationDelta = BABYLON.Vector3.Zero();
  18160. var defForwardMult = this.definedFacingForward ? -1 : 1;
  18161. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  18162. return translationDelta;
  18163. };
  18164. // ================================== Point of View Rotation =================================
  18165. /**
  18166. * Perform relative rotation change from the point of view of behind the front of the mesh.
  18167. * Supports definition of mesh facing forward or backward.
  18168. * @param {number} flipBack
  18169. * @param {number} twirlClockwise
  18170. * @param {number} tiltRight
  18171. *
  18172. * Returns the AbstractMesh.
  18173. */
  18174. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  18175. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  18176. return this;
  18177. };
  18178. /**
  18179. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  18180. * Supports definition of mesh facing forward or backward.
  18181. * @param {number} flipBack
  18182. * @param {number} twirlClockwise
  18183. * @param {number} tiltRight
  18184. *
  18185. * Returns a new Vector3.
  18186. */
  18187. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  18188. var defForwardMult = this.definedFacingForward ? 1 : -1;
  18189. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  18190. };
  18191. /**
  18192. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  18193. * @param includeDescendants Include bounding info from descendants as well (true by default).
  18194. */
  18195. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants) {
  18196. if (includeDescendants === void 0) { includeDescendants = true; }
  18197. this.computeWorldMatrix(true);
  18198. var min;
  18199. var max;
  18200. var boundingInfo = this.getBoundingInfo();
  18201. if (!this.subMeshes) {
  18202. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  18203. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  18204. }
  18205. else {
  18206. min = boundingInfo.boundingBox.minimumWorld;
  18207. max = boundingInfo.boundingBox.maximumWorld;
  18208. }
  18209. if (includeDescendants) {
  18210. var descendants = this.getDescendants(false);
  18211. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  18212. var descendant = descendants_1[_i];
  18213. var childMesh = descendant;
  18214. childMesh.computeWorldMatrix(true);
  18215. //make sure we have the needed params to get mix and max
  18216. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  18217. continue;
  18218. }
  18219. var childBoundingInfo = childMesh.getBoundingInfo();
  18220. var boundingBox = childBoundingInfo.boundingBox;
  18221. var minBox = boundingBox.minimumWorld;
  18222. var maxBox = boundingBox.maximumWorld;
  18223. BABYLON.Tools.CheckExtends(minBox, min, max);
  18224. BABYLON.Tools.CheckExtends(maxBox, min, max);
  18225. }
  18226. }
  18227. return {
  18228. min: min,
  18229. max: max
  18230. };
  18231. };
  18232. /**
  18233. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  18234. * Returns the AbstractMesh.
  18235. */
  18236. AbstractMesh.prototype._updateBoundingInfo = function () {
  18237. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  18238. this._boundingInfo.update(this.worldMatrixFromCache);
  18239. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  18240. return this;
  18241. };
  18242. /**
  18243. * Update a mesh's children BoundingInfo objects only.
  18244. * Returns the AbstractMesh.
  18245. */
  18246. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  18247. if (!this.subMeshes) {
  18248. return this;
  18249. }
  18250. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  18251. var subMesh = this.subMeshes[subIndex];
  18252. if (!subMesh.IsGlobal) {
  18253. subMesh.updateBoundingInfo(matrix);
  18254. }
  18255. }
  18256. return this;
  18257. };
  18258. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  18259. // Bounding info
  18260. this._updateBoundingInfo();
  18261. };
  18262. /**
  18263. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  18264. * A mesh is in the frustum if its bounding box intersects the frustum.
  18265. * Boolean returned.
  18266. */
  18267. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  18268. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  18269. };
  18270. /**
  18271. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  18272. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  18273. * Boolean returned.
  18274. */
  18275. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18276. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  18277. ;
  18278. };
  18279. /**
  18280. * True if the mesh intersects another mesh or a SolidParticle object.
  18281. * Unless the parameter `precise` is set to `true` the intersection is computed according to Axis Aligned Bounding Boxes (AABB), else according to OBB (Oriented BBoxes)
  18282. * includeDescendants can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  18283. * Returns a boolean.
  18284. */
  18285. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  18286. if (precise === void 0) { precise = false; }
  18287. if (!this._boundingInfo || !mesh._boundingInfo) {
  18288. return false;
  18289. }
  18290. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  18291. return true;
  18292. }
  18293. if (includeDescendants) {
  18294. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  18295. var child = _a[_i];
  18296. if (child.intersectsMesh(mesh, precise, true)) {
  18297. return true;
  18298. }
  18299. }
  18300. }
  18301. return false;
  18302. };
  18303. /**
  18304. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  18305. * Returns a boolean.
  18306. */
  18307. AbstractMesh.prototype.intersectsPoint = function (point) {
  18308. if (!this._boundingInfo) {
  18309. return false;
  18310. }
  18311. return this._boundingInfo.intersectsPoint(point);
  18312. };
  18313. AbstractMesh.prototype.getPhysicsImpostor = function () {
  18314. return this.physicsImpostor;
  18315. };
  18316. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  18317. if (camera === void 0) { camera = null; }
  18318. if (!camera) {
  18319. camera = this.getScene().activeCamera;
  18320. }
  18321. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  18322. };
  18323. /**
  18324. * Returns the distance from the mesh to the active camera.
  18325. * Returns a float.
  18326. */
  18327. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  18328. if (camera === void 0) { camera = null; }
  18329. if (!camera) {
  18330. camera = this.getScene().activeCamera;
  18331. }
  18332. return this.absolutePosition.subtract(camera.position).length();
  18333. };
  18334. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  18335. if (!this.physicsImpostor) {
  18336. return this;
  18337. }
  18338. this.physicsImpostor.applyImpulse(force, contactPoint);
  18339. return this;
  18340. };
  18341. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  18342. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  18343. return this;
  18344. }
  18345. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  18346. mainPivot: pivot1,
  18347. connectedPivot: pivot2,
  18348. nativeParams: options
  18349. });
  18350. return this;
  18351. };
  18352. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  18353. // Collisions
  18354. /**
  18355. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  18356. * Default `false`.
  18357. */
  18358. get: function () {
  18359. return this._checkCollisions;
  18360. },
  18361. set: function (collisionEnabled) {
  18362. this._checkCollisions = collisionEnabled;
  18363. if (this.getScene().workerCollisions) {
  18364. this.getScene().collisionCoordinator.onMeshUpdated(this);
  18365. }
  18366. },
  18367. enumerable: true,
  18368. configurable: true
  18369. });
  18370. Object.defineProperty(AbstractMesh.prototype, "collider", {
  18371. /**
  18372. * Gets Collider object used to compute collisions (not physics)
  18373. */
  18374. get: function () {
  18375. return this._collider;
  18376. },
  18377. enumerable: true,
  18378. configurable: true
  18379. });
  18380. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  18381. var globalPosition = this.getAbsolutePosition();
  18382. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  18383. if (!this._collider) {
  18384. this._collider = new BABYLON.Collider();
  18385. }
  18386. this._collider._radius = this.ellipsoid;
  18387. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  18388. return this;
  18389. };
  18390. // Submeshes octree
  18391. /**
  18392. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  18393. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  18394. * Returns an Octree of submeshes.
  18395. */
  18396. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  18397. if (maxCapacity === void 0) { maxCapacity = 64; }
  18398. if (maxDepth === void 0) { maxDepth = 2; }
  18399. if (!this._submeshesOctree) {
  18400. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  18401. }
  18402. this.computeWorldMatrix(true);
  18403. var boundingInfo = this.getBoundingInfo();
  18404. // Update octree
  18405. var bbox = boundingInfo.boundingBox;
  18406. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  18407. return this._submeshesOctree;
  18408. };
  18409. // Collisions
  18410. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  18411. this._generatePointsArray();
  18412. if (!this._positions) {
  18413. return this;
  18414. }
  18415. // Transformation
  18416. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  18417. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  18418. subMesh._lastColliderWorldVertices = [];
  18419. subMesh._trianglePlanes = [];
  18420. var start = subMesh.verticesStart;
  18421. var end = (subMesh.verticesStart + subMesh.verticesCount);
  18422. for (var i = start; i < end; i++) {
  18423. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  18424. }
  18425. }
  18426. // Collide
  18427. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  18428. if (collider.collisionFound) {
  18429. collider.collidedMesh = this;
  18430. }
  18431. return this;
  18432. };
  18433. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  18434. var subMeshes;
  18435. var len;
  18436. // Octrees
  18437. if (this._submeshesOctree && this.useOctreeForCollisions) {
  18438. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  18439. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  18440. len = intersections.length;
  18441. subMeshes = intersections.data;
  18442. }
  18443. else {
  18444. subMeshes = this.subMeshes;
  18445. len = subMeshes.length;
  18446. }
  18447. for (var index = 0; index < len; index++) {
  18448. var subMesh = subMeshes[index];
  18449. // Bounding test
  18450. if (len > 1 && !subMesh._checkCollision(collider))
  18451. continue;
  18452. this._collideForSubMesh(subMesh, transformMatrix, collider);
  18453. }
  18454. return this;
  18455. };
  18456. AbstractMesh.prototype._checkCollision = function (collider) {
  18457. // Bounding box test
  18458. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  18459. return this;
  18460. // Transformation matrix
  18461. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  18462. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  18463. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  18464. return this;
  18465. };
  18466. // Picking
  18467. AbstractMesh.prototype._generatePointsArray = function () {
  18468. return false;
  18469. };
  18470. /**
  18471. * Checks if the passed Ray intersects with the mesh.
  18472. * Returns an object PickingInfo.
  18473. */
  18474. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  18475. var pickingInfo = new BABYLON.PickingInfo();
  18476. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  18477. return pickingInfo;
  18478. }
  18479. if (!this._generatePointsArray()) {
  18480. return pickingInfo;
  18481. }
  18482. var intersectInfo = null;
  18483. // Octrees
  18484. var subMeshes;
  18485. var len;
  18486. if (this._submeshesOctree && this.useOctreeForPicking) {
  18487. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  18488. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  18489. len = intersections.length;
  18490. subMeshes = intersections.data;
  18491. }
  18492. else {
  18493. subMeshes = this.subMeshes;
  18494. len = subMeshes.length;
  18495. }
  18496. for (var index = 0; index < len; index++) {
  18497. var subMesh = subMeshes[index];
  18498. // Bounding test
  18499. if (len > 1 && !subMesh.canIntersects(ray))
  18500. continue;
  18501. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  18502. if (currentIntersectInfo) {
  18503. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  18504. intersectInfo = currentIntersectInfo;
  18505. intersectInfo.subMeshId = index;
  18506. if (fastCheck) {
  18507. break;
  18508. }
  18509. }
  18510. }
  18511. }
  18512. if (intersectInfo) {
  18513. // Get picked point
  18514. var world = this.getWorldMatrix();
  18515. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  18516. var direction = ray.direction.clone();
  18517. direction = direction.scale(intersectInfo.distance);
  18518. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  18519. var pickedPoint = worldOrigin.add(worldDirection);
  18520. // Return result
  18521. pickingInfo.hit = true;
  18522. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  18523. pickingInfo.pickedPoint = pickedPoint;
  18524. pickingInfo.pickedMesh = this;
  18525. pickingInfo.bu = intersectInfo.bu || 0;
  18526. pickingInfo.bv = intersectInfo.bv || 0;
  18527. pickingInfo.faceId = intersectInfo.faceId;
  18528. pickingInfo.subMeshId = intersectInfo.subMeshId;
  18529. return pickingInfo;
  18530. }
  18531. return pickingInfo;
  18532. };
  18533. /**
  18534. * Clones the mesh, used by the class Mesh.
  18535. * Just returns `null` for an AbstractMesh.
  18536. */
  18537. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  18538. return null;
  18539. };
  18540. /**
  18541. * Disposes all the mesh submeshes.
  18542. * Returns the AbstractMesh.
  18543. */
  18544. AbstractMesh.prototype.releaseSubMeshes = function () {
  18545. if (this.subMeshes) {
  18546. while (this.subMeshes.length) {
  18547. this.subMeshes[0].dispose();
  18548. }
  18549. }
  18550. else {
  18551. this.subMeshes = new Array();
  18552. }
  18553. return this;
  18554. };
  18555. /**
  18556. * Releases resources associated with this abstract mesh.
  18557. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  18558. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  18559. */
  18560. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  18561. var _this = this;
  18562. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  18563. var index;
  18564. // Smart Array Retainers.
  18565. this.getScene().freeActiveMeshes();
  18566. this.getScene().freeRenderingGroups();
  18567. // Action manager
  18568. if (this.actionManager !== undefined && this.actionManager !== null) {
  18569. this.actionManager.dispose();
  18570. this.actionManager = null;
  18571. }
  18572. // Skeleton
  18573. this.skeleton = null;
  18574. // Physics
  18575. if (this.physicsImpostor) {
  18576. this.physicsImpostor.dispose();
  18577. }
  18578. // Intersections in progress
  18579. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  18580. var other = this._intersectionsInProgress[index];
  18581. var pos = other._intersectionsInProgress.indexOf(this);
  18582. other._intersectionsInProgress.splice(pos, 1);
  18583. }
  18584. this._intersectionsInProgress = [];
  18585. // Lights
  18586. var lights = this.getScene().lights;
  18587. lights.forEach(function (light) {
  18588. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  18589. if (meshIndex !== -1) {
  18590. light.includedOnlyMeshes.splice(meshIndex, 1);
  18591. }
  18592. meshIndex = light.excludedMeshes.indexOf(_this);
  18593. if (meshIndex !== -1) {
  18594. light.excludedMeshes.splice(meshIndex, 1);
  18595. }
  18596. // Shadow generators
  18597. var generator = light.getShadowGenerator();
  18598. if (generator) {
  18599. var shadowMap = generator.getShadowMap();
  18600. if (shadowMap && shadowMap.renderList) {
  18601. meshIndex = shadowMap.renderList.indexOf(_this);
  18602. if (meshIndex !== -1) {
  18603. shadowMap.renderList.splice(meshIndex, 1);
  18604. }
  18605. }
  18606. }
  18607. });
  18608. // Edges
  18609. if (this._edgesRenderer) {
  18610. this._edgesRenderer.dispose();
  18611. this._edgesRenderer = null;
  18612. }
  18613. // SubMeshes
  18614. if (this.getClassName() !== "InstancedMesh") {
  18615. this.releaseSubMeshes();
  18616. }
  18617. // Octree
  18618. var sceneOctree = this.getScene().selectionOctree;
  18619. if (sceneOctree !== undefined && sceneOctree !== null) {
  18620. var index = sceneOctree.dynamicContent.indexOf(this);
  18621. if (index !== -1) {
  18622. sceneOctree.dynamicContent.splice(index, 1);
  18623. }
  18624. }
  18625. // Query
  18626. var engine = this.getScene().getEngine();
  18627. if (this._occlusionQuery) {
  18628. this._isOcclusionQueryInProgress = false;
  18629. engine.deleteQuery(this._occlusionQuery);
  18630. this._occlusionQuery = null;
  18631. }
  18632. // Engine
  18633. engine.wipeCaches();
  18634. // Remove from scene
  18635. this.getScene().removeMesh(this);
  18636. if (disposeMaterialAndTextures) {
  18637. if (this.material) {
  18638. this.material.dispose(false, true);
  18639. }
  18640. }
  18641. if (!doNotRecurse) {
  18642. // Particles
  18643. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  18644. if (this.getScene().particleSystems[index].emitter === this) {
  18645. this.getScene().particleSystems[index].dispose();
  18646. index--;
  18647. }
  18648. }
  18649. }
  18650. // facet data
  18651. if (this._facetDataEnabled) {
  18652. this.disableFacetData();
  18653. }
  18654. this.onAfterWorldMatrixUpdateObservable.clear();
  18655. this.onCollideObservable.clear();
  18656. this.onCollisionPositionChangeObservable.clear();
  18657. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  18658. };
  18659. /**
  18660. * Adds the passed mesh as a child to the current mesh.
  18661. * Returns the AbstractMesh.
  18662. */
  18663. AbstractMesh.prototype.addChild = function (mesh) {
  18664. mesh.setParent(this);
  18665. return this;
  18666. };
  18667. /**
  18668. * Removes the passed mesh from the current mesh children list.
  18669. * Returns the AbstractMesh.
  18670. */
  18671. AbstractMesh.prototype.removeChild = function (mesh) {
  18672. mesh.setParent(null);
  18673. return this;
  18674. };
  18675. // Facet data
  18676. /**
  18677. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  18678. * Returns the AbstractMesh.
  18679. */
  18680. AbstractMesh.prototype._initFacetData = function () {
  18681. if (!this._facetNormals) {
  18682. this._facetNormals = new Array();
  18683. }
  18684. if (!this._facetPositions) {
  18685. this._facetPositions = new Array();
  18686. }
  18687. if (!this._facetPartitioning) {
  18688. this._facetPartitioning = new Array();
  18689. }
  18690. this._facetNb = (this.getIndices().length / 3) | 0;
  18691. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  18692. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  18693. for (var f = 0; f < this._facetNb; f++) {
  18694. this._facetNormals[f] = BABYLON.Vector3.Zero();
  18695. this._facetPositions[f] = BABYLON.Vector3.Zero();
  18696. }
  18697. this._facetDataEnabled = true;
  18698. return this;
  18699. };
  18700. /**
  18701. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  18702. * This method can be called within the render loop.
  18703. * You don't need to call this method by yourself in the render loop when you update/morph a mesh with the methods CreateXXX() as they automatically manage this computation.
  18704. * Returns the AbstractMesh.
  18705. */
  18706. AbstractMesh.prototype.updateFacetData = function () {
  18707. if (!this._facetDataEnabled) {
  18708. this._initFacetData();
  18709. }
  18710. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18711. var indices = this.getIndices();
  18712. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  18713. var bInfo = this.getBoundingInfo();
  18714. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  18715. // init arrays, matrix and sort function on first call
  18716. this._facetDepthSortEnabled = true;
  18717. if (indices instanceof Uint16Array) {
  18718. this._depthSortedIndices = new Uint16Array(indices);
  18719. }
  18720. else if (indices instanceof Uint32Array) {
  18721. this._depthSortedIndices = new Uint32Array(indices);
  18722. }
  18723. else {
  18724. var needs32bits = false;
  18725. for (var i = 0; i < indices.length; i++) {
  18726. if (indices[i] > 65535) {
  18727. needs32bits = true;
  18728. break;
  18729. }
  18730. }
  18731. if (needs32bits) {
  18732. this._depthSortedIndices = new Uint32Array(indices);
  18733. }
  18734. else {
  18735. this._depthSortedIndices = new Uint16Array(indices);
  18736. }
  18737. }
  18738. this._facetDepthSortFunction = function (f1, f2) {
  18739. return (f2.sqDistance - f1.sqDistance);
  18740. };
  18741. if (!this._facetDepthSortFrom) {
  18742. var camera = this.getScene().activeCamera;
  18743. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  18744. }
  18745. this._depthSortedFacets = [];
  18746. for (var f = 0; f < this._facetNb; f++) {
  18747. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  18748. this._depthSortedFacets.push(depthSortedFacet);
  18749. }
  18750. this._invertedMatrix = BABYLON.Matrix.Identity();
  18751. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  18752. }
  18753. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  18754. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  18755. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  18756. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  18757. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  18758. this._subDiv.max = this._partitioningSubdivisions;
  18759. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  18760. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  18761. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  18762. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  18763. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  18764. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  18765. // set the parameters for ComputeNormals()
  18766. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  18767. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  18768. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  18769. this._facetParameters.bInfo = bInfo;
  18770. this._facetParameters.bbSize = this._bbSize;
  18771. this._facetParameters.subDiv = this._subDiv;
  18772. this._facetParameters.ratio = this.partitioningBBoxRatio;
  18773. this._facetParameters.depthSort = this._facetDepthSort;
  18774. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  18775. this.computeWorldMatrix(true);
  18776. this._worldMatrix.invertToRef(this._invertedMatrix);
  18777. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  18778. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  18779. }
  18780. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  18781. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  18782. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  18783. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  18784. var l = (this._depthSortedIndices.length / 3) | 0;
  18785. for (var f = 0; f < l; f++) {
  18786. var sind = this._depthSortedFacets[f].ind;
  18787. this._depthSortedIndices[f * 3] = indices[sind];
  18788. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  18789. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  18790. }
  18791. this.updateIndices(this._depthSortedIndices);
  18792. }
  18793. return this;
  18794. };
  18795. /**
  18796. * Returns the facetLocalNormals array.
  18797. * The normals are expressed in the mesh local space.
  18798. */
  18799. AbstractMesh.prototype.getFacetLocalNormals = function () {
  18800. if (!this._facetNormals) {
  18801. this.updateFacetData();
  18802. }
  18803. return this._facetNormals;
  18804. };
  18805. /**
  18806. * Returns the facetLocalPositions array.
  18807. * The facet positions are expressed in the mesh local space.
  18808. */
  18809. AbstractMesh.prototype.getFacetLocalPositions = function () {
  18810. if (!this._facetPositions) {
  18811. this.updateFacetData();
  18812. }
  18813. return this._facetPositions;
  18814. };
  18815. /**
  18816. * Returns the facetLocalPartioning array.
  18817. */
  18818. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  18819. if (!this._facetPartitioning) {
  18820. this.updateFacetData();
  18821. }
  18822. return this._facetPartitioning;
  18823. };
  18824. /**
  18825. * Returns the i-th facet position in the world system.
  18826. * This method allocates a new Vector3 per call.
  18827. */
  18828. AbstractMesh.prototype.getFacetPosition = function (i) {
  18829. var pos = BABYLON.Vector3.Zero();
  18830. this.getFacetPositionToRef(i, pos);
  18831. return pos;
  18832. };
  18833. /**
  18834. * Sets the reference Vector3 with the i-th facet position in the world system.
  18835. * Returns the AbstractMesh.
  18836. */
  18837. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  18838. var localPos = (this.getFacetLocalPositions())[i];
  18839. var world = this.getWorldMatrix();
  18840. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  18841. return this;
  18842. };
  18843. /**
  18844. * Returns the i-th facet normal in the world system.
  18845. * This method allocates a new Vector3 per call.
  18846. */
  18847. AbstractMesh.prototype.getFacetNormal = function (i) {
  18848. var norm = BABYLON.Vector3.Zero();
  18849. this.getFacetNormalToRef(i, norm);
  18850. return norm;
  18851. };
  18852. /**
  18853. * Sets the reference Vector3 with the i-th facet normal in the world system.
  18854. * Returns the AbstractMesh.
  18855. */
  18856. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  18857. var localNorm = (this.getFacetLocalNormals())[i];
  18858. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  18859. return this;
  18860. };
  18861. /**
  18862. * Returns the facets (in an array) in the same partitioning block than the one the passed coordinates are located (expressed in the mesh local system).
  18863. */
  18864. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  18865. var bInfo = this.getBoundingInfo();
  18866. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  18867. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  18868. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  18869. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  18870. return null;
  18871. }
  18872. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  18873. };
  18874. /**
  18875. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  18876. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  18877. * If checkFace is true (default false), only the facet "facing" to (x,y,z) or only the ones "turning their backs", according to the parameter "facing" are returned.
  18878. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  18879. * If facing si false and checkFace is true, only the facet "turning their backs" to (x, y, z) are returned : negative dot (x, y, z) * facet position.
  18880. */
  18881. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  18882. if (checkFace === void 0) { checkFace = false; }
  18883. if (facing === void 0) { facing = true; }
  18884. var world = this.getWorldMatrix();
  18885. var invMat = BABYLON.Tmp.Matrix[5];
  18886. world.invertToRef(invMat);
  18887. var invVect = BABYLON.Tmp.Vector3[8];
  18888. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  18889. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  18890. if (projected) {
  18891. // tranform the local computed projected vector to world coordinates
  18892. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  18893. }
  18894. return closest;
  18895. };
  18896. /**
  18897. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  18898. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  18899. * If checkFace is true (default false), only the facet "facing" to (x,y,z) or only the ones "turning their backs", according to the parameter "facing" are returned.
  18900. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  18901. * If facing si false and checkFace is true, only the facet "turning their backs" to (x, y, z) are returned : negative dot (x, y, z) * facet position.
  18902. */
  18903. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  18904. if (checkFace === void 0) { checkFace = false; }
  18905. if (facing === void 0) { facing = true; }
  18906. var closest = null;
  18907. var tmpx = 0.0;
  18908. var tmpy = 0.0;
  18909. var tmpz = 0.0;
  18910. var d = 0.0; // tmp dot facet normal * facet position
  18911. var t0 = 0.0;
  18912. var projx = 0.0;
  18913. var projy = 0.0;
  18914. var projz = 0.0;
  18915. // Get all the facets in the same partitioning block than (x, y, z)
  18916. var facetPositions = this.getFacetLocalPositions();
  18917. var facetNormals = this.getFacetLocalNormals();
  18918. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  18919. if (!facetsInBlock) {
  18920. return null;
  18921. }
  18922. // Get the closest facet to (x, y, z)
  18923. var shortest = Number.MAX_VALUE; // init distance vars
  18924. var tmpDistance = shortest;
  18925. var fib; // current facet in the block
  18926. var norm; // current facet normal
  18927. var p0; // current facet barycenter position
  18928. // loop on all the facets in the current partitioning block
  18929. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  18930. fib = facetsInBlock[idx];
  18931. norm = facetNormals[fib];
  18932. p0 = facetPositions[fib];
  18933. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  18934. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  18935. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  18936. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  18937. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  18938. projx = x + norm.x * t0;
  18939. projy = y + norm.y * t0;
  18940. projz = z + norm.z * t0;
  18941. tmpx = projx - x;
  18942. tmpy = projy - y;
  18943. tmpz = projz - z;
  18944. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  18945. if (tmpDistance < shortest) {
  18946. shortest = tmpDistance;
  18947. closest = fib;
  18948. if (projected) {
  18949. projected.x = projx;
  18950. projected.y = projy;
  18951. projected.z = projz;
  18952. }
  18953. }
  18954. }
  18955. }
  18956. return closest;
  18957. };
  18958. /**
  18959. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  18960. */
  18961. AbstractMesh.prototype.getFacetDataParameters = function () {
  18962. return this._facetParameters;
  18963. };
  18964. /**
  18965. * Disables the feature FacetData and frees the related memory.
  18966. * Returns the AbstractMesh.
  18967. */
  18968. AbstractMesh.prototype.disableFacetData = function () {
  18969. if (this._facetDataEnabled) {
  18970. this._facetDataEnabled = false;
  18971. this._facetPositions = new Array();
  18972. this._facetNormals = new Array();
  18973. this._facetPartitioning = new Array();
  18974. this._facetParameters = null;
  18975. this._depthSortedIndices = new Uint32Array(0);
  18976. }
  18977. return this;
  18978. };
  18979. /**
  18980. * Updates the AbstractMesh indices array. Actually, used by the Mesh object.
  18981. * Returns the mesh.
  18982. */
  18983. AbstractMesh.prototype.updateIndices = function (indices) {
  18984. return this;
  18985. };
  18986. /**
  18987. * The mesh Geometry. Actually used by the Mesh object.
  18988. * Returns a blank geometry object.
  18989. */
  18990. /**
  18991. * Creates new normals data for the mesh.
  18992. * @param updatable.
  18993. */
  18994. AbstractMesh.prototype.createNormals = function (updatable) {
  18995. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18996. var indices = this.getIndices();
  18997. var normals;
  18998. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  18999. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  19000. }
  19001. else {
  19002. normals = [];
  19003. }
  19004. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  19005. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  19006. };
  19007. /**
  19008. * Align the mesh with a normal.
  19009. * Returns the mesh.
  19010. */
  19011. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  19012. if (!upDirection) {
  19013. upDirection = BABYLON.Axis.Y;
  19014. }
  19015. var axisX = BABYLON.Tmp.Vector3[0];
  19016. var axisZ = BABYLON.Tmp.Vector3[1];
  19017. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  19018. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  19019. if (this.rotationQuaternion) {
  19020. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  19021. }
  19022. else {
  19023. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  19024. }
  19025. return this;
  19026. };
  19027. AbstractMesh.prototype.checkOcclusionQuery = function () {
  19028. var engine = this.getEngine();
  19029. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  19030. this._isOccluded = false;
  19031. return;
  19032. }
  19033. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  19034. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  19035. if (isOcclusionQueryAvailable) {
  19036. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  19037. this._isOcclusionQueryInProgress = false;
  19038. this._occlusionInternalRetryCounter = 0;
  19039. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  19040. }
  19041. else {
  19042. this._occlusionInternalRetryCounter++;
  19043. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  19044. this._isOcclusionQueryInProgress = false;
  19045. this._occlusionInternalRetryCounter = 0;
  19046. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  19047. // if strict continue the last state of the object.
  19048. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  19049. }
  19050. else {
  19051. return;
  19052. }
  19053. }
  19054. }
  19055. var scene = this.getScene();
  19056. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  19057. if (!this._occlusionQuery) {
  19058. this._occlusionQuery = engine.createQuery();
  19059. }
  19060. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  19061. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  19062. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  19063. this._isOcclusionQueryInProgress = true;
  19064. };
  19065. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  19066. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  19067. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  19068. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  19069. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  19070. return AbstractMesh;
  19071. }(BABYLON.TransformNode));
  19072. BABYLON.AbstractMesh = AbstractMesh;
  19073. })(BABYLON || (BABYLON = {}));
  19074. //# sourceMappingURL=babylon.abstractMesh.js.map
  19075. var BABYLON;
  19076. (function (BABYLON) {
  19077. /**
  19078. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  19079. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  19080. * All meshes allow light to pass through them unless shadow generation is activated. The default number of lights allowed is four but this can be increased.
  19081. */
  19082. var Light = /** @class */ (function (_super) {
  19083. __extends(Light, _super);
  19084. /**
  19085. * Creates a Light object in the scene.
  19086. * Documentation : http://doc.babylonjs.com/tutorials/lights
  19087. * @param name The firendly name of the light
  19088. * @param scene The scene the light belongs too
  19089. */
  19090. function Light(name, scene) {
  19091. var _this = _super.call(this, name, scene) || this;
  19092. /**
  19093. * Diffuse gives the basic color to an object.
  19094. */
  19095. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  19096. /**
  19097. * Specular produces a highlight color on an object.
  19098. * Note: This is note affecting PBR materials.
  19099. */
  19100. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  19101. /**
  19102. * Strength of the light.
  19103. * Note: By default it is define in the framework own unit.
  19104. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  19105. */
  19106. _this.intensity = 1.0;
  19107. /**
  19108. * Defines how far from the source the light is impacting in scene units.
  19109. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  19110. */
  19111. _this.range = Number.MAX_VALUE;
  19112. /**
  19113. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  19114. * of light.
  19115. */
  19116. _this._photometricScale = 1.0;
  19117. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  19118. _this._radius = 0.00001;
  19119. /**
  19120. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  19121. * exceeding the number allowed of the materials.
  19122. */
  19123. _this.renderPriority = 0;
  19124. /**
  19125. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  19126. * the current shadow generator.
  19127. */
  19128. _this.shadowEnabled = true;
  19129. _this._excludeWithLayerMask = 0;
  19130. _this._includeOnlyWithLayerMask = 0;
  19131. _this._lightmapMode = 0;
  19132. /**
  19133. * @ignore Internal use only.
  19134. */
  19135. _this._excludedMeshesIds = new Array();
  19136. /**
  19137. * @ignore Internal use only.
  19138. */
  19139. _this._includedOnlyMeshesIds = new Array();
  19140. _this.getScene().addLight(_this);
  19141. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  19142. _this._buildUniformLayout();
  19143. _this.includedOnlyMeshes = new Array();
  19144. _this.excludedMeshes = new Array();
  19145. _this._resyncMeshes();
  19146. return _this;
  19147. }
  19148. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  19149. /**
  19150. * If every light affecting the material is in this lightmapMode,
  19151. * material.lightmapTexture adds or multiplies
  19152. * (depends on material.useLightmapAsShadowmap)
  19153. * after every other light calculations.
  19154. */
  19155. get: function () {
  19156. return Light._LIGHTMAP_DEFAULT;
  19157. },
  19158. enumerable: true,
  19159. configurable: true
  19160. });
  19161. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  19162. /**
  19163. * material.lightmapTexture as only diffuse lighting from this light
  19164. * adds only specular lighting from this light
  19165. * adds dynamic shadows
  19166. */
  19167. get: function () {
  19168. return Light._LIGHTMAP_SPECULAR;
  19169. },
  19170. enumerable: true,
  19171. configurable: true
  19172. });
  19173. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  19174. /**
  19175. * material.lightmapTexture as only lighting
  19176. * no light calculation from this light
  19177. * only adds dynamic shadows from this light
  19178. */
  19179. get: function () {
  19180. return Light._LIGHTMAP_SHADOWSONLY;
  19181. },
  19182. enumerable: true,
  19183. configurable: true
  19184. });
  19185. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  19186. /**
  19187. * Each light type uses the default quantity according to its type:
  19188. * point/spot lights use luminous intensity
  19189. * directional lights use illuminance
  19190. */
  19191. get: function () {
  19192. return Light._INTENSITYMODE_AUTOMATIC;
  19193. },
  19194. enumerable: true,
  19195. configurable: true
  19196. });
  19197. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  19198. /**
  19199. * lumen (lm)
  19200. */
  19201. get: function () {
  19202. return Light._INTENSITYMODE_LUMINOUSPOWER;
  19203. },
  19204. enumerable: true,
  19205. configurable: true
  19206. });
  19207. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  19208. /**
  19209. * candela (lm/sr)
  19210. */
  19211. get: function () {
  19212. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  19213. },
  19214. enumerable: true,
  19215. configurable: true
  19216. });
  19217. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  19218. /**
  19219. * lux (lm/m^2)
  19220. */
  19221. get: function () {
  19222. return Light._INTENSITYMODE_ILLUMINANCE;
  19223. },
  19224. enumerable: true,
  19225. configurable: true
  19226. });
  19227. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  19228. /**
  19229. * nit (cd/m^2)
  19230. */
  19231. get: function () {
  19232. return Light._INTENSITYMODE_LUMINANCE;
  19233. },
  19234. enumerable: true,
  19235. configurable: true
  19236. });
  19237. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  19238. /**
  19239. * Light type const id of the point light.
  19240. */
  19241. get: function () {
  19242. return Light._LIGHTTYPEID_POINTLIGHT;
  19243. },
  19244. enumerable: true,
  19245. configurable: true
  19246. });
  19247. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  19248. /**
  19249. * Light type const id of the directional light.
  19250. */
  19251. get: function () {
  19252. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  19253. },
  19254. enumerable: true,
  19255. configurable: true
  19256. });
  19257. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  19258. /**
  19259. * Light type const id of the spot light.
  19260. */
  19261. get: function () {
  19262. return Light._LIGHTTYPEID_SPOTLIGHT;
  19263. },
  19264. enumerable: true,
  19265. configurable: true
  19266. });
  19267. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  19268. /**
  19269. * Light type const id of the hemispheric light.
  19270. */
  19271. get: function () {
  19272. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  19273. },
  19274. enumerable: true,
  19275. configurable: true
  19276. });
  19277. Object.defineProperty(Light.prototype, "intensityMode", {
  19278. /**
  19279. * Gets the photometric scale used to interpret the intensity.
  19280. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  19281. */
  19282. get: function () {
  19283. return this._intensityMode;
  19284. },
  19285. /**
  19286. * Sets the photometric scale used to interpret the intensity.
  19287. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  19288. */
  19289. set: function (value) {
  19290. this._intensityMode = value;
  19291. this._computePhotometricScale();
  19292. },
  19293. enumerable: true,
  19294. configurable: true
  19295. });
  19296. ;
  19297. ;
  19298. Object.defineProperty(Light.prototype, "radius", {
  19299. /**
  19300. * Gets the light radius used by PBR Materials to simulate soft area lights.
  19301. */
  19302. get: function () {
  19303. return this._radius;
  19304. },
  19305. /**
  19306. * sets the light radius used by PBR Materials to simulate soft area lights.
  19307. */
  19308. set: function (value) {
  19309. this._radius = value;
  19310. this._computePhotometricScale();
  19311. },
  19312. enumerable: true,
  19313. configurable: true
  19314. });
  19315. ;
  19316. ;
  19317. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  19318. /**
  19319. * Gets the only meshes impacted by this light.
  19320. */
  19321. get: function () {
  19322. return this._includedOnlyMeshes;
  19323. },
  19324. /**
  19325. * Sets the only meshes impacted by this light.
  19326. */
  19327. set: function (value) {
  19328. this._includedOnlyMeshes = value;
  19329. this._hookArrayForIncludedOnly(value);
  19330. },
  19331. enumerable: true,
  19332. configurable: true
  19333. });
  19334. Object.defineProperty(Light.prototype, "excludedMeshes", {
  19335. /**
  19336. * Gets the meshes not impacted by this light.
  19337. */
  19338. get: function () {
  19339. return this._excludedMeshes;
  19340. },
  19341. /**
  19342. * Sets the meshes not impacted by this light.
  19343. */
  19344. set: function (value) {
  19345. this._excludedMeshes = value;
  19346. this._hookArrayForExcluded(value);
  19347. },
  19348. enumerable: true,
  19349. configurable: true
  19350. });
  19351. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  19352. /**
  19353. * Gets the layer id use to find what meshes are not impacted by the light.
  19354. * Inactive if 0
  19355. */
  19356. get: function () {
  19357. return this._excludeWithLayerMask;
  19358. },
  19359. /**
  19360. * Sets the layer id use to find what meshes are not impacted by the light.
  19361. * Inactive if 0
  19362. */
  19363. set: function (value) {
  19364. this._excludeWithLayerMask = value;
  19365. this._resyncMeshes();
  19366. },
  19367. enumerable: true,
  19368. configurable: true
  19369. });
  19370. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  19371. /**
  19372. * Gets the layer id use to find what meshes are impacted by the light.
  19373. * Inactive if 0
  19374. */
  19375. get: function () {
  19376. return this._includeOnlyWithLayerMask;
  19377. },
  19378. /**
  19379. * Sets the layer id use to find what meshes are impacted by the light.
  19380. * Inactive if 0
  19381. */
  19382. set: function (value) {
  19383. this._includeOnlyWithLayerMask = value;
  19384. this._resyncMeshes();
  19385. },
  19386. enumerable: true,
  19387. configurable: true
  19388. });
  19389. Object.defineProperty(Light.prototype, "lightmapMode", {
  19390. /**
  19391. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  19392. */
  19393. get: function () {
  19394. return this._lightmapMode;
  19395. },
  19396. /**
  19397. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  19398. */
  19399. set: function (value) {
  19400. if (this._lightmapMode === value) {
  19401. return;
  19402. }
  19403. this._lightmapMode = value;
  19404. this._markMeshesAsLightDirty();
  19405. },
  19406. enumerable: true,
  19407. configurable: true
  19408. });
  19409. /**
  19410. * Returns the string "Light".
  19411. * @returns the class name
  19412. */
  19413. Light.prototype.getClassName = function () {
  19414. return "Light";
  19415. };
  19416. /**
  19417. * Converts the light information to a readable string for debug purpose.
  19418. * @param fullDetails Supports for multiple levels of logging within scene loading
  19419. * @returns the human readable light info
  19420. */
  19421. Light.prototype.toString = function (fullDetails) {
  19422. var ret = "Name: " + this.name;
  19423. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  19424. if (this.animations) {
  19425. for (var i = 0; i < this.animations.length; i++) {
  19426. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  19427. }
  19428. }
  19429. if (fullDetails) {
  19430. }
  19431. return ret;
  19432. };
  19433. /**
  19434. * Set the enabled state of this node.
  19435. * @param value - the new enabled state
  19436. * @see isEnabled
  19437. */
  19438. Light.prototype.setEnabled = function (value) {
  19439. _super.prototype.setEnabled.call(this, value);
  19440. this._resyncMeshes();
  19441. };
  19442. /**
  19443. * Returns the Light associated shadow generator if any.
  19444. * @return the associated shadow generator.
  19445. */
  19446. Light.prototype.getShadowGenerator = function () {
  19447. return this._shadowGenerator;
  19448. };
  19449. /**
  19450. * Returns a Vector3, the absolute light position in the World.
  19451. * @returns the world space position of the light
  19452. */
  19453. Light.prototype.getAbsolutePosition = function () {
  19454. return BABYLON.Vector3.Zero();
  19455. };
  19456. /**
  19457. * Specifies if the light will affect the passed mesh.
  19458. * @param mesh The mesh to test against the light
  19459. * @return true the mesh is affected otherwise, false.
  19460. */
  19461. Light.prototype.canAffectMesh = function (mesh) {
  19462. if (!mesh) {
  19463. return true;
  19464. }
  19465. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  19466. return false;
  19467. }
  19468. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  19469. return false;
  19470. }
  19471. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  19472. return false;
  19473. }
  19474. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  19475. return false;
  19476. }
  19477. return true;
  19478. };
  19479. /**
  19480. * Computes and Returns the light World matrix.
  19481. * @returns the world matrix
  19482. */
  19483. Light.prototype.getWorldMatrix = function () {
  19484. this._currentRenderId = this.getScene().getRenderId();
  19485. var worldMatrix = this._getWorldMatrix();
  19486. if (this.parent && this.parent.getWorldMatrix) {
  19487. if (!this._parentedWorldMatrix) {
  19488. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  19489. }
  19490. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  19491. this._markSyncedWithParent();
  19492. return this._parentedWorldMatrix;
  19493. }
  19494. return worldMatrix;
  19495. };
  19496. /**
  19497. * Sort function to order lights for rendering.
  19498. * @param a First Light object to compare to second.
  19499. * @param b Second Light object to compare first.
  19500. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  19501. */
  19502. Light.CompareLightsPriority = function (a, b) {
  19503. //shadow-casting lights have priority over non-shadow-casting lights
  19504. //the renderPrioirty is a secondary sort criterion
  19505. if (a.shadowEnabled !== b.shadowEnabled) {
  19506. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  19507. }
  19508. return b.renderPriority - a.renderPriority;
  19509. };
  19510. /**
  19511. * Releases resources associated with this node.
  19512. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  19513. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  19514. */
  19515. Light.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  19516. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  19517. if (this._shadowGenerator) {
  19518. this._shadowGenerator.dispose();
  19519. this._shadowGenerator = null;
  19520. }
  19521. // Animations
  19522. this.getScene().stopAnimation(this);
  19523. // Remove from meshes
  19524. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  19525. var mesh = _a[_i];
  19526. mesh._removeLightSource(this);
  19527. }
  19528. this._uniformBuffer.dispose();
  19529. // Remove from scene
  19530. this.getScene().removeLight(this);
  19531. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  19532. };
  19533. /**
  19534. * Returns the light type ID (integer).
  19535. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  19536. */
  19537. Light.prototype.getTypeID = function () {
  19538. return 0;
  19539. };
  19540. /**
  19541. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  19542. * @returns the scaled intensity in intensity mode unit
  19543. */
  19544. Light.prototype.getScaledIntensity = function () {
  19545. return this._photometricScale * this.intensity;
  19546. };
  19547. /**
  19548. * Returns a new Light object, named "name", from the current one.
  19549. * @param name The name of the cloned light
  19550. * @returns the new created light
  19551. */
  19552. Light.prototype.clone = function (name) {
  19553. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  19554. if (!constructor) {
  19555. return null;
  19556. }
  19557. return BABYLON.SerializationHelper.Clone(constructor, this);
  19558. };
  19559. /**
  19560. * Serializes the current light into a Serialization object.
  19561. * @returns the serialized object.
  19562. */
  19563. Light.prototype.serialize = function () {
  19564. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  19565. // Type
  19566. serializationObject.type = this.getTypeID();
  19567. // Parent
  19568. if (this.parent) {
  19569. serializationObject.parentId = this.parent.id;
  19570. }
  19571. // Inclusion / exclusions
  19572. if (this.excludedMeshes.length > 0) {
  19573. serializationObject.excludedMeshesIds = [];
  19574. this.excludedMeshes.forEach(function (mesh) {
  19575. serializationObject.excludedMeshesIds.push(mesh.id);
  19576. });
  19577. }
  19578. if (this.includedOnlyMeshes.length > 0) {
  19579. serializationObject.includedOnlyMeshesIds = [];
  19580. this.includedOnlyMeshes.forEach(function (mesh) {
  19581. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  19582. });
  19583. }
  19584. // Animations
  19585. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  19586. serializationObject.ranges = this.serializeAnimationRanges();
  19587. return serializationObject;
  19588. };
  19589. /**
  19590. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  19591. * This new light is named "name" and added to the passed scene.
  19592. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  19593. * @param name The friendly name of the light
  19594. * @param scene The scene the new light will belong to
  19595. * @returns the constructor function
  19596. */
  19597. Light.GetConstructorFromName = function (type, name, scene) {
  19598. switch (type) {
  19599. case 0:
  19600. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  19601. case 1:
  19602. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  19603. case 2:
  19604. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  19605. case 3:
  19606. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  19607. }
  19608. return null;
  19609. };
  19610. /**
  19611. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  19612. * @param parsedLight The JSON representation of the light
  19613. * @param scene The scene to create the parsed light in
  19614. * @returns the created light after parsing
  19615. */
  19616. Light.Parse = function (parsedLight, scene) {
  19617. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  19618. if (!constructor) {
  19619. return null;
  19620. }
  19621. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  19622. // Inclusion / exclusions
  19623. if (parsedLight.excludedMeshesIds) {
  19624. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  19625. }
  19626. if (parsedLight.includedOnlyMeshesIds) {
  19627. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  19628. }
  19629. // Parent
  19630. if (parsedLight.parentId) {
  19631. light._waitingParentId = parsedLight.parentId;
  19632. }
  19633. // Animations
  19634. if (parsedLight.animations) {
  19635. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  19636. var parsedAnimation = parsedLight.animations[animationIndex];
  19637. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  19638. }
  19639. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  19640. }
  19641. if (parsedLight.autoAnimate) {
  19642. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  19643. }
  19644. return light;
  19645. };
  19646. Light.prototype._hookArrayForExcluded = function (array) {
  19647. var _this = this;
  19648. var oldPush = array.push;
  19649. array.push = function () {
  19650. var items = [];
  19651. for (var _i = 0; _i < arguments.length; _i++) {
  19652. items[_i] = arguments[_i];
  19653. }
  19654. var result = oldPush.apply(array, items);
  19655. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  19656. var item = items_1[_a];
  19657. item._resyncLighSource(_this);
  19658. }
  19659. return result;
  19660. };
  19661. var oldSplice = array.splice;
  19662. array.splice = function (index, deleteCount) {
  19663. var deleted = oldSplice.apply(array, [index, deleteCount]);
  19664. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  19665. var item = deleted_1[_i];
  19666. item._resyncLighSource(_this);
  19667. }
  19668. return deleted;
  19669. };
  19670. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  19671. var item = array_1[_i];
  19672. item._resyncLighSource(this);
  19673. }
  19674. };
  19675. Light.prototype._hookArrayForIncludedOnly = function (array) {
  19676. var _this = this;
  19677. var oldPush = array.push;
  19678. array.push = function () {
  19679. var items = [];
  19680. for (var _i = 0; _i < arguments.length; _i++) {
  19681. items[_i] = arguments[_i];
  19682. }
  19683. var result = oldPush.apply(array, items);
  19684. _this._resyncMeshes();
  19685. return result;
  19686. };
  19687. var oldSplice = array.splice;
  19688. array.splice = function (index, deleteCount) {
  19689. var deleted = oldSplice.apply(array, [index, deleteCount]);
  19690. _this._resyncMeshes();
  19691. return deleted;
  19692. };
  19693. this._resyncMeshes();
  19694. };
  19695. Light.prototype._resyncMeshes = function () {
  19696. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  19697. var mesh = _a[_i];
  19698. mesh._resyncLighSource(this);
  19699. }
  19700. };
  19701. /**
  19702. * Forces the meshes to update their light related information in their rendering used effects
  19703. * @ignore Internal Use Only
  19704. */
  19705. Light.prototype._markMeshesAsLightDirty = function () {
  19706. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  19707. var mesh = _a[_i];
  19708. if (mesh._lightSources.indexOf(this) !== -1) {
  19709. mesh._markSubMeshesAsLightDirty();
  19710. }
  19711. }
  19712. };
  19713. /**
  19714. * Recomputes the cached photometric scale if needed.
  19715. */
  19716. Light.prototype._computePhotometricScale = function () {
  19717. this._photometricScale = this._getPhotometricScale();
  19718. this.getScene().resetCachedMaterial();
  19719. };
  19720. /**
  19721. * Returns the Photometric Scale according to the light type and intensity mode.
  19722. */
  19723. Light.prototype._getPhotometricScale = function () {
  19724. var photometricScale = 0.0;
  19725. var lightTypeID = this.getTypeID();
  19726. //get photometric mode
  19727. var photometricMode = this.intensityMode;
  19728. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  19729. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  19730. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  19731. }
  19732. else {
  19733. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  19734. }
  19735. }
  19736. //compute photometric scale
  19737. switch (lightTypeID) {
  19738. case Light.LIGHTTYPEID_POINTLIGHT:
  19739. case Light.LIGHTTYPEID_SPOTLIGHT:
  19740. switch (photometricMode) {
  19741. case Light.INTENSITYMODE_LUMINOUSPOWER:
  19742. photometricScale = 1.0 / (4.0 * Math.PI);
  19743. break;
  19744. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  19745. photometricScale = 1.0;
  19746. break;
  19747. case Light.INTENSITYMODE_LUMINANCE:
  19748. photometricScale = this.radius * this.radius;
  19749. break;
  19750. }
  19751. break;
  19752. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  19753. switch (photometricMode) {
  19754. case Light.INTENSITYMODE_ILLUMINANCE:
  19755. photometricScale = 1.0;
  19756. break;
  19757. case Light.INTENSITYMODE_LUMINANCE:
  19758. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  19759. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  19760. var apexAngleRadians = this.radius;
  19761. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  19762. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  19763. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  19764. photometricScale = solidAngle;
  19765. break;
  19766. }
  19767. break;
  19768. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  19769. // No fall off in hemisperic light.
  19770. photometricScale = 1.0;
  19771. break;
  19772. }
  19773. return photometricScale;
  19774. };
  19775. /**
  19776. * Reorder the light in the scene according to their defined priority.
  19777. * @ignore Internal Use Only
  19778. */
  19779. Light.prototype._reorderLightsInScene = function () {
  19780. var scene = this.getScene();
  19781. if (this._renderPriority != 0) {
  19782. scene.requireLightSorting = true;
  19783. }
  19784. this.getScene().sortLightsByPriority();
  19785. };
  19786. //lightmapMode Consts
  19787. Light._LIGHTMAP_DEFAULT = 0;
  19788. Light._LIGHTMAP_SPECULAR = 1;
  19789. Light._LIGHTMAP_SHADOWSONLY = 2;
  19790. // Intensity Mode Consts
  19791. Light._INTENSITYMODE_AUTOMATIC = 0;
  19792. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  19793. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  19794. Light._INTENSITYMODE_ILLUMINANCE = 3;
  19795. Light._INTENSITYMODE_LUMINANCE = 4;
  19796. // Light types ids const.
  19797. Light._LIGHTTYPEID_POINTLIGHT = 0;
  19798. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  19799. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  19800. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  19801. __decorate([
  19802. BABYLON.serializeAsColor3()
  19803. ], Light.prototype, "diffuse", void 0);
  19804. __decorate([
  19805. BABYLON.serializeAsColor3()
  19806. ], Light.prototype, "specular", void 0);
  19807. __decorate([
  19808. BABYLON.serialize()
  19809. ], Light.prototype, "intensity", void 0);
  19810. __decorate([
  19811. BABYLON.serialize()
  19812. ], Light.prototype, "range", void 0);
  19813. __decorate([
  19814. BABYLON.serialize()
  19815. ], Light.prototype, "intensityMode", null);
  19816. __decorate([
  19817. BABYLON.serialize()
  19818. ], Light.prototype, "radius", null);
  19819. __decorate([
  19820. BABYLON.serialize()
  19821. ], Light.prototype, "_renderPriority", void 0);
  19822. __decorate([
  19823. BABYLON.expandToProperty("_reorderLightsInScene")
  19824. ], Light.prototype, "renderPriority", void 0);
  19825. __decorate([
  19826. BABYLON.serialize()
  19827. ], Light.prototype, "shadowEnabled", void 0);
  19828. __decorate([
  19829. BABYLON.serialize("excludeWithLayerMask")
  19830. ], Light.prototype, "_excludeWithLayerMask", void 0);
  19831. __decorate([
  19832. BABYLON.serialize("includeOnlyWithLayerMask")
  19833. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  19834. __decorate([
  19835. BABYLON.serialize("lightmapMode")
  19836. ], Light.prototype, "_lightmapMode", void 0);
  19837. return Light;
  19838. }(BABYLON.Node));
  19839. BABYLON.Light = Light;
  19840. })(BABYLON || (BABYLON = {}));
  19841. //# sourceMappingURL=babylon.light.js.map
  19842. var BABYLON;
  19843. (function (BABYLON) {
  19844. var Camera = /** @class */ (function (_super) {
  19845. __extends(Camera, _super);
  19846. function Camera(name, position, scene) {
  19847. var _this = _super.call(this, name, scene) || this;
  19848. /**
  19849. * The vector the camera should consider as up.
  19850. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  19851. */
  19852. _this.upVector = BABYLON.Vector3.Up();
  19853. _this.orthoLeft = null;
  19854. _this.orthoRight = null;
  19855. _this.orthoBottom = null;
  19856. _this.orthoTop = null;
  19857. /**
  19858. * FOV is set in Radians. (default is 0.8)
  19859. */
  19860. _this.fov = 0.8;
  19861. _this.minZ = 1;
  19862. _this.maxZ = 10000.0;
  19863. _this.inertia = 0.9;
  19864. _this.mode = Camera.PERSPECTIVE_CAMERA;
  19865. _this.isIntermediate = false;
  19866. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  19867. /**
  19868. * Restricts the camera to viewing objects with the same layerMask.
  19869. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  19870. */
  19871. _this.layerMask = 0x0FFFFFFF;
  19872. /**
  19873. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  19874. */
  19875. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  19876. // Camera rig members
  19877. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  19878. _this._rigCameras = new Array();
  19879. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  19880. _this._skipRendering = false;
  19881. _this.customRenderTargets = new Array();
  19882. // Observables
  19883. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  19884. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  19885. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  19886. _this.onRestoreStateObservable = new BABYLON.Observable();
  19887. // Cache
  19888. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  19889. _this._projectionMatrix = new BABYLON.Matrix();
  19890. _this._doNotComputeProjectionMatrix = false;
  19891. _this._postProcesses = new Array();
  19892. _this._transformMatrix = BABYLON.Matrix.Zero();
  19893. _this._activeMeshes = new BABYLON.SmartArray(256);
  19894. _this._globalPosition = BABYLON.Vector3.Zero();
  19895. _this._refreshFrustumPlanes = true;
  19896. _this.getScene().addCamera(_this);
  19897. if (!_this.getScene().activeCamera) {
  19898. _this.getScene().activeCamera = _this;
  19899. }
  19900. _this.position = position;
  19901. return _this;
  19902. }
  19903. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  19904. get: function () {
  19905. return Camera._PERSPECTIVE_CAMERA;
  19906. },
  19907. enumerable: true,
  19908. configurable: true
  19909. });
  19910. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  19911. get: function () {
  19912. return Camera._ORTHOGRAPHIC_CAMERA;
  19913. },
  19914. enumerable: true,
  19915. configurable: true
  19916. });
  19917. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  19918. /**
  19919. * This is the default FOV mode for perspective cameras.
  19920. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  19921. *
  19922. */
  19923. get: function () {
  19924. return Camera._FOVMODE_VERTICAL_FIXED;
  19925. },
  19926. enumerable: true,
  19927. configurable: true
  19928. });
  19929. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  19930. /**
  19931. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  19932. *
  19933. */
  19934. get: function () {
  19935. return Camera._FOVMODE_HORIZONTAL_FIXED;
  19936. },
  19937. enumerable: true,
  19938. configurable: true
  19939. });
  19940. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  19941. get: function () {
  19942. return Camera._RIG_MODE_NONE;
  19943. },
  19944. enumerable: true,
  19945. configurable: true
  19946. });
  19947. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  19948. get: function () {
  19949. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  19950. },
  19951. enumerable: true,
  19952. configurable: true
  19953. });
  19954. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  19955. get: function () {
  19956. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  19957. },
  19958. enumerable: true,
  19959. configurable: true
  19960. });
  19961. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  19962. get: function () {
  19963. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  19964. },
  19965. enumerable: true,
  19966. configurable: true
  19967. });
  19968. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  19969. get: function () {
  19970. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  19971. },
  19972. enumerable: true,
  19973. configurable: true
  19974. });
  19975. Object.defineProperty(Camera, "RIG_MODE_VR", {
  19976. get: function () {
  19977. return Camera._RIG_MODE_VR;
  19978. },
  19979. enumerable: true,
  19980. configurable: true
  19981. });
  19982. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  19983. get: function () {
  19984. return Camera._RIG_MODE_WEBVR;
  19985. },
  19986. enumerable: true,
  19987. configurable: true
  19988. });
  19989. /**
  19990. * Store current camera state (fov, position, etc..)
  19991. */
  19992. Camera.prototype.storeState = function () {
  19993. this._stateStored = true;
  19994. this._storedFov = this.fov;
  19995. return this;
  19996. };
  19997. /**
  19998. * Restores the camera state values if it has been stored. You must call storeState() first
  19999. */
  20000. Camera.prototype._restoreStateValues = function () {
  20001. if (!this._stateStored) {
  20002. return false;
  20003. }
  20004. this.fov = this._storedFov;
  20005. return true;
  20006. };
  20007. /**
  20008. * Restored camera state. You must call storeState() first
  20009. */
  20010. Camera.prototype.restoreState = function () {
  20011. if (this._restoreStateValues()) {
  20012. this.onRestoreStateObservable.notifyObservers(this);
  20013. return true;
  20014. }
  20015. return false;
  20016. };
  20017. Camera.prototype.getClassName = function () {
  20018. return "Camera";
  20019. };
  20020. /**
  20021. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  20022. */
  20023. Camera.prototype.toString = function (fullDetails) {
  20024. var ret = "Name: " + this.name;
  20025. ret += ", type: " + this.getClassName();
  20026. if (this.animations) {
  20027. for (var i = 0; i < this.animations.length; i++) {
  20028. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  20029. }
  20030. }
  20031. if (fullDetails) {
  20032. }
  20033. return ret;
  20034. };
  20035. Object.defineProperty(Camera.prototype, "globalPosition", {
  20036. get: function () {
  20037. return this._globalPosition;
  20038. },
  20039. enumerable: true,
  20040. configurable: true
  20041. });
  20042. Camera.prototype.getActiveMeshes = function () {
  20043. return this._activeMeshes;
  20044. };
  20045. Camera.prototype.isActiveMesh = function (mesh) {
  20046. return (this._activeMeshes.indexOf(mesh) !== -1);
  20047. };
  20048. //Cache
  20049. Camera.prototype._initCache = function () {
  20050. _super.prototype._initCache.call(this);
  20051. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  20052. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  20053. this._cache.mode = undefined;
  20054. this._cache.minZ = undefined;
  20055. this._cache.maxZ = undefined;
  20056. this._cache.fov = undefined;
  20057. this._cache.fovMode = undefined;
  20058. this._cache.aspectRatio = undefined;
  20059. this._cache.orthoLeft = undefined;
  20060. this._cache.orthoRight = undefined;
  20061. this._cache.orthoBottom = undefined;
  20062. this._cache.orthoTop = undefined;
  20063. this._cache.renderWidth = undefined;
  20064. this._cache.renderHeight = undefined;
  20065. };
  20066. Camera.prototype._updateCache = function (ignoreParentClass) {
  20067. if (!ignoreParentClass) {
  20068. _super.prototype._updateCache.call(this);
  20069. }
  20070. this._cache.position.copyFrom(this.position);
  20071. this._cache.upVector.copyFrom(this.upVector);
  20072. };
  20073. // Synchronized
  20074. Camera.prototype._isSynchronized = function () {
  20075. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  20076. };
  20077. Camera.prototype._isSynchronizedViewMatrix = function () {
  20078. if (!_super.prototype._isSynchronized.call(this))
  20079. return false;
  20080. return this._cache.position.equals(this.position)
  20081. && this._cache.upVector.equals(this.upVector)
  20082. && this.isSynchronizedWithParent();
  20083. };
  20084. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  20085. var check = this._cache.mode === this.mode
  20086. && this._cache.minZ === this.minZ
  20087. && this._cache.maxZ === this.maxZ;
  20088. if (!check) {
  20089. return false;
  20090. }
  20091. var engine = this.getEngine();
  20092. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  20093. check = this._cache.fov === this.fov
  20094. && this._cache.fovMode === this.fovMode
  20095. && this._cache.aspectRatio === engine.getAspectRatio(this);
  20096. }
  20097. else {
  20098. check = this._cache.orthoLeft === this.orthoLeft
  20099. && this._cache.orthoRight === this.orthoRight
  20100. && this._cache.orthoBottom === this.orthoBottom
  20101. && this._cache.orthoTop === this.orthoTop
  20102. && this._cache.renderWidth === engine.getRenderWidth()
  20103. && this._cache.renderHeight === engine.getRenderHeight();
  20104. }
  20105. return check;
  20106. };
  20107. // Controls
  20108. Camera.prototype.attachControl = function (element, noPreventDefault) {
  20109. };
  20110. Camera.prototype.detachControl = function (element) {
  20111. };
  20112. Camera.prototype.update = function () {
  20113. this._checkInputs();
  20114. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  20115. this._updateRigCameras();
  20116. }
  20117. };
  20118. Camera.prototype._checkInputs = function () {
  20119. this.onAfterCheckInputsObservable.notifyObservers(this);
  20120. };
  20121. Object.defineProperty(Camera.prototype, "rigCameras", {
  20122. get: function () {
  20123. return this._rigCameras;
  20124. },
  20125. enumerable: true,
  20126. configurable: true
  20127. });
  20128. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  20129. get: function () {
  20130. return this._rigPostProcess;
  20131. },
  20132. enumerable: true,
  20133. configurable: true
  20134. });
  20135. /**
  20136. * Internal, gets the first post proces.
  20137. * @returns the first post process to be run on this camera.
  20138. */
  20139. Camera.prototype._getFirstPostProcess = function () {
  20140. for (var pp in this._postProcesses) {
  20141. if (this._postProcesses[pp] !== null) {
  20142. return this._postProcesses[pp];
  20143. }
  20144. }
  20145. return null;
  20146. };
  20147. Camera.prototype._cascadePostProcessesToRigCams = function () {
  20148. // invalidate framebuffer
  20149. var firstPostProcess = this._getFirstPostProcess();
  20150. if (firstPostProcess) {
  20151. firstPostProcess.markTextureDirty();
  20152. }
  20153. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  20154. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  20155. var cam = this._rigCameras[i];
  20156. var rigPostProcess = cam._rigPostProcess;
  20157. // for VR rig, there does not have to be a post process
  20158. if (rigPostProcess) {
  20159. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  20160. if (isPass) {
  20161. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  20162. cam.isIntermediate = this._postProcesses.length === 0;
  20163. }
  20164. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  20165. rigPostProcess.markTextureDirty();
  20166. }
  20167. else {
  20168. cam._postProcesses = this._postProcesses.slice(0);
  20169. }
  20170. }
  20171. };
  20172. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  20173. if (insertAt === void 0) { insertAt = null; }
  20174. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  20175. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  20176. return 0;
  20177. }
  20178. if (insertAt == null || insertAt < 0) {
  20179. this._postProcesses.push(postProcess);
  20180. }
  20181. else if (this._postProcesses[insertAt] === null) {
  20182. this._postProcesses[insertAt] = postProcess;
  20183. }
  20184. else {
  20185. this._postProcesses.splice(insertAt, 0, postProcess);
  20186. }
  20187. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  20188. return this._postProcesses.indexOf(postProcess);
  20189. };
  20190. Camera.prototype.detachPostProcess = function (postProcess) {
  20191. var idx = this._postProcesses.indexOf(postProcess);
  20192. if (idx !== -1) {
  20193. this._postProcesses[idx] = null;
  20194. }
  20195. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  20196. };
  20197. Camera.prototype.getWorldMatrix = function () {
  20198. if (!this._worldMatrix) {
  20199. this._worldMatrix = BABYLON.Matrix.Identity();
  20200. }
  20201. var viewMatrix = this.getViewMatrix();
  20202. viewMatrix.invertToRef(this._worldMatrix);
  20203. return this._worldMatrix;
  20204. };
  20205. Camera.prototype._getViewMatrix = function () {
  20206. return BABYLON.Matrix.Identity();
  20207. };
  20208. Camera.prototype.getViewMatrix = function (force) {
  20209. if (!force && this._isSynchronizedViewMatrix()) {
  20210. return this._computedViewMatrix;
  20211. }
  20212. this.updateCache();
  20213. this._computedViewMatrix = this._getViewMatrix();
  20214. this._currentRenderId = this.getScene().getRenderId();
  20215. this._refreshFrustumPlanes = true;
  20216. if (!this.parent || !this.parent.getWorldMatrix) {
  20217. this._globalPosition.copyFrom(this.position);
  20218. }
  20219. else {
  20220. if (!this._worldMatrix) {
  20221. this._worldMatrix = BABYLON.Matrix.Identity();
  20222. }
  20223. this._computedViewMatrix.invertToRef(this._worldMatrix);
  20224. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  20225. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  20226. this._computedViewMatrix.invert();
  20227. this._markSyncedWithParent();
  20228. }
  20229. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  20230. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  20231. }
  20232. this.onViewMatrixChangedObservable.notifyObservers(this);
  20233. return this._computedViewMatrix;
  20234. };
  20235. Camera.prototype.freezeProjectionMatrix = function (projection) {
  20236. this._doNotComputeProjectionMatrix = true;
  20237. if (projection !== undefined) {
  20238. this._projectionMatrix = projection;
  20239. }
  20240. };
  20241. ;
  20242. Camera.prototype.unfreezeProjectionMatrix = function () {
  20243. this._doNotComputeProjectionMatrix = false;
  20244. };
  20245. ;
  20246. Camera.prototype.getProjectionMatrix = function (force) {
  20247. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  20248. return this._projectionMatrix;
  20249. }
  20250. // Cache
  20251. this._cache.mode = this.mode;
  20252. this._cache.minZ = this.minZ;
  20253. this._cache.maxZ = this.maxZ;
  20254. // Matrix
  20255. this._refreshFrustumPlanes = true;
  20256. var engine = this.getEngine();
  20257. var scene = this.getScene();
  20258. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  20259. this._cache.fov = this.fov;
  20260. this._cache.fovMode = this.fovMode;
  20261. this._cache.aspectRatio = engine.getAspectRatio(this);
  20262. if (this.minZ <= 0) {
  20263. this.minZ = 0.1;
  20264. }
  20265. if (scene.useRightHandedSystem) {
  20266. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  20267. }
  20268. else {
  20269. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  20270. }
  20271. }
  20272. else {
  20273. var halfWidth = engine.getRenderWidth() / 2.0;
  20274. var halfHeight = engine.getRenderHeight() / 2.0;
  20275. if (scene.useRightHandedSystem) {
  20276. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  20277. }
  20278. else {
  20279. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  20280. }
  20281. this._cache.orthoLeft = this.orthoLeft;
  20282. this._cache.orthoRight = this.orthoRight;
  20283. this._cache.orthoBottom = this.orthoBottom;
  20284. this._cache.orthoTop = this.orthoTop;
  20285. this._cache.renderWidth = engine.getRenderWidth();
  20286. this._cache.renderHeight = engine.getRenderHeight();
  20287. }
  20288. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  20289. return this._projectionMatrix;
  20290. };
  20291. Camera.prototype.getTranformationMatrix = function () {
  20292. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  20293. return this._transformMatrix;
  20294. };
  20295. Camera.prototype.updateFrustumPlanes = function () {
  20296. if (!this._refreshFrustumPlanes) {
  20297. return;
  20298. }
  20299. this.getTranformationMatrix();
  20300. if (!this._frustumPlanes) {
  20301. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  20302. }
  20303. else {
  20304. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  20305. }
  20306. this._refreshFrustumPlanes = false;
  20307. };
  20308. Camera.prototype.isInFrustum = function (target) {
  20309. this.updateFrustumPlanes();
  20310. return target.isInFrustum(this._frustumPlanes);
  20311. };
  20312. Camera.prototype.isCompletelyInFrustum = function (target) {
  20313. this.updateFrustumPlanes();
  20314. return target.isCompletelyInFrustum(this._frustumPlanes);
  20315. };
  20316. Camera.prototype.getForwardRay = function (length, transform, origin) {
  20317. if (length === void 0) { length = 100; }
  20318. if (!transform) {
  20319. transform = this.getWorldMatrix();
  20320. }
  20321. if (!origin) {
  20322. origin = this.position;
  20323. }
  20324. var forward = new BABYLON.Vector3(0, 0, 1);
  20325. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  20326. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  20327. return new BABYLON.Ray(origin, direction, length);
  20328. };
  20329. /**
  20330. * Releases resources associated with this node.
  20331. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  20332. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  20333. */
  20334. Camera.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  20335. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  20336. // Observables
  20337. this.onViewMatrixChangedObservable.clear();
  20338. this.onProjectionMatrixChangedObservable.clear();
  20339. this.onAfterCheckInputsObservable.clear();
  20340. this.onRestoreStateObservable.clear();
  20341. // Inputs
  20342. if (this.inputs) {
  20343. this.inputs.clear();
  20344. }
  20345. // Animations
  20346. this.getScene().stopAnimation(this);
  20347. // Remove from scene
  20348. this.getScene().removeCamera(this);
  20349. while (this._rigCameras.length > 0) {
  20350. var camera = this._rigCameras.pop();
  20351. if (camera) {
  20352. camera.dispose();
  20353. }
  20354. }
  20355. // Postprocesses
  20356. if (this._rigPostProcess) {
  20357. this._rigPostProcess.dispose(this);
  20358. this._rigPostProcess = null;
  20359. this._postProcesses = [];
  20360. }
  20361. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  20362. this._rigPostProcess = null;
  20363. this._postProcesses = [];
  20364. }
  20365. else {
  20366. var i = this._postProcesses.length;
  20367. while (--i >= 0) {
  20368. var postProcess = this._postProcesses[i];
  20369. if (postProcess) {
  20370. postProcess.dispose(this);
  20371. }
  20372. }
  20373. }
  20374. // Render targets
  20375. var i = this.customRenderTargets.length;
  20376. while (--i >= 0) {
  20377. this.customRenderTargets[i].dispose();
  20378. }
  20379. this.customRenderTargets = [];
  20380. // Active Meshes
  20381. this._activeMeshes.dispose();
  20382. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  20383. };
  20384. Object.defineProperty(Camera.prototype, "leftCamera", {
  20385. // ---- Camera rigs section ----
  20386. get: function () {
  20387. if (this._rigCameras.length < 1) {
  20388. return null;
  20389. }
  20390. return this._rigCameras[0];
  20391. },
  20392. enumerable: true,
  20393. configurable: true
  20394. });
  20395. Object.defineProperty(Camera.prototype, "rightCamera", {
  20396. get: function () {
  20397. if (this._rigCameras.length < 2) {
  20398. return null;
  20399. }
  20400. return this._rigCameras[1];
  20401. },
  20402. enumerable: true,
  20403. configurable: true
  20404. });
  20405. Camera.prototype.getLeftTarget = function () {
  20406. if (this._rigCameras.length < 1) {
  20407. return null;
  20408. }
  20409. return this._rigCameras[0].getTarget();
  20410. };
  20411. Camera.prototype.getRightTarget = function () {
  20412. if (this._rigCameras.length < 2) {
  20413. return null;
  20414. }
  20415. return this._rigCameras[1].getTarget();
  20416. };
  20417. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  20418. if (this.cameraRigMode === mode) {
  20419. return;
  20420. }
  20421. while (this._rigCameras.length > 0) {
  20422. var camera = this._rigCameras.pop();
  20423. if (camera) {
  20424. camera.dispose();
  20425. }
  20426. }
  20427. this.cameraRigMode = mode;
  20428. this._cameraRigParams = {};
  20429. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  20430. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  20431. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  20432. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  20433. // create the rig cameras, unless none
  20434. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  20435. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  20436. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  20437. if (leftCamera && rightCamera) {
  20438. this._rigCameras.push(leftCamera);
  20439. this._rigCameras.push(rightCamera);
  20440. }
  20441. }
  20442. switch (this.cameraRigMode) {
  20443. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  20444. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  20445. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  20446. break;
  20447. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  20448. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  20449. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  20450. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  20451. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  20452. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  20453. break;
  20454. case Camera.RIG_MODE_VR:
  20455. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  20456. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  20457. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  20458. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20459. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  20460. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  20461. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  20462. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  20463. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  20464. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20465. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  20466. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  20467. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  20468. if (metrics.compensateDistortion) {
  20469. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  20470. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  20471. }
  20472. break;
  20473. case Camera.RIG_MODE_WEBVR:
  20474. if (rigParams.vrDisplay) {
  20475. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  20476. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  20477. //Left eye
  20478. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  20479. this._rigCameras[0].setCameraRigParameter("left", true);
  20480. //leaving this for future reference
  20481. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  20482. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  20483. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  20484. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  20485. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20486. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  20487. this._rigCameras[0].parent = this;
  20488. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  20489. //Right eye
  20490. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  20491. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  20492. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  20493. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  20494. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  20495. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20496. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  20497. this._rigCameras[1].parent = this;
  20498. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  20499. if (Camera.UseAlternateWebVRRendering) {
  20500. this._rigCameras[1]._skipRendering = true;
  20501. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  20502. }
  20503. }
  20504. break;
  20505. }
  20506. this._cascadePostProcessesToRigCams();
  20507. this.update();
  20508. };
  20509. Camera.prototype._getVRProjectionMatrix = function () {
  20510. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  20511. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  20512. return this._projectionMatrix;
  20513. };
  20514. Camera.prototype._updateCameraRotationMatrix = function () {
  20515. //Here for WebVR
  20516. };
  20517. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  20518. //Here for WebVR
  20519. };
  20520. /**
  20521. * This function MUST be overwritten by the different WebVR cameras available.
  20522. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  20523. */
  20524. Camera.prototype._getWebVRProjectionMatrix = function () {
  20525. return BABYLON.Matrix.Identity();
  20526. };
  20527. /**
  20528. * This function MUST be overwritten by the different WebVR cameras available.
  20529. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  20530. */
  20531. Camera.prototype._getWebVRViewMatrix = function () {
  20532. return BABYLON.Matrix.Identity();
  20533. };
  20534. Camera.prototype.setCameraRigParameter = function (name, value) {
  20535. if (!this._cameraRigParams) {
  20536. this._cameraRigParams = {};
  20537. }
  20538. this._cameraRigParams[name] = value;
  20539. //provisionnally:
  20540. if (name === "interaxialDistance") {
  20541. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  20542. }
  20543. };
  20544. /**
  20545. * needs to be overridden by children so sub has required properties to be copied
  20546. */
  20547. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  20548. return null;
  20549. };
  20550. /**
  20551. * May need to be overridden by children
  20552. */
  20553. Camera.prototype._updateRigCameras = function () {
  20554. for (var i = 0; i < this._rigCameras.length; i++) {
  20555. this._rigCameras[i].minZ = this.minZ;
  20556. this._rigCameras[i].maxZ = this.maxZ;
  20557. this._rigCameras[i].fov = this.fov;
  20558. }
  20559. // only update viewport when ANAGLYPH
  20560. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  20561. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  20562. }
  20563. };
  20564. Camera.prototype._setupInputs = function () {
  20565. };
  20566. Camera.prototype.serialize = function () {
  20567. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  20568. // Type
  20569. serializationObject.type = this.getClassName();
  20570. // Parent
  20571. if (this.parent) {
  20572. serializationObject.parentId = this.parent.id;
  20573. }
  20574. if (this.inputs) {
  20575. this.inputs.serialize(serializationObject);
  20576. }
  20577. // Animations
  20578. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  20579. serializationObject.ranges = this.serializeAnimationRanges();
  20580. return serializationObject;
  20581. };
  20582. Camera.prototype.clone = function (name) {
  20583. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  20584. };
  20585. Camera.prototype.getDirection = function (localAxis) {
  20586. var result = BABYLON.Vector3.Zero();
  20587. this.getDirectionToRef(localAxis, result);
  20588. return result;
  20589. };
  20590. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  20591. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  20592. };
  20593. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  20594. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  20595. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  20596. switch (type) {
  20597. case "ArcRotateCamera":
  20598. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  20599. case "DeviceOrientationCamera":
  20600. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  20601. case "FollowCamera":
  20602. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  20603. case "ArcFollowCamera":
  20604. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  20605. case "GamepadCamera":
  20606. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  20607. case "TouchCamera":
  20608. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  20609. case "VirtualJoysticksCamera":
  20610. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  20611. case "WebVRFreeCamera":
  20612. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  20613. case "WebVRGamepadCamera":
  20614. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  20615. case "VRDeviceOrientationFreeCamera":
  20616. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  20617. case "VRDeviceOrientationGamepadCamera":
  20618. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  20619. case "AnaglyphArcRotateCamera":
  20620. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20621. case "AnaglyphFreeCamera":
  20622. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20623. case "AnaglyphGamepadCamera":
  20624. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20625. case "AnaglyphUniversalCamera":
  20626. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20627. case "StereoscopicArcRotateCamera":
  20628. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20629. case "StereoscopicFreeCamera":
  20630. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20631. case "StereoscopicGamepadCamera":
  20632. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20633. case "StereoscopicUniversalCamera":
  20634. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20635. case "FreeCamera":// Forcing Universal here
  20636. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  20637. default:// Universal Camera is the default value
  20638. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  20639. }
  20640. };
  20641. Camera.prototype.computeWorldMatrix = function () {
  20642. return this.getWorldMatrix();
  20643. };
  20644. Camera.Parse = function (parsedCamera, scene) {
  20645. var type = parsedCamera.type;
  20646. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  20647. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  20648. // Parent
  20649. if (parsedCamera.parentId) {
  20650. camera._waitingParentId = parsedCamera.parentId;
  20651. }
  20652. //If camera has an input manager, let it parse inputs settings
  20653. if (camera.inputs) {
  20654. camera.inputs.parse(parsedCamera);
  20655. camera._setupInputs();
  20656. }
  20657. if (camera.setPosition) {
  20658. camera.position.copyFromFloats(0, 0, 0);
  20659. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  20660. }
  20661. // Target
  20662. if (parsedCamera.target) {
  20663. if (camera.setTarget) {
  20664. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  20665. }
  20666. }
  20667. // Apply 3d rig, when found
  20668. if (parsedCamera.cameraRigMode) {
  20669. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  20670. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  20671. }
  20672. // Animations
  20673. if (parsedCamera.animations) {
  20674. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  20675. var parsedAnimation = parsedCamera.animations[animationIndex];
  20676. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  20677. }
  20678. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  20679. }
  20680. if (parsedCamera.autoAnimate) {
  20681. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  20682. }
  20683. return camera;
  20684. };
  20685. // Statics
  20686. Camera._PERSPECTIVE_CAMERA = 0;
  20687. Camera._ORTHOGRAPHIC_CAMERA = 1;
  20688. Camera._FOVMODE_VERTICAL_FIXED = 0;
  20689. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  20690. Camera._RIG_MODE_NONE = 0;
  20691. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  20692. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  20693. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  20694. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  20695. Camera._RIG_MODE_VR = 20;
  20696. Camera._RIG_MODE_WEBVR = 21;
  20697. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  20698. Camera.UseAlternateWebVRRendering = false;
  20699. __decorate([
  20700. BABYLON.serializeAsVector3()
  20701. ], Camera.prototype, "position", void 0);
  20702. __decorate([
  20703. BABYLON.serializeAsVector3()
  20704. ], Camera.prototype, "upVector", void 0);
  20705. __decorate([
  20706. BABYLON.serialize()
  20707. ], Camera.prototype, "orthoLeft", void 0);
  20708. __decorate([
  20709. BABYLON.serialize()
  20710. ], Camera.prototype, "orthoRight", void 0);
  20711. __decorate([
  20712. BABYLON.serialize()
  20713. ], Camera.prototype, "orthoBottom", void 0);
  20714. __decorate([
  20715. BABYLON.serialize()
  20716. ], Camera.prototype, "orthoTop", void 0);
  20717. __decorate([
  20718. BABYLON.serialize()
  20719. ], Camera.prototype, "fov", void 0);
  20720. __decorate([
  20721. BABYLON.serialize()
  20722. ], Camera.prototype, "minZ", void 0);
  20723. __decorate([
  20724. BABYLON.serialize()
  20725. ], Camera.prototype, "maxZ", void 0);
  20726. __decorate([
  20727. BABYLON.serialize()
  20728. ], Camera.prototype, "inertia", void 0);
  20729. __decorate([
  20730. BABYLON.serialize()
  20731. ], Camera.prototype, "mode", void 0);
  20732. __decorate([
  20733. BABYLON.serialize()
  20734. ], Camera.prototype, "layerMask", void 0);
  20735. __decorate([
  20736. BABYLON.serialize()
  20737. ], Camera.prototype, "fovMode", void 0);
  20738. __decorate([
  20739. BABYLON.serialize()
  20740. ], Camera.prototype, "cameraRigMode", void 0);
  20741. __decorate([
  20742. BABYLON.serialize()
  20743. ], Camera.prototype, "interaxialDistance", void 0);
  20744. __decorate([
  20745. BABYLON.serialize()
  20746. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  20747. return Camera;
  20748. }(BABYLON.Node));
  20749. BABYLON.Camera = Camera;
  20750. })(BABYLON || (BABYLON = {}));
  20751. //# sourceMappingURL=babylon.camera.js.map
  20752. var BABYLON;
  20753. (function (BABYLON) {
  20754. var RenderingManager = /** @class */ (function () {
  20755. function RenderingManager(scene) {
  20756. this._renderingGroups = new Array();
  20757. this._autoClearDepthStencil = {};
  20758. this._customOpaqueSortCompareFn = {};
  20759. this._customAlphaTestSortCompareFn = {};
  20760. this._customTransparentSortCompareFn = {};
  20761. this._renderinGroupInfo = null;
  20762. this._scene = scene;
  20763. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  20764. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  20765. }
  20766. }
  20767. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  20768. if (depth === void 0) { depth = true; }
  20769. if (stencil === void 0) { stencil = true; }
  20770. if (this._depthStencilBufferAlreadyCleaned) {
  20771. return;
  20772. }
  20773. this._scene.getEngine().clear(null, false, depth, stencil);
  20774. this._depthStencilBufferAlreadyCleaned = true;
  20775. };
  20776. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  20777. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  20778. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  20779. var info = null;
  20780. if (observable) {
  20781. if (!this._renderinGroupInfo) {
  20782. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  20783. }
  20784. info = this._renderinGroupInfo;
  20785. info.scene = this._scene;
  20786. info.camera = this._scene.activeCamera;
  20787. }
  20788. // Dispatch sprites
  20789. if (renderSprites) {
  20790. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  20791. var manager = this._scene.spriteManagers[index];
  20792. this.dispatchSprites(manager);
  20793. }
  20794. }
  20795. // Render
  20796. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  20797. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  20798. var renderingGroup = this._renderingGroups[index];
  20799. if (!renderingGroup && !observable)
  20800. continue;
  20801. var renderingGroupMask = 0;
  20802. // Fire PRECLEAR stage
  20803. if (observable && info) {
  20804. renderingGroupMask = Math.pow(2, index);
  20805. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  20806. info.renderingGroupId = index;
  20807. observable.notifyObservers(info, renderingGroupMask);
  20808. }
  20809. // Clear depth/stencil if needed
  20810. if (RenderingManager.AUTOCLEAR) {
  20811. var autoClear = this._autoClearDepthStencil[index];
  20812. if (autoClear && autoClear.autoClear) {
  20813. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  20814. }
  20815. }
  20816. if (observable && info) {
  20817. // Fire PREOPAQUE stage
  20818. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  20819. observable.notifyObservers(info, renderingGroupMask);
  20820. // Fire PRETRANSPARENT stage
  20821. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  20822. observable.notifyObservers(info, renderingGroupMask);
  20823. }
  20824. if (renderingGroup)
  20825. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  20826. // Fire POSTTRANSPARENT stage
  20827. if (observable && info) {
  20828. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  20829. observable.notifyObservers(info, renderingGroupMask);
  20830. }
  20831. }
  20832. };
  20833. RenderingManager.prototype.reset = function () {
  20834. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  20835. var renderingGroup = this._renderingGroups[index];
  20836. if (renderingGroup) {
  20837. renderingGroup.prepare();
  20838. }
  20839. }
  20840. };
  20841. RenderingManager.prototype.dispose = function () {
  20842. this.freeRenderingGroups();
  20843. this._renderingGroups.length = 0;
  20844. };
  20845. /**
  20846. * Clear the info related to rendering groups preventing retention points during dispose.
  20847. */
  20848. RenderingManager.prototype.freeRenderingGroups = function () {
  20849. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  20850. var renderingGroup = this._renderingGroups[index];
  20851. if (renderingGroup) {
  20852. renderingGroup.dispose();
  20853. }
  20854. }
  20855. };
  20856. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  20857. if (this._renderingGroups[renderingGroupId] === undefined) {
  20858. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  20859. }
  20860. };
  20861. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  20862. var renderingGroupId = spriteManager.renderingGroupId || 0;
  20863. this._prepareRenderingGroup(renderingGroupId);
  20864. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  20865. };
  20866. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  20867. var renderingGroupId = particleSystem.renderingGroupId || 0;
  20868. this._prepareRenderingGroup(renderingGroupId);
  20869. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  20870. };
  20871. /**
  20872. * @param subMesh The submesh to dispatch
  20873. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  20874. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  20875. */
  20876. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  20877. if (mesh === undefined) {
  20878. mesh = subMesh.getMesh();
  20879. }
  20880. var renderingGroupId = mesh.renderingGroupId || 0;
  20881. this._prepareRenderingGroup(renderingGroupId);
  20882. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  20883. };
  20884. /**
  20885. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  20886. * This allowed control for front to back rendering or reversly depending of the special needs.
  20887. *
  20888. * @param renderingGroupId The rendering group id corresponding to its index
  20889. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  20890. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  20891. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  20892. */
  20893. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  20894. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  20895. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  20896. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  20897. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  20898. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  20899. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  20900. if (this._renderingGroups[renderingGroupId]) {
  20901. var group = this._renderingGroups[renderingGroupId];
  20902. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  20903. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  20904. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  20905. }
  20906. };
  20907. /**
  20908. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  20909. *
  20910. * @param renderingGroupId The rendering group id corresponding to its index
  20911. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  20912. * @param depth Automatically clears depth between groups if true and autoClear is true.
  20913. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  20914. */
  20915. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  20916. if (depth === void 0) { depth = true; }
  20917. if (stencil === void 0) { stencil = true; }
  20918. this._autoClearDepthStencil[renderingGroupId] = {
  20919. autoClear: autoClearDepthStencil,
  20920. depth: depth,
  20921. stencil: stencil
  20922. };
  20923. };
  20924. /**
  20925. * The max id used for rendering groups (not included)
  20926. */
  20927. RenderingManager.MAX_RENDERINGGROUPS = 4;
  20928. /**
  20929. * The min id used for rendering groups (included)
  20930. */
  20931. RenderingManager.MIN_RENDERINGGROUPS = 0;
  20932. /**
  20933. * Used to globally prevent autoclearing scenes.
  20934. */
  20935. RenderingManager.AUTOCLEAR = true;
  20936. return RenderingManager;
  20937. }());
  20938. BABYLON.RenderingManager = RenderingManager;
  20939. })(BABYLON || (BABYLON = {}));
  20940. //# sourceMappingURL=babylon.renderingManager.js.map
  20941. var BABYLON;
  20942. (function (BABYLON) {
  20943. var RenderingGroup = /** @class */ (function () {
  20944. /**
  20945. * Creates a new rendering group.
  20946. * @param index The rendering group index
  20947. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  20948. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  20949. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  20950. */
  20951. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  20952. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  20953. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  20954. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  20955. this.index = index;
  20956. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  20957. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  20958. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  20959. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  20960. this._particleSystems = new BABYLON.SmartArray(256);
  20961. this._spriteManagers = new BABYLON.SmartArray(256);
  20962. this._edgesRenderers = new BABYLON.SmartArray(16);
  20963. this._scene = scene;
  20964. this.opaqueSortCompareFn = opaqueSortCompareFn;
  20965. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  20966. this.transparentSortCompareFn = transparentSortCompareFn;
  20967. }
  20968. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  20969. /**
  20970. * Set the opaque sort comparison function.
  20971. * If null the sub meshes will be render in the order they were created
  20972. */
  20973. set: function (value) {
  20974. this._opaqueSortCompareFn = value;
  20975. if (value) {
  20976. this._renderOpaque = this.renderOpaqueSorted;
  20977. }
  20978. else {
  20979. this._renderOpaque = RenderingGroup.renderUnsorted;
  20980. }
  20981. },
  20982. enumerable: true,
  20983. configurable: true
  20984. });
  20985. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  20986. /**
  20987. * Set the alpha test sort comparison function.
  20988. * If null the sub meshes will be render in the order they were created
  20989. */
  20990. set: function (value) {
  20991. this._alphaTestSortCompareFn = value;
  20992. if (value) {
  20993. this._renderAlphaTest = this.renderAlphaTestSorted;
  20994. }
  20995. else {
  20996. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  20997. }
  20998. },
  20999. enumerable: true,
  21000. configurable: true
  21001. });
  21002. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  21003. /**
  21004. * Set the transparent sort comparison function.
  21005. * If null the sub meshes will be render in the order they were created
  21006. */
  21007. set: function (value) {
  21008. if (value) {
  21009. this._transparentSortCompareFn = value;
  21010. }
  21011. else {
  21012. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  21013. }
  21014. this._renderTransparent = this.renderTransparentSorted;
  21015. },
  21016. enumerable: true,
  21017. configurable: true
  21018. });
  21019. /**
  21020. * Render all the sub meshes contained in the group.
  21021. * @param customRenderFunction Used to override the default render behaviour of the group.
  21022. * @returns true if rendered some submeshes.
  21023. */
  21024. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  21025. if (customRenderFunction) {
  21026. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  21027. return;
  21028. }
  21029. var engine = this._scene.getEngine();
  21030. // Depth only
  21031. if (this._depthOnlySubMeshes.length !== 0) {
  21032. engine.setColorWrite(false);
  21033. this._renderAlphaTest(this._depthOnlySubMeshes);
  21034. engine.setColorWrite(true);
  21035. }
  21036. // Opaque
  21037. if (this._opaqueSubMeshes.length !== 0) {
  21038. this._renderOpaque(this._opaqueSubMeshes);
  21039. }
  21040. // Alpha test
  21041. if (this._alphaTestSubMeshes.length !== 0) {
  21042. this._renderAlphaTest(this._alphaTestSubMeshes);
  21043. }
  21044. var stencilState = engine.getStencilBuffer();
  21045. engine.setStencilBuffer(false);
  21046. // Sprites
  21047. if (renderSprites) {
  21048. this._renderSprites();
  21049. }
  21050. // Particles
  21051. if (renderParticles) {
  21052. this._renderParticles(activeMeshes);
  21053. }
  21054. if (this.onBeforeTransparentRendering) {
  21055. this.onBeforeTransparentRendering();
  21056. }
  21057. // Transparent
  21058. if (this._transparentSubMeshes.length !== 0) {
  21059. this._renderTransparent(this._transparentSubMeshes);
  21060. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21061. }
  21062. // Set back stencil to false in case it changes before the edge renderer.
  21063. engine.setStencilBuffer(false);
  21064. // Edges
  21065. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  21066. this._edgesRenderers.data[edgesRendererIndex].render();
  21067. }
  21068. // Restore Stencil state.
  21069. engine.setStencilBuffer(stencilState);
  21070. };
  21071. /**
  21072. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  21073. * @param subMeshes The submeshes to render
  21074. */
  21075. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  21076. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  21077. };
  21078. /**
  21079. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  21080. * @param subMeshes The submeshes to render
  21081. */
  21082. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  21083. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  21084. };
  21085. /**
  21086. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  21087. * @param subMeshes The submeshes to render
  21088. */
  21089. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  21090. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  21091. };
  21092. /**
  21093. * Renders the submeshes in a specified order.
  21094. * @param subMeshes The submeshes to sort before render
  21095. * @param sortCompareFn The comparison function use to sort
  21096. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  21097. * @param transparent Specifies to activate blending if true
  21098. */
  21099. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  21100. var subIndex = 0;
  21101. var subMesh;
  21102. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  21103. for (; subIndex < subMeshes.length; subIndex++) {
  21104. subMesh = subMeshes.data[subIndex];
  21105. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  21106. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  21107. }
  21108. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  21109. if (sortCompareFn) {
  21110. sortedArray.sort(sortCompareFn);
  21111. }
  21112. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  21113. subMesh = sortedArray[subIndex];
  21114. if (transparent) {
  21115. var material = subMesh.getMaterial();
  21116. if (material && material.needDepthPrePass) {
  21117. var engine = material.getScene().getEngine();
  21118. engine.setColorWrite(false);
  21119. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21120. subMesh.render(false);
  21121. engine.setColorWrite(true);
  21122. }
  21123. }
  21124. subMesh.render(transparent);
  21125. }
  21126. };
  21127. /**
  21128. * Renders the submeshes in the order they were dispatched (no sort applied).
  21129. * @param subMeshes The submeshes to render
  21130. */
  21131. RenderingGroup.renderUnsorted = function (subMeshes) {
  21132. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  21133. var submesh = subMeshes.data[subIndex];
  21134. submesh.render(false);
  21135. }
  21136. };
  21137. /**
  21138. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  21139. * are rendered back to front if in the same alpha index.
  21140. *
  21141. * @param a The first submesh
  21142. * @param b The second submesh
  21143. * @returns The result of the comparison
  21144. */
  21145. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  21146. // Alpha index first
  21147. if (a._alphaIndex > b._alphaIndex) {
  21148. return 1;
  21149. }
  21150. if (a._alphaIndex < b._alphaIndex) {
  21151. return -1;
  21152. }
  21153. // Then distance to camera
  21154. return RenderingGroup.backToFrontSortCompare(a, b);
  21155. };
  21156. /**
  21157. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  21158. * are rendered back to front.
  21159. *
  21160. * @param a The first submesh
  21161. * @param b The second submesh
  21162. * @returns The result of the comparison
  21163. */
  21164. RenderingGroup.backToFrontSortCompare = function (a, b) {
  21165. // Then distance to camera
  21166. if (a._distanceToCamera < b._distanceToCamera) {
  21167. return 1;
  21168. }
  21169. if (a._distanceToCamera > b._distanceToCamera) {
  21170. return -1;
  21171. }
  21172. return 0;
  21173. };
  21174. /**
  21175. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  21176. * are rendered front to back (prevent overdraw).
  21177. *
  21178. * @param a The first submesh
  21179. * @param b The second submesh
  21180. * @returns The result of the comparison
  21181. */
  21182. RenderingGroup.frontToBackSortCompare = function (a, b) {
  21183. // Then distance to camera
  21184. if (a._distanceToCamera < b._distanceToCamera) {
  21185. return -1;
  21186. }
  21187. if (a._distanceToCamera > b._distanceToCamera) {
  21188. return 1;
  21189. }
  21190. return 0;
  21191. };
  21192. /**
  21193. * Resets the different lists of submeshes to prepare a new frame.
  21194. */
  21195. RenderingGroup.prototype.prepare = function () {
  21196. this._opaqueSubMeshes.reset();
  21197. this._transparentSubMeshes.reset();
  21198. this._alphaTestSubMeshes.reset();
  21199. this._depthOnlySubMeshes.reset();
  21200. this._particleSystems.reset();
  21201. this._spriteManagers.reset();
  21202. this._edgesRenderers.reset();
  21203. };
  21204. RenderingGroup.prototype.dispose = function () {
  21205. this._opaqueSubMeshes.dispose();
  21206. this._transparentSubMeshes.dispose();
  21207. this._alphaTestSubMeshes.dispose();
  21208. this._depthOnlySubMeshes.dispose();
  21209. this._particleSystems.dispose();
  21210. this._spriteManagers.dispose();
  21211. this._edgesRenderers.dispose();
  21212. };
  21213. /**
  21214. * Inserts the submesh in its correct queue depending on its material.
  21215. * @param subMesh The submesh to dispatch
  21216. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  21217. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  21218. */
  21219. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  21220. // Get mesh and materials if not provided
  21221. if (mesh === undefined) {
  21222. mesh = subMesh.getMesh();
  21223. }
  21224. if (material === undefined) {
  21225. material = subMesh.getMaterial();
  21226. }
  21227. if (material === null || material === undefined) {
  21228. return;
  21229. }
  21230. if (material.needAlphaBlendingForMesh(mesh)) {
  21231. this._transparentSubMeshes.push(subMesh);
  21232. }
  21233. else if (material.needAlphaTesting()) {
  21234. if (material.needDepthPrePass) {
  21235. this._depthOnlySubMeshes.push(subMesh);
  21236. }
  21237. this._alphaTestSubMeshes.push(subMesh);
  21238. }
  21239. else {
  21240. if (material.needDepthPrePass) {
  21241. this._depthOnlySubMeshes.push(subMesh);
  21242. }
  21243. this._opaqueSubMeshes.push(subMesh); // Opaque
  21244. }
  21245. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined) {
  21246. this._edgesRenderers.push(mesh._edgesRenderer);
  21247. }
  21248. };
  21249. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  21250. this._spriteManagers.push(spriteManager);
  21251. };
  21252. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  21253. this._particleSystems.push(particleSystem);
  21254. };
  21255. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  21256. if (this._particleSystems.length === 0) {
  21257. return;
  21258. }
  21259. // Particles
  21260. var activeCamera = this._scene.activeCamera;
  21261. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  21262. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  21263. var particleSystem = this._particleSystems.data[particleIndex];
  21264. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  21265. continue;
  21266. }
  21267. var emitter = particleSystem.emitter;
  21268. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  21269. this._scene._activeParticles.addCount(particleSystem.render(), false);
  21270. }
  21271. }
  21272. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  21273. };
  21274. RenderingGroup.prototype._renderSprites = function () {
  21275. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  21276. return;
  21277. }
  21278. // Sprites
  21279. var activeCamera = this._scene.activeCamera;
  21280. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  21281. for (var id = 0; id < this._spriteManagers.length; id++) {
  21282. var spriteManager = this._spriteManagers.data[id];
  21283. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  21284. spriteManager.render();
  21285. }
  21286. }
  21287. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  21288. };
  21289. return RenderingGroup;
  21290. }());
  21291. BABYLON.RenderingGroup = RenderingGroup;
  21292. })(BABYLON || (BABYLON = {}));
  21293. //# sourceMappingURL=babylon.renderingGroup.js.map
  21294. var BABYLON;
  21295. (function (BABYLON) {
  21296. var ClickInfo = /** @class */ (function () {
  21297. function ClickInfo() {
  21298. this._singleClick = false;
  21299. this._doubleClick = false;
  21300. this._hasSwiped = false;
  21301. this._ignore = false;
  21302. }
  21303. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  21304. get: function () {
  21305. return this._singleClick;
  21306. },
  21307. set: function (b) {
  21308. this._singleClick = b;
  21309. },
  21310. enumerable: true,
  21311. configurable: true
  21312. });
  21313. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  21314. get: function () {
  21315. return this._doubleClick;
  21316. },
  21317. set: function (b) {
  21318. this._doubleClick = b;
  21319. },
  21320. enumerable: true,
  21321. configurable: true
  21322. });
  21323. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  21324. get: function () {
  21325. return this._hasSwiped;
  21326. },
  21327. set: function (b) {
  21328. this._hasSwiped = b;
  21329. },
  21330. enumerable: true,
  21331. configurable: true
  21332. });
  21333. Object.defineProperty(ClickInfo.prototype, "ignore", {
  21334. get: function () {
  21335. return this._ignore;
  21336. },
  21337. set: function (b) {
  21338. this._ignore = b;
  21339. },
  21340. enumerable: true,
  21341. configurable: true
  21342. });
  21343. return ClickInfo;
  21344. }());
  21345. /**
  21346. * This class is used by the onRenderingGroupObservable
  21347. */
  21348. var RenderingGroupInfo = /** @class */ (function () {
  21349. function RenderingGroupInfo() {
  21350. }
  21351. /**
  21352. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  21353. * This stage will be fired no matter what
  21354. */
  21355. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  21356. /**
  21357. * Called before opaque object are rendered.
  21358. * This stage will be fired only if there's 3D Opaque content to render
  21359. */
  21360. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  21361. /**
  21362. * Called after the opaque objects are rendered and before the transparent ones
  21363. * This stage will be fired only if there's 3D transparent content to render
  21364. */
  21365. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  21366. /**
  21367. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  21368. * This stage will be fired no matter what
  21369. */
  21370. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  21371. return RenderingGroupInfo;
  21372. }());
  21373. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  21374. /**
  21375. * Represents a scene to be rendered by the engine.
  21376. * @see http://doc.babylonjs.com/page.php?p=21911
  21377. */
  21378. var Scene = /** @class */ (function () {
  21379. /**
  21380. * @constructor
  21381. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  21382. */
  21383. function Scene(engine) {
  21384. // Members
  21385. this.autoClear = true;
  21386. this.autoClearDepthAndStencil = true;
  21387. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  21388. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  21389. this.forceWireframe = false;
  21390. this._forcePointsCloud = false;
  21391. this.forceShowBoundingBoxes = false;
  21392. this.animationsEnabled = true;
  21393. this.useConstantAnimationDeltaTime = false;
  21394. this.constantlyUpdateMeshUnderPointer = false;
  21395. this.hoverCursor = "pointer";
  21396. this.defaultCursor = "";
  21397. /**
  21398. * This is used to call preventDefault() on pointer down
  21399. * in order to block unwanted artifacts like system double clicks
  21400. */
  21401. this.preventDefaultOnPointerDown = true;
  21402. // Metadata
  21403. this.metadata = null;
  21404. /**
  21405. * An event triggered when the scene is disposed.
  21406. * @type {BABYLON.Observable}
  21407. */
  21408. this.onDisposeObservable = new BABYLON.Observable();
  21409. /**
  21410. * An event triggered before rendering the scene (right after animations and physics)
  21411. * @type {BABYLON.Observable}
  21412. */
  21413. this.onBeforeRenderObservable = new BABYLON.Observable();
  21414. /**
  21415. * An event triggered after rendering the scene
  21416. * @type {BABYLON.Observable}
  21417. */
  21418. this.onAfterRenderObservable = new BABYLON.Observable();
  21419. /**
  21420. * An event triggered before animating the scene
  21421. * @type {BABYLON.Observable}
  21422. */
  21423. this.onBeforeAnimationsObservable = new BABYLON.Observable();
  21424. /**
  21425. * An event triggered after animations processing
  21426. * @type {BABYLON.Observable}
  21427. */
  21428. this.onAfterAnimationsObservable = new BABYLON.Observable();
  21429. /**
  21430. * An event triggered before draw calls are ready to be sent
  21431. * @type {BABYLON.Observable}
  21432. */
  21433. this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  21434. /**
  21435. * An event triggered after draw calls have been sent
  21436. * @type {BABYLON.Observable}
  21437. */
  21438. this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  21439. /**
  21440. * An event triggered when physic simulation is about to be run
  21441. * @type {BABYLON.Observable}
  21442. */
  21443. this.onBeforePhysicsObservable = new BABYLON.Observable();
  21444. /**
  21445. * An event triggered when physic simulation has been done
  21446. * @type {BABYLON.Observable}
  21447. */
  21448. this.onAfterPhysicsObservable = new BABYLON.Observable();
  21449. /**
  21450. * An event triggered when the scene is ready
  21451. * @type {BABYLON.Observable}
  21452. */
  21453. this.onReadyObservable = new BABYLON.Observable();
  21454. /**
  21455. * An event triggered before rendering a camera
  21456. * @type {BABYLON.Observable}
  21457. */
  21458. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  21459. /**
  21460. * An event triggered after rendering a camera
  21461. * @type {BABYLON.Observable}
  21462. */
  21463. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  21464. /**
  21465. * An event triggered when active meshes evaluation is about to start
  21466. * @type {BABYLON.Observable}
  21467. */
  21468. this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  21469. /**
  21470. * An event triggered when active meshes evaluation is done
  21471. * @type {BABYLON.Observable}
  21472. */
  21473. this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  21474. /**
  21475. * An event triggered when particles rendering is about to start
  21476. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  21477. * @type {BABYLON.Observable}
  21478. */
  21479. this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  21480. /**
  21481. * An event triggered when particles rendering is done
  21482. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  21483. * @type {BABYLON.Observable}
  21484. */
  21485. this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  21486. /**
  21487. * An event triggered when sprites rendering is about to start
  21488. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  21489. * @type {BABYLON.Observable}
  21490. */
  21491. this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  21492. /**
  21493. * An event triggered when sprites rendering is done
  21494. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  21495. * @type {BABYLON.Observable}
  21496. */
  21497. this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  21498. /**
  21499. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  21500. * @type {BABYLON.Observable}
  21501. */
  21502. this.onDataLoadedObservable = new BABYLON.Observable();
  21503. /**
  21504. * An event triggered when a camera is created
  21505. * @type {BABYLON.Observable}
  21506. */
  21507. this.onNewCameraAddedObservable = new BABYLON.Observable();
  21508. /**
  21509. * An event triggered when a camera is removed
  21510. * @type {BABYLON.Observable}
  21511. */
  21512. this.onCameraRemovedObservable = new BABYLON.Observable();
  21513. /**
  21514. * An event triggered when a light is created
  21515. * @type {BABYLON.Observable}
  21516. */
  21517. this.onNewLightAddedObservable = new BABYLON.Observable();
  21518. /**
  21519. * An event triggered when a light is removed
  21520. * @type {BABYLON.Observable}
  21521. */
  21522. this.onLightRemovedObservable = new BABYLON.Observable();
  21523. /**
  21524. * An event triggered when a geometry is created
  21525. * @type {BABYLON.Observable}
  21526. */
  21527. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  21528. /**
  21529. * An event triggered when a geometry is removed
  21530. * @type {BABYLON.Observable}
  21531. */
  21532. this.onGeometryRemovedObservable = new BABYLON.Observable();
  21533. /**
  21534. * An event triggered when a transform node is created
  21535. * @type {BABYLON.Observable}
  21536. */
  21537. this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  21538. /**
  21539. * An event triggered when a transform node is removed
  21540. * @type {BABYLON.Observable}
  21541. */
  21542. this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  21543. /**
  21544. * An event triggered when a mesh is created
  21545. * @type {BABYLON.Observable}
  21546. */
  21547. this.onNewMeshAddedObservable = new BABYLON.Observable();
  21548. /**
  21549. * An event triggered when a mesh is removed
  21550. * @type {BABYLON.Observable}
  21551. */
  21552. this.onMeshRemovedObservable = new BABYLON.Observable();
  21553. /**
  21554. * An event triggered when render targets are about to be rendered
  21555. * Can happen multiple times per frame.
  21556. * @type {BABYLON.Observable}
  21557. */
  21558. this.OnBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  21559. /**
  21560. * An event triggered when render targets were rendered.
  21561. * Can happen multiple times per frame.
  21562. * @type {BABYLON.Observable}
  21563. */
  21564. this.OnAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  21565. /**
  21566. * An event triggered before calculating deterministic simulation step
  21567. * @type {BABYLON.Observable}
  21568. */
  21569. this.onBeforeStepObservable = new BABYLON.Observable();
  21570. /**
  21571. * An event triggered after calculating deterministic simulation step
  21572. * @type {BABYLON.Observable}
  21573. */
  21574. this.onAfterStepObservable = new BABYLON.Observable();
  21575. /**
  21576. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  21577. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  21578. * 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)
  21579. */
  21580. this.onRenderingGroupObservable = new BABYLON.Observable();
  21581. // Animations
  21582. this.animations = [];
  21583. /**
  21584. * 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).
  21585. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  21586. */
  21587. this.onPrePointerObservable = new BABYLON.Observable();
  21588. /**
  21589. * Observable event triggered each time an input event is received from the rendering canvas
  21590. */
  21591. this.onPointerObservable = new BABYLON.Observable();
  21592. this._meshPickProceed = false;
  21593. this._currentPickResult = null;
  21594. this._previousPickResult = null;
  21595. this._totalPointersPressed = 0;
  21596. this._doubleClickOccured = false;
  21597. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  21598. this.cameraToUseForPointers = null;
  21599. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  21600. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  21601. this._startingPointerTime = 0;
  21602. this._previousStartingPointerTime = 0;
  21603. // Deterministic lockstep
  21604. this._timeAccumulator = 0;
  21605. this._currentStepId = 0;
  21606. this._currentInternalStep = 0;
  21607. // Keyboard
  21608. /**
  21609. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  21610. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  21611. */
  21612. this.onPreKeyboardObservable = new BABYLON.Observable();
  21613. /**
  21614. * Observable event triggered each time an keyboard event is received from the hosting window
  21615. */
  21616. this.onKeyboardObservable = new BABYLON.Observable();
  21617. // Coordinate system
  21618. /**
  21619. * use right-handed coordinate system on this scene.
  21620. * @type {boolean}
  21621. */
  21622. this._useRightHandedSystem = false;
  21623. // Fog
  21624. this._fogEnabled = true;
  21625. this._fogMode = Scene.FOGMODE_NONE;
  21626. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  21627. this.fogDensity = 0.1;
  21628. this.fogStart = 0;
  21629. this.fogEnd = 1000.0;
  21630. // Lights
  21631. /**
  21632. * is shadow enabled on this scene.
  21633. * @type {boolean}
  21634. */
  21635. this._shadowsEnabled = true;
  21636. /**
  21637. * is light enabled on this scene.
  21638. * @type {boolean}
  21639. */
  21640. this._lightsEnabled = true;
  21641. /**
  21642. * All of the lights added to this scene.
  21643. * @see BABYLON.Light
  21644. * @type {BABYLON.Light[]}
  21645. */
  21646. this.lights = new Array();
  21647. // Cameras
  21648. /** All of the cameras added to this scene. */
  21649. this.cameras = new Array();
  21650. /** All of the active cameras added to this scene. */
  21651. this.activeCameras = new Array();
  21652. // Meshes
  21653. /**
  21654. * All of the tranform nodes added to this scene.
  21655. * @see BABYLON.TransformNode
  21656. * @type {BABYLON.TransformNode[]}
  21657. */
  21658. this.transformNodes = new Array();
  21659. /**
  21660. * All of the (abstract) meshes added to this scene.
  21661. * @see BABYLON.AbstractMesh
  21662. * @type {BABYLON.AbstractMesh[]}
  21663. */
  21664. this.meshes = new Array();
  21665. /**
  21666. * All of the animation groups added to this scene.
  21667. * @see BABYLON.AnimationGroup
  21668. * @type {BABYLON.AnimationGroup[]}
  21669. */
  21670. this.animationGroups = new Array();
  21671. // Geometries
  21672. this._geometries = new Array();
  21673. this.materials = new Array();
  21674. this.multiMaterials = new Array();
  21675. // Textures
  21676. this._texturesEnabled = true;
  21677. this.textures = new Array();
  21678. // Particles
  21679. this.particlesEnabled = true;
  21680. this.particleSystems = new Array();
  21681. // Sprites
  21682. this.spritesEnabled = true;
  21683. this.spriteManagers = new Array();
  21684. /**
  21685. * The list of layers (background and foreground) of the scene.
  21686. */
  21687. this.layers = new Array();
  21688. /**
  21689. * The list of effect layers (highlights/glow) contained in the scene.
  21690. */
  21691. this.effectLayers = new Array();
  21692. // Skeletons
  21693. this._skeletonsEnabled = true;
  21694. this.skeletons = new Array();
  21695. // Morph targets
  21696. this.morphTargetManagers = new Array();
  21697. // Lens flares
  21698. this.lensFlaresEnabled = true;
  21699. this.lensFlareSystems = new Array();
  21700. // Collisions
  21701. this.collisionsEnabled = true;
  21702. /** Defines the gravity applied to this scene */
  21703. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  21704. // Postprocesses
  21705. this.postProcesses = new Array();
  21706. this.postProcessesEnabled = true;
  21707. // Customs render targets
  21708. this.renderTargetsEnabled = true;
  21709. this.dumpNextRenderTargets = false;
  21710. this.customRenderTargets = new Array();
  21711. // Imported meshes
  21712. this.importedMeshesFiles = new Array();
  21713. // Probes
  21714. this.probesEnabled = true;
  21715. this.reflectionProbes = new Array();
  21716. this._actionManagers = new Array();
  21717. this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  21718. // Procedural textures
  21719. this.proceduralTexturesEnabled = true;
  21720. this._proceduralTextures = new Array();
  21721. this.soundTracks = new Array();
  21722. this._audioEnabled = true;
  21723. this._headphone = false;
  21724. // Performance counters
  21725. this._totalVertices = new BABYLON.PerfCounter();
  21726. this._activeIndices = new BABYLON.PerfCounter();
  21727. this._activeParticles = new BABYLON.PerfCounter();
  21728. this._activeBones = new BABYLON.PerfCounter();
  21729. this._animationTime = 0;
  21730. this.animationTimeScale = 1;
  21731. this._renderId = 0;
  21732. this._executeWhenReadyTimeoutId = -1;
  21733. this._intermediateRendering = false;
  21734. this._viewUpdateFlag = -1;
  21735. this._projectionUpdateFlag = -1;
  21736. this._alternateViewUpdateFlag = -1;
  21737. this._alternateProjectionUpdateFlag = -1;
  21738. this._toBeDisposed = new BABYLON.SmartArray(256);
  21739. this._activeRequests = new Array();
  21740. this._pendingData = new Array();
  21741. this._isDisposed = false;
  21742. this.dispatchAllSubMeshesOfActiveMeshes = false;
  21743. this._activeMeshes = new BABYLON.SmartArray(256);
  21744. this._processedMaterials = new BABYLON.SmartArray(256);
  21745. this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  21746. this._activeParticleSystems = new BABYLON.SmartArray(256);
  21747. this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  21748. this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  21749. this._activeAnimatables = new Array();
  21750. this._transformMatrix = BABYLON.Matrix.Zero();
  21751. this._useAlternateCameraConfiguration = false;
  21752. this._alternateRendering = false;
  21753. this.requireLightSorting = false;
  21754. this._depthRenderer = {};
  21755. this._activeMeshesFrozen = false;
  21756. this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  21757. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  21758. this._engine.scenes.push(this);
  21759. this._uid = null;
  21760. this._renderingManager = new BABYLON.RenderingManager(this);
  21761. this.postProcessManager = new BABYLON.PostProcessManager(this);
  21762. if (BABYLON.OutlineRenderer) {
  21763. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  21764. }
  21765. if (BABYLON.Tools.IsWindowObjectExist()) {
  21766. this.attachControl();
  21767. }
  21768. //simplification queue
  21769. if (BABYLON.SimplificationQueue) {
  21770. this.simplificationQueue = new BABYLON.SimplificationQueue();
  21771. }
  21772. //collision coordinator initialization. For now legacy per default.
  21773. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  21774. // Uniform Buffer
  21775. this._createUbo();
  21776. // Default Image processing definition.
  21777. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  21778. }
  21779. Object.defineProperty(Scene, "FOGMODE_NONE", {
  21780. /** The fog is deactivated */
  21781. get: function () {
  21782. return Scene._FOGMODE_NONE;
  21783. },
  21784. enumerable: true,
  21785. configurable: true
  21786. });
  21787. Object.defineProperty(Scene, "FOGMODE_EXP", {
  21788. /** The fog density is following an exponential function */
  21789. get: function () {
  21790. return Scene._FOGMODE_EXP;
  21791. },
  21792. enumerable: true,
  21793. configurable: true
  21794. });
  21795. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  21796. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  21797. get: function () {
  21798. return Scene._FOGMODE_EXP2;
  21799. },
  21800. enumerable: true,
  21801. configurable: true
  21802. });
  21803. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  21804. /** The fog density is following a linear function. */
  21805. get: function () {
  21806. return Scene._FOGMODE_LINEAR;
  21807. },
  21808. enumerable: true,
  21809. configurable: true
  21810. });
  21811. Object.defineProperty(Scene.prototype, "environmentTexture", {
  21812. /**
  21813. * Texture used in all pbr material as the reflection texture.
  21814. * As in the majority of the scene they are the same (exception for multi room and so on),
  21815. * this is easier to reference from here than from all the materials.
  21816. */
  21817. get: function () {
  21818. return this._environmentTexture;
  21819. },
  21820. /**
  21821. * Texture used in all pbr material as the reflection texture.
  21822. * As in the majority of the scene they are the same (exception for multi room and so on),
  21823. * this is easier to set here than in all the materials.
  21824. */
  21825. set: function (value) {
  21826. if (this._environmentTexture === value) {
  21827. return;
  21828. }
  21829. this._environmentTexture = value;
  21830. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  21831. },
  21832. enumerable: true,
  21833. configurable: true
  21834. });
  21835. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  21836. /**
  21837. * Default image processing configuration used either in the rendering
  21838. * Forward main pass or through the imageProcessingPostProcess if present.
  21839. * As in the majority of the scene they are the same (exception for multi camera),
  21840. * this is easier to reference from here than from all the materials and post process.
  21841. *
  21842. * No setter as we it is a shared configuration, you can set the values instead.
  21843. */
  21844. get: function () {
  21845. return this._imageProcessingConfiguration;
  21846. },
  21847. enumerable: true,
  21848. configurable: true
  21849. });
  21850. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  21851. get: function () {
  21852. return this._forcePointsCloud;
  21853. },
  21854. set: function (value) {
  21855. if (this._forcePointsCloud === value) {
  21856. return;
  21857. }
  21858. this._forcePointsCloud = value;
  21859. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  21860. },
  21861. enumerable: true,
  21862. configurable: true
  21863. });
  21864. Object.defineProperty(Scene.prototype, "onDispose", {
  21865. /** A function to be executed when this scene is disposed. */
  21866. set: function (callback) {
  21867. if (this._onDisposeObserver) {
  21868. this.onDisposeObservable.remove(this._onDisposeObserver);
  21869. }
  21870. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  21871. },
  21872. enumerable: true,
  21873. configurable: true
  21874. });
  21875. Object.defineProperty(Scene.prototype, "beforeRender", {
  21876. /** A function to be executed before rendering this scene */
  21877. set: function (callback) {
  21878. if (this._onBeforeRenderObserver) {
  21879. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  21880. }
  21881. if (callback) {
  21882. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  21883. }
  21884. },
  21885. enumerable: true,
  21886. configurable: true
  21887. });
  21888. Object.defineProperty(Scene.prototype, "afterRender", {
  21889. /** A function to be executed after rendering this scene */
  21890. set: function (callback) {
  21891. if (this._onAfterRenderObserver) {
  21892. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  21893. }
  21894. if (callback) {
  21895. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  21896. }
  21897. },
  21898. enumerable: true,
  21899. configurable: true
  21900. });
  21901. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  21902. set: function (callback) {
  21903. if (this._onBeforeCameraRenderObserver) {
  21904. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  21905. }
  21906. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  21907. },
  21908. enumerable: true,
  21909. configurable: true
  21910. });
  21911. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  21912. set: function (callback) {
  21913. if (this._onAfterCameraRenderObserver) {
  21914. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  21915. }
  21916. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  21917. },
  21918. enumerable: true,
  21919. configurable: true
  21920. });
  21921. Object.defineProperty(Scene.prototype, "gamepadManager", {
  21922. get: function () {
  21923. if (!this._gamepadManager) {
  21924. this._gamepadManager = new BABYLON.GamepadManager(this);
  21925. }
  21926. return this._gamepadManager;
  21927. },
  21928. enumerable: true,
  21929. configurable: true
  21930. });
  21931. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  21932. get: function () {
  21933. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  21934. },
  21935. enumerable: true,
  21936. configurable: true
  21937. });
  21938. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  21939. get: function () {
  21940. return this._useRightHandedSystem;
  21941. },
  21942. set: function (value) {
  21943. if (this._useRightHandedSystem === value) {
  21944. return;
  21945. }
  21946. this._useRightHandedSystem = value;
  21947. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  21948. },
  21949. enumerable: true,
  21950. configurable: true
  21951. });
  21952. Scene.prototype.setStepId = function (newStepId) {
  21953. this._currentStepId = newStepId;
  21954. };
  21955. ;
  21956. Scene.prototype.getStepId = function () {
  21957. return this._currentStepId;
  21958. };
  21959. ;
  21960. Scene.prototype.getInternalStep = function () {
  21961. return this._currentInternalStep;
  21962. };
  21963. ;
  21964. Object.defineProperty(Scene.prototype, "fogEnabled", {
  21965. get: function () {
  21966. return this._fogEnabled;
  21967. },
  21968. /**
  21969. * is fog enabled on this scene.
  21970. */
  21971. set: function (value) {
  21972. if (this._fogEnabled === value) {
  21973. return;
  21974. }
  21975. this._fogEnabled = value;
  21976. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  21977. },
  21978. enumerable: true,
  21979. configurable: true
  21980. });
  21981. Object.defineProperty(Scene.prototype, "fogMode", {
  21982. get: function () {
  21983. return this._fogMode;
  21984. },
  21985. set: function (value) {
  21986. if (this._fogMode === value) {
  21987. return;
  21988. }
  21989. this._fogMode = value;
  21990. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  21991. },
  21992. enumerable: true,
  21993. configurable: true
  21994. });
  21995. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  21996. get: function () {
  21997. return this._shadowsEnabled;
  21998. },
  21999. set: function (value) {
  22000. if (this._shadowsEnabled === value) {
  22001. return;
  22002. }
  22003. this._shadowsEnabled = value;
  22004. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  22005. },
  22006. enumerable: true,
  22007. configurable: true
  22008. });
  22009. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  22010. get: function () {
  22011. return this._lightsEnabled;
  22012. },
  22013. set: function (value) {
  22014. if (this._lightsEnabled === value) {
  22015. return;
  22016. }
  22017. this._lightsEnabled = value;
  22018. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  22019. },
  22020. enumerable: true,
  22021. configurable: true
  22022. });
  22023. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  22024. /** The default material used on meshes when no material is affected */
  22025. get: function () {
  22026. if (!this._defaultMaterial) {
  22027. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  22028. }
  22029. return this._defaultMaterial;
  22030. },
  22031. /** The default material used on meshes when no material is affected */
  22032. set: function (value) {
  22033. this._defaultMaterial = value;
  22034. },
  22035. enumerable: true,
  22036. configurable: true
  22037. });
  22038. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  22039. get: function () {
  22040. return this._texturesEnabled;
  22041. },
  22042. set: function (value) {
  22043. if (this._texturesEnabled === value) {
  22044. return;
  22045. }
  22046. this._texturesEnabled = value;
  22047. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  22048. },
  22049. enumerable: true,
  22050. configurable: true
  22051. });
  22052. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  22053. get: function () {
  22054. return this._skeletonsEnabled;
  22055. },
  22056. set: function (value) {
  22057. if (this._skeletonsEnabled === value) {
  22058. return;
  22059. }
  22060. this._skeletonsEnabled = value;
  22061. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  22062. },
  22063. enumerable: true,
  22064. configurable: true
  22065. });
  22066. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  22067. get: function () {
  22068. if (!this._postProcessRenderPipelineManager) {
  22069. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  22070. }
  22071. return this._postProcessRenderPipelineManager;
  22072. },
  22073. enumerable: true,
  22074. configurable: true
  22075. });
  22076. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  22077. get: function () {
  22078. if (!this._mainSoundTrack) {
  22079. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  22080. }
  22081. return this._mainSoundTrack;
  22082. },
  22083. enumerable: true,
  22084. configurable: true
  22085. });
  22086. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  22087. get: function () {
  22088. return this._alternateRendering;
  22089. },
  22090. enumerable: true,
  22091. configurable: true
  22092. });
  22093. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  22094. get: function () {
  22095. return this._frustumPlanes;
  22096. },
  22097. enumerable: true,
  22098. configurable: true
  22099. });
  22100. Object.defineProperty(Scene.prototype, "geometryBufferRenderer", {
  22101. /**
  22102. * Gets the current geometry buffer associated to the scene.
  22103. */
  22104. get: function () {
  22105. return this._geometryBufferRenderer;
  22106. },
  22107. /**
  22108. * Sets the current geometry buffer for the scene.
  22109. */
  22110. set: function (geometryBufferRenderer) {
  22111. if (geometryBufferRenderer && geometryBufferRenderer.isSupported) {
  22112. this._geometryBufferRenderer = geometryBufferRenderer;
  22113. }
  22114. },
  22115. enumerable: true,
  22116. configurable: true
  22117. });
  22118. Object.defineProperty(Scene.prototype, "debugLayer", {
  22119. // Properties
  22120. get: function () {
  22121. if (!this._debugLayer) {
  22122. this._debugLayer = new BABYLON.DebugLayer(this);
  22123. }
  22124. return this._debugLayer;
  22125. },
  22126. enumerable: true,
  22127. configurable: true
  22128. });
  22129. Object.defineProperty(Scene.prototype, "workerCollisions", {
  22130. get: function () {
  22131. return this._workerCollisions;
  22132. },
  22133. set: function (enabled) {
  22134. if (!BABYLON.CollisionCoordinatorLegacy) {
  22135. return;
  22136. }
  22137. enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker);
  22138. this._workerCollisions = enabled;
  22139. if (this.collisionCoordinator) {
  22140. this.collisionCoordinator.destroy();
  22141. }
  22142. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  22143. this.collisionCoordinator.init(this);
  22144. },
  22145. enumerable: true,
  22146. configurable: true
  22147. });
  22148. Object.defineProperty(Scene.prototype, "selectionOctree", {
  22149. get: function () {
  22150. return this._selectionOctree;
  22151. },
  22152. enumerable: true,
  22153. configurable: true
  22154. });
  22155. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  22156. /**
  22157. * The mesh that is currently under the pointer.
  22158. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  22159. */
  22160. get: function () {
  22161. return this._pointerOverMesh;
  22162. },
  22163. enumerable: true,
  22164. configurable: true
  22165. });
  22166. Object.defineProperty(Scene.prototype, "pointerX", {
  22167. /**
  22168. * Current on-screen X position of the pointer
  22169. * @return {number} X position of the pointer
  22170. */
  22171. get: function () {
  22172. return this._pointerX;
  22173. },
  22174. enumerable: true,
  22175. configurable: true
  22176. });
  22177. Object.defineProperty(Scene.prototype, "pointerY", {
  22178. /**
  22179. * Current on-screen Y position of the pointer
  22180. * @return {number} Y position of the pointer
  22181. */
  22182. get: function () {
  22183. return this._pointerY;
  22184. },
  22185. enumerable: true,
  22186. configurable: true
  22187. });
  22188. Scene.prototype.getCachedMaterial = function () {
  22189. return this._cachedMaterial;
  22190. };
  22191. Scene.prototype.getCachedEffect = function () {
  22192. return this._cachedEffect;
  22193. };
  22194. Scene.prototype.getCachedVisibility = function () {
  22195. return this._cachedVisibility;
  22196. };
  22197. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  22198. if (visibility === void 0) { visibility = 1; }
  22199. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  22200. };
  22201. Scene.prototype.getBoundingBoxRenderer = function () {
  22202. if (!this._boundingBoxRenderer) {
  22203. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  22204. }
  22205. return this._boundingBoxRenderer;
  22206. };
  22207. Scene.prototype.getOutlineRenderer = function () {
  22208. return this._outlineRenderer;
  22209. };
  22210. Scene.prototype.getEngine = function () {
  22211. return this._engine;
  22212. };
  22213. Scene.prototype.getTotalVertices = function () {
  22214. return this._totalVertices.current;
  22215. };
  22216. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  22217. get: function () {
  22218. return this._totalVertices;
  22219. },
  22220. enumerable: true,
  22221. configurable: true
  22222. });
  22223. Scene.prototype.getActiveIndices = function () {
  22224. return this._activeIndices.current;
  22225. };
  22226. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  22227. get: function () {
  22228. return this._activeIndices;
  22229. },
  22230. enumerable: true,
  22231. configurable: true
  22232. });
  22233. Scene.prototype.getActiveParticles = function () {
  22234. return this._activeParticles.current;
  22235. };
  22236. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  22237. get: function () {
  22238. return this._activeParticles;
  22239. },
  22240. enumerable: true,
  22241. configurable: true
  22242. });
  22243. Scene.prototype.getActiveBones = function () {
  22244. return this._activeBones.current;
  22245. };
  22246. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  22247. get: function () {
  22248. return this._activeBones;
  22249. },
  22250. enumerable: true,
  22251. configurable: true
  22252. });
  22253. // Stats
  22254. Scene.prototype.getInterFramePerfCounter = function () {
  22255. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  22256. return 0;
  22257. };
  22258. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  22259. get: function () {
  22260. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  22261. return null;
  22262. },
  22263. enumerable: true,
  22264. configurable: true
  22265. });
  22266. Scene.prototype.getLastFrameDuration = function () {
  22267. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  22268. return 0;
  22269. };
  22270. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  22271. get: function () {
  22272. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  22273. return null;
  22274. },
  22275. enumerable: true,
  22276. configurable: true
  22277. });
  22278. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  22279. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  22280. return 0;
  22281. };
  22282. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  22283. get: function () {
  22284. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  22285. return null;
  22286. },
  22287. enumerable: true,
  22288. configurable: true
  22289. });
  22290. Scene.prototype.getActiveMeshes = function () {
  22291. return this._activeMeshes;
  22292. };
  22293. Scene.prototype.getRenderTargetsDuration = function () {
  22294. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  22295. return 0;
  22296. };
  22297. Scene.prototype.getRenderDuration = function () {
  22298. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  22299. return 0;
  22300. };
  22301. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  22302. get: function () {
  22303. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  22304. return null;
  22305. },
  22306. enumerable: true,
  22307. configurable: true
  22308. });
  22309. Scene.prototype.getParticlesDuration = function () {
  22310. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  22311. return 0;
  22312. };
  22313. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  22314. get: function () {
  22315. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  22316. return null;
  22317. },
  22318. enumerable: true,
  22319. configurable: true
  22320. });
  22321. Scene.prototype.getSpritesDuration = function () {
  22322. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  22323. return 0;
  22324. };
  22325. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  22326. get: function () {
  22327. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  22328. return null;
  22329. },
  22330. enumerable: true,
  22331. configurable: true
  22332. });
  22333. Scene.prototype.getAnimationRatio = function () {
  22334. return this._animationRatio;
  22335. };
  22336. Scene.prototype.getRenderId = function () {
  22337. return this._renderId;
  22338. };
  22339. Scene.prototype.incrementRenderId = function () {
  22340. this._renderId++;
  22341. };
  22342. Scene.prototype._updatePointerPosition = function (evt) {
  22343. var canvasRect = this._engine.getRenderingCanvasClientRect();
  22344. if (!canvasRect) {
  22345. return;
  22346. }
  22347. this._pointerX = evt.clientX - canvasRect.left;
  22348. this._pointerY = evt.clientY - canvasRect.top;
  22349. this._unTranslatedPointerX = this._pointerX;
  22350. this._unTranslatedPointerY = this._pointerY;
  22351. };
  22352. Scene.prototype._createUbo = function () {
  22353. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  22354. this._sceneUbo.addUniform("viewProjection", 16);
  22355. this._sceneUbo.addUniform("view", 16);
  22356. };
  22357. Scene.prototype._createAlternateUbo = function () {
  22358. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  22359. this._alternateSceneUbo.addUniform("viewProjection", 16);
  22360. this._alternateSceneUbo.addUniform("view", 16);
  22361. };
  22362. // Pointers handling
  22363. /**
  22364. * Use this method to simulate a pointer move on a mesh
  22365. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  22366. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  22367. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  22368. */
  22369. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  22370. var evt = new PointerEvent("pointermove", pointerEventInit);
  22371. return this._processPointerMove(pickResult, evt);
  22372. };
  22373. Scene.prototype._processPointerMove = function (pickResult, evt) {
  22374. var canvas = this._engine.getRenderingCanvas();
  22375. if (!canvas) {
  22376. return this;
  22377. }
  22378. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  22379. this.setPointerOverSprite(null);
  22380. this.setPointerOverMesh(pickResult.pickedMesh);
  22381. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  22382. if (this._pointerOverMesh.actionManager.hoverCursor) {
  22383. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  22384. }
  22385. else {
  22386. canvas.style.cursor = this.hoverCursor;
  22387. }
  22388. }
  22389. else {
  22390. canvas.style.cursor = this.defaultCursor;
  22391. }
  22392. }
  22393. else {
  22394. this.setPointerOverMesh(null);
  22395. // Sprites
  22396. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  22397. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  22398. this.setPointerOverSprite(pickResult.pickedSprite);
  22399. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  22400. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  22401. }
  22402. else {
  22403. canvas.style.cursor = this.hoverCursor;
  22404. }
  22405. }
  22406. else {
  22407. this.setPointerOverSprite(null);
  22408. // Restore pointer
  22409. canvas.style.cursor = this.defaultCursor;
  22410. }
  22411. }
  22412. if (pickResult) {
  22413. if (this.onPointerMove) {
  22414. this.onPointerMove(evt, pickResult);
  22415. }
  22416. if (this.onPointerObservable.hasObservers()) {
  22417. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  22418. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22419. this.onPointerObservable.notifyObservers(pi, type);
  22420. }
  22421. }
  22422. return this;
  22423. };
  22424. /**
  22425. * Use this method to simulate a pointer down on a mesh
  22426. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  22427. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  22428. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  22429. */
  22430. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  22431. var evt = new PointerEvent("pointerdown", pointerEventInit);
  22432. return this._processPointerDown(pickResult, evt);
  22433. };
  22434. Scene.prototype._processPointerDown = function (pickResult, evt) {
  22435. var _this = this;
  22436. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  22437. this._pickedDownMesh = pickResult.pickedMesh;
  22438. var actionManager = pickResult.pickedMesh.actionManager;
  22439. if (actionManager) {
  22440. if (actionManager.hasPickTriggers) {
  22441. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22442. switch (evt.button) {
  22443. case 0:
  22444. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22445. break;
  22446. case 1:
  22447. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22448. break;
  22449. case 2:
  22450. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22451. break;
  22452. }
  22453. }
  22454. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  22455. window.setTimeout(function () {
  22456. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, function (mesh) { return (mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger) && mesh == _this._pickedDownMesh); }, false, _this.cameraToUseForPointers);
  22457. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  22458. if (_this._totalPointersPressed !== 0 &&
  22459. ((new Date().getTime() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  22460. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  22461. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  22462. _this._startingPointerTime = 0;
  22463. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22464. }
  22465. }
  22466. }, Scene.LongPressDelay);
  22467. }
  22468. }
  22469. }
  22470. if (pickResult) {
  22471. if (this.onPointerDown) {
  22472. this.onPointerDown(evt, pickResult);
  22473. }
  22474. if (this.onPointerObservable.hasObservers()) {
  22475. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  22476. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22477. this.onPointerObservable.notifyObservers(pi, type);
  22478. }
  22479. }
  22480. return this;
  22481. };
  22482. /**
  22483. * Use this method to simulate a pointer up on a mesh
  22484. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  22485. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  22486. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  22487. */
  22488. Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit) {
  22489. var evt = new PointerEvent("pointerup", pointerEventInit);
  22490. var clickInfo = new ClickInfo();
  22491. clickInfo.singleClick = true;
  22492. clickInfo.ignore = true;
  22493. return this._processPointerUp(pickResult, evt, clickInfo);
  22494. };
  22495. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  22496. if (pickResult && pickResult && pickResult.pickedMesh) {
  22497. this._pickedUpMesh = pickResult.pickedMesh;
  22498. if (this._pickedDownMesh === this._pickedUpMesh) {
  22499. if (this.onPointerPick) {
  22500. this.onPointerPick(evt, pickResult);
  22501. }
  22502. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  22503. var type = BABYLON.PointerEventTypes.POINTERPICK;
  22504. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22505. this.onPointerObservable.notifyObservers(pi, type);
  22506. }
  22507. }
  22508. if (pickResult.pickedMesh.actionManager) {
  22509. if (clickInfo.ignore) {
  22510. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22511. }
  22512. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  22513. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22514. }
  22515. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  22516. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22517. }
  22518. }
  22519. }
  22520. if (this._pickedDownMesh &&
  22521. this._pickedDownMesh.actionManager &&
  22522. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  22523. this._pickedDownMesh !== this._pickedUpMesh) {
  22524. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  22525. }
  22526. if (this.onPointerUp) {
  22527. this.onPointerUp(evt, pickResult);
  22528. }
  22529. if (this.onPointerObservable.hasObservers()) {
  22530. if (!clickInfo.ignore) {
  22531. if (!clickInfo.hasSwiped) {
  22532. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  22533. var type = BABYLON.PointerEventTypes.POINTERTAP;
  22534. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22535. this.onPointerObservable.notifyObservers(pi, type);
  22536. }
  22537. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  22538. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  22539. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22540. this.onPointerObservable.notifyObservers(pi, type);
  22541. }
  22542. }
  22543. }
  22544. else {
  22545. var type = BABYLON.PointerEventTypes.POINTERUP;
  22546. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22547. this.onPointerObservable.notifyObservers(pi, type);
  22548. }
  22549. }
  22550. return this;
  22551. };
  22552. /**
  22553. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  22554. * @param attachUp defines if you want to attach events to pointerup
  22555. * @param attachDown defines if you want to attach events to pointerdown
  22556. * @param attachMove defines if you want to attach events to pointermove
  22557. */
  22558. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  22559. var _this = this;
  22560. if (attachUp === void 0) { attachUp = true; }
  22561. if (attachDown === void 0) { attachDown = true; }
  22562. if (attachMove === void 0) { attachMove = true; }
  22563. this._initActionManager = function (act, clickInfo) {
  22564. if (!_this._meshPickProceed) {
  22565. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  22566. _this._currentPickResult = pickResult;
  22567. if (pickResult) {
  22568. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  22569. }
  22570. _this._meshPickProceed = true;
  22571. }
  22572. return act;
  22573. };
  22574. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  22575. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  22576. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  22577. btn !== _this._previousButtonPressed) {
  22578. _this._doubleClickOccured = false;
  22579. clickInfo.singleClick = true;
  22580. clickInfo.ignore = false;
  22581. cb(clickInfo, _this._currentPickResult);
  22582. }
  22583. };
  22584. this._initClickEvent = function (obs1, obs2, evt, cb) {
  22585. var clickInfo = new ClickInfo();
  22586. _this._currentPickResult = null;
  22587. var act = null;
  22588. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  22589. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  22590. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  22591. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  22592. act = _this._initActionManager(act, clickInfo);
  22593. if (act)
  22594. checkPicking = act.hasPickTriggers;
  22595. }
  22596. if (checkPicking) {
  22597. var btn = evt.button;
  22598. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  22599. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  22600. if (!clickInfo.hasSwiped) {
  22601. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  22602. if (!checkSingleClickImmediately) {
  22603. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  22604. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  22605. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  22606. act = _this._initActionManager(act, clickInfo);
  22607. if (act)
  22608. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  22609. }
  22610. }
  22611. if (checkSingleClickImmediately) {
  22612. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  22613. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  22614. btn !== _this._previousButtonPressed) {
  22615. clickInfo.singleClick = true;
  22616. cb(clickInfo, _this._currentPickResult);
  22617. }
  22618. }
  22619. else {
  22620. // wait that no double click has been raised during the double click delay
  22621. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  22622. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  22623. }
  22624. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  22625. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  22626. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  22627. act = _this._initActionManager(act, clickInfo);
  22628. if (act)
  22629. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  22630. }
  22631. if (checkDoubleClick) {
  22632. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  22633. if (btn === _this._previousButtonPressed &&
  22634. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  22635. !_this._doubleClickOccured) {
  22636. // pointer has not moved for 2 clicks, it's a double click
  22637. if (!clickInfo.hasSwiped &&
  22638. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  22639. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  22640. _this._previousStartingPointerTime = 0;
  22641. _this._doubleClickOccured = true;
  22642. clickInfo.doubleClick = true;
  22643. clickInfo.ignore = false;
  22644. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  22645. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  22646. }
  22647. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  22648. cb(clickInfo, _this._currentPickResult);
  22649. }
  22650. else {
  22651. _this._doubleClickOccured = false;
  22652. _this._previousStartingPointerTime = _this._startingPointerTime;
  22653. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  22654. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  22655. _this._previousButtonPressed = btn;
  22656. if (Scene.ExclusiveDoubleClickMode) {
  22657. if (_this._previousDelayedSimpleClickTimeout) {
  22658. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  22659. }
  22660. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  22661. cb(clickInfo, _this._previousPickResult);
  22662. }
  22663. else {
  22664. cb(clickInfo, _this._currentPickResult);
  22665. }
  22666. }
  22667. }
  22668. else {
  22669. _this._doubleClickOccured = false;
  22670. _this._previousStartingPointerTime = _this._startingPointerTime;
  22671. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  22672. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  22673. _this._previousButtonPressed = btn;
  22674. }
  22675. }
  22676. }
  22677. }
  22678. clickInfo.ignore = true;
  22679. cb(clickInfo, _this._currentPickResult);
  22680. };
  22681. this._spritePredicate = function (sprite) {
  22682. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  22683. };
  22684. this._onPointerMove = function (evt) {
  22685. _this._updatePointerPosition(evt);
  22686. // PreObservable support
  22687. if (_this.onPrePointerObservable.hasObservers()) {
  22688. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  22689. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22690. _this.onPrePointerObservable.notifyObservers(pi, type);
  22691. if (pi.skipOnPointerObservable) {
  22692. return;
  22693. }
  22694. }
  22695. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  22696. return;
  22697. }
  22698. if (!_this.pointerMovePredicate) {
  22699. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  22700. }
  22701. // Meshes
  22702. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  22703. _this._processPointerMove(pickResult, evt);
  22704. };
  22705. this._onPointerDown = function (evt) {
  22706. _this._totalPointersPressed++;
  22707. _this._pickedDownMesh = null;
  22708. _this._meshPickProceed = false;
  22709. _this._updatePointerPosition(evt);
  22710. if (_this.preventDefaultOnPointerDown && canvas) {
  22711. evt.preventDefault();
  22712. canvas.focus();
  22713. }
  22714. // PreObservable support
  22715. if (_this.onPrePointerObservable.hasObservers()) {
  22716. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  22717. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22718. _this.onPrePointerObservable.notifyObservers(pi, type);
  22719. if (pi.skipOnPointerObservable) {
  22720. return;
  22721. }
  22722. }
  22723. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  22724. return;
  22725. }
  22726. _this._startingPointerPosition.x = _this._pointerX;
  22727. _this._startingPointerPosition.y = _this._pointerY;
  22728. _this._startingPointerTime = new Date().getTime();
  22729. if (!_this.pointerDownPredicate) {
  22730. _this.pointerDownPredicate = function (mesh) {
  22731. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  22732. };
  22733. }
  22734. // Meshes
  22735. _this._pickedDownMesh = null;
  22736. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  22737. _this._processPointerDown(pickResult, evt);
  22738. // Sprites
  22739. _this._pickedDownSprite = null;
  22740. if (_this.spriteManagers.length > 0) {
  22741. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  22742. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  22743. if (pickResult.pickedSprite.actionManager) {
  22744. _this._pickedDownSprite = pickResult.pickedSprite;
  22745. switch (evt.button) {
  22746. case 0:
  22747. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22748. break;
  22749. case 1:
  22750. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22751. break;
  22752. case 2:
  22753. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22754. break;
  22755. }
  22756. if (pickResult.pickedSprite.actionManager) {
  22757. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22758. }
  22759. }
  22760. }
  22761. }
  22762. };
  22763. this._onPointerUp = function (evt) {
  22764. if (_this._totalPointersPressed === 0) {
  22765. return; // So we need to test it the pointer down was pressed before.
  22766. }
  22767. _this._totalPointersPressed--;
  22768. _this._pickedUpMesh = null;
  22769. _this._meshPickProceed = false;
  22770. _this._updatePointerPosition(evt);
  22771. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  22772. // PreObservable support
  22773. if (_this.onPrePointerObservable.hasObservers()) {
  22774. if (!clickInfo.ignore) {
  22775. if (!clickInfo.hasSwiped) {
  22776. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  22777. var type = BABYLON.PointerEventTypes.POINTERTAP;
  22778. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22779. _this.onPrePointerObservable.notifyObservers(pi, type);
  22780. if (pi.skipOnPointerObservable) {
  22781. return;
  22782. }
  22783. }
  22784. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  22785. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  22786. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22787. _this.onPrePointerObservable.notifyObservers(pi, type);
  22788. if (pi.skipOnPointerObservable) {
  22789. return;
  22790. }
  22791. }
  22792. }
  22793. }
  22794. else {
  22795. var type = BABYLON.PointerEventTypes.POINTERUP;
  22796. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22797. _this.onPrePointerObservable.notifyObservers(pi, type);
  22798. if (pi.skipOnPointerObservable) {
  22799. return;
  22800. }
  22801. }
  22802. }
  22803. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  22804. return;
  22805. }
  22806. if (!_this.pointerUpPredicate) {
  22807. _this.pointerUpPredicate = function (mesh) {
  22808. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  22809. };
  22810. }
  22811. // Meshes
  22812. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  22813. _this._initActionManager(null, clickInfo);
  22814. }
  22815. if (!pickResult) {
  22816. pickResult = _this._currentPickResult;
  22817. }
  22818. _this._processPointerUp(pickResult, evt, clickInfo);
  22819. // Sprites
  22820. if (_this.spriteManagers.length > 0) {
  22821. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  22822. if (spritePickResult) {
  22823. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  22824. if (spritePickResult.pickedSprite.actionManager) {
  22825. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  22826. if (spritePickResult.pickedSprite.actionManager) {
  22827. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  22828. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  22829. }
  22830. }
  22831. }
  22832. }
  22833. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  22834. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  22835. }
  22836. }
  22837. }
  22838. _this._previousPickResult = _this._currentPickResult;
  22839. });
  22840. };
  22841. this._onKeyDown = function (evt) {
  22842. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  22843. if (_this.onPreKeyboardObservable.hasObservers()) {
  22844. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  22845. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  22846. if (pi.skipOnPointerObservable) {
  22847. return;
  22848. }
  22849. }
  22850. if (_this.onKeyboardObservable.hasObservers()) {
  22851. var pi = new BABYLON.KeyboardInfo(type, evt);
  22852. _this.onKeyboardObservable.notifyObservers(pi, type);
  22853. }
  22854. if (_this.actionManager) {
  22855. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  22856. }
  22857. };
  22858. this._onKeyUp = function (evt) {
  22859. var type = BABYLON.KeyboardEventTypes.KEYUP;
  22860. if (_this.onPreKeyboardObservable.hasObservers()) {
  22861. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  22862. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  22863. if (pi.skipOnPointerObservable) {
  22864. return;
  22865. }
  22866. }
  22867. if (_this.onKeyboardObservable.hasObservers()) {
  22868. var pi = new BABYLON.KeyboardInfo(type, evt);
  22869. _this.onKeyboardObservable.notifyObservers(pi, type);
  22870. }
  22871. if (_this.actionManager) {
  22872. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  22873. }
  22874. };
  22875. var engine = this.getEngine();
  22876. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  22877. if (!canvas) {
  22878. return;
  22879. }
  22880. canvas.addEventListener("keydown", _this._onKeyDown, false);
  22881. canvas.addEventListener("keyup", _this._onKeyUp, false);
  22882. });
  22883. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  22884. if (!canvas) {
  22885. return;
  22886. }
  22887. canvas.removeEventListener("keydown", _this._onKeyDown);
  22888. canvas.removeEventListener("keyup", _this._onKeyUp);
  22889. });
  22890. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  22891. var canvas = this._engine.getRenderingCanvas();
  22892. if (!canvas) {
  22893. return;
  22894. }
  22895. if (attachMove) {
  22896. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  22897. // Wheel
  22898. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  22899. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  22900. }
  22901. if (attachDown) {
  22902. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  22903. }
  22904. if (attachUp) {
  22905. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  22906. }
  22907. canvas.tabIndex = 1;
  22908. };
  22909. Scene.prototype.detachControl = function () {
  22910. var engine = this.getEngine();
  22911. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  22912. var canvas = engine.getRenderingCanvas();
  22913. if (!canvas) {
  22914. return;
  22915. }
  22916. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  22917. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  22918. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  22919. if (this._onCanvasBlurObserver) {
  22920. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  22921. }
  22922. if (this._onCanvasFocusObserver) {
  22923. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  22924. }
  22925. // Wheel
  22926. canvas.removeEventListener('mousewheel', this._onPointerMove);
  22927. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  22928. // Keyboard
  22929. canvas.removeEventListener("keydown", this._onKeyDown);
  22930. canvas.removeEventListener("keyup", this._onKeyUp);
  22931. // Observables
  22932. this.onKeyboardObservable.clear();
  22933. this.onPreKeyboardObservable.clear();
  22934. this.onPointerObservable.clear();
  22935. this.onPrePointerObservable.clear();
  22936. };
  22937. /**
  22938. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  22939. * Delay loaded resources are not taking in account
  22940. * @return true if all required resources are ready
  22941. */
  22942. Scene.prototype.isReady = function () {
  22943. if (this._isDisposed) {
  22944. return false;
  22945. }
  22946. if (this._pendingData.length > 0) {
  22947. return false;
  22948. }
  22949. var index;
  22950. var engine = this.getEngine();
  22951. // Geometries
  22952. for (index = 0; index < this._geometries.length; index++) {
  22953. var geometry = this._geometries[index];
  22954. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  22955. return false;
  22956. }
  22957. }
  22958. // Meshes
  22959. for (index = 0; index < this.meshes.length; index++) {
  22960. var mesh = this.meshes[index];
  22961. if (!mesh.isEnabled()) {
  22962. continue;
  22963. }
  22964. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  22965. continue;
  22966. }
  22967. if (!mesh.isReady(true)) {
  22968. return false;
  22969. }
  22970. // Effect layers
  22971. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  22972. for (var _i = 0, _a = this.effectLayers; _i < _a.length; _i++) {
  22973. var layer = _a[_i];
  22974. if (!layer.hasMesh(mesh)) {
  22975. continue;
  22976. }
  22977. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  22978. var subMesh = _c[_b];
  22979. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  22980. return false;
  22981. }
  22982. }
  22983. }
  22984. }
  22985. // Particles
  22986. for (var _d = 0, _e = this.particleSystems; _d < _e.length; _d++) {
  22987. var particleSystem = _e[_d];
  22988. if (!particleSystem.isReady()) {
  22989. return false;
  22990. }
  22991. }
  22992. return true;
  22993. };
  22994. Scene.prototype.resetCachedMaterial = function () {
  22995. this._cachedMaterial = null;
  22996. this._cachedEffect = null;
  22997. this._cachedVisibility = null;
  22998. };
  22999. Scene.prototype.registerBeforeRender = function (func) {
  23000. this.onBeforeRenderObservable.add(func);
  23001. };
  23002. Scene.prototype.unregisterBeforeRender = function (func) {
  23003. this.onBeforeRenderObservable.removeCallback(func);
  23004. };
  23005. Scene.prototype.registerAfterRender = function (func) {
  23006. this.onAfterRenderObservable.add(func);
  23007. };
  23008. Scene.prototype.unregisterAfterRender = function (func) {
  23009. this.onAfterRenderObservable.removeCallback(func);
  23010. };
  23011. Scene.prototype._executeOnceBeforeRender = function (func) {
  23012. var _this = this;
  23013. var execFunc = function () {
  23014. func();
  23015. setTimeout(function () {
  23016. _this.unregisterBeforeRender(execFunc);
  23017. });
  23018. };
  23019. this.registerBeforeRender(execFunc);
  23020. };
  23021. /**
  23022. * The provided function will run before render once and will be disposed afterwards.
  23023. * A timeout delay can be provided so that the function will be executed in N ms.
  23024. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  23025. * @param func The function to be executed.
  23026. * @param timeout optional delay in ms
  23027. */
  23028. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  23029. var _this = this;
  23030. if (timeout !== undefined) {
  23031. setTimeout(function () {
  23032. _this._executeOnceBeforeRender(func);
  23033. }, timeout);
  23034. }
  23035. else {
  23036. this._executeOnceBeforeRender(func);
  23037. }
  23038. };
  23039. Scene.prototype._addPendingData = function (data) {
  23040. this._pendingData.push(data);
  23041. };
  23042. Scene.prototype._removePendingData = function (data) {
  23043. var wasLoading = this.isLoading;
  23044. var index = this._pendingData.indexOf(data);
  23045. if (index !== -1) {
  23046. this._pendingData.splice(index, 1);
  23047. }
  23048. if (wasLoading && !this.isLoading) {
  23049. this.onDataLoadedObservable.notifyObservers(this);
  23050. }
  23051. };
  23052. Scene.prototype.getWaitingItemsCount = function () {
  23053. return this._pendingData.length;
  23054. };
  23055. Object.defineProperty(Scene.prototype, "isLoading", {
  23056. get: function () {
  23057. return this._pendingData.length > 0;
  23058. },
  23059. enumerable: true,
  23060. configurable: true
  23061. });
  23062. /**
  23063. * Registers a function to be executed when the scene is ready.
  23064. * @param {Function} func - the function to be executed.
  23065. */
  23066. Scene.prototype.executeWhenReady = function (func) {
  23067. var _this = this;
  23068. this.onReadyObservable.add(func);
  23069. if (this._executeWhenReadyTimeoutId !== -1) {
  23070. return;
  23071. }
  23072. this._executeWhenReadyTimeoutId = setTimeout(function () {
  23073. _this._checkIsReady();
  23074. }, 150);
  23075. };
  23076. /**
  23077. * Returns a promise that resolves when the scene is ready.
  23078. * @returns A promise that resolves when the scene is ready.
  23079. */
  23080. Scene.prototype.whenReadyAsync = function () {
  23081. var _this = this;
  23082. return new Promise(function (resolve) {
  23083. _this.executeWhenReady(function () {
  23084. resolve();
  23085. });
  23086. });
  23087. };
  23088. Scene.prototype._checkIsReady = function () {
  23089. var _this = this;
  23090. if (this.isReady()) {
  23091. this.onReadyObservable.notifyObservers(this);
  23092. this.onReadyObservable.clear();
  23093. this._executeWhenReadyTimeoutId = -1;
  23094. return;
  23095. }
  23096. this._executeWhenReadyTimeoutId = setTimeout(function () {
  23097. _this._checkIsReady();
  23098. }, 150);
  23099. };
  23100. // Animations
  23101. /**
  23102. * Will start the animation sequence of a given target
  23103. * @param target - the target
  23104. * @param {number} from - from which frame should animation start
  23105. * @param {number} to - till which frame should animation run.
  23106. * @param {boolean} [loop] - should the animation loop
  23107. * @param {number} [speedRatio] - the speed in which to run the animation
  23108. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  23109. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  23110. * Returns {BABYLON.Animatable} the animatable object created for this animation
  23111. * See BABYLON.Animatable
  23112. */
  23113. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  23114. if (speedRatio === void 0) { speedRatio = 1.0; }
  23115. if (from > to && speedRatio > 0) {
  23116. speedRatio *= -1;
  23117. }
  23118. this.stopAnimation(target);
  23119. if (!animatable) {
  23120. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  23121. }
  23122. // Local animations
  23123. if (target.animations) {
  23124. animatable.appendAnimations(target, target.animations);
  23125. }
  23126. // Children animations
  23127. if (target.getAnimatables) {
  23128. var animatables = target.getAnimatables();
  23129. for (var index = 0; index < animatables.length; index++) {
  23130. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  23131. }
  23132. }
  23133. animatable.reset();
  23134. return animatable;
  23135. };
  23136. /**
  23137. * Begin a new animation on a given node
  23138. * @param {BABYLON.Node} node defines the root node where the animation will take place
  23139. * @param {BABYLON.Animation[]} defines the list of animations to start
  23140. * @param {number} from defines the initial value
  23141. * @param {number} to defines the final value
  23142. * @param {boolean} loop defines if you want animation to loop (off by default)
  23143. * @param {number} speedRatio defines the speed ratio to apply to all animations
  23144. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  23145. * @returns the list of created animatables
  23146. */
  23147. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  23148. if (speedRatio === undefined) {
  23149. speedRatio = 1.0;
  23150. }
  23151. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  23152. return animatable;
  23153. };
  23154. /**
  23155. * Begin a new animation on a given node and its hierarchy
  23156. * @param {BABYLON.Node} node defines the root node where the animation will take place
  23157. * @param {boolean} directDescendantsOnly if true only direct descendants will be used, if false direct and also indirect (children of children, an so on in a recursive manner) descendants will be used.
  23158. * @param {BABYLON.Animation[]} defines the list of animations to start
  23159. * @param {number} from defines the initial value
  23160. * @param {number} to defines the final value
  23161. * @param {boolean} loop defines if you want animation to loop (off by default)
  23162. * @param {number} speedRatio defines the speed ratio to apply to all animations
  23163. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  23164. * @returns the list of animatables created for all nodes
  23165. */
  23166. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  23167. var children = target.getDescendants(directDescendantsOnly);
  23168. var result = [];
  23169. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  23170. var child = children_1[_i];
  23171. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  23172. }
  23173. return result;
  23174. };
  23175. Scene.prototype.getAnimatableByTarget = function (target) {
  23176. for (var index = 0; index < this._activeAnimatables.length; index++) {
  23177. if (this._activeAnimatables[index].target === target) {
  23178. return this._activeAnimatables[index];
  23179. }
  23180. }
  23181. return null;
  23182. };
  23183. Object.defineProperty(Scene.prototype, "animatables", {
  23184. get: function () {
  23185. return this._activeAnimatables;
  23186. },
  23187. enumerable: true,
  23188. configurable: true
  23189. });
  23190. /**
  23191. * Will stop the animation of the given target
  23192. * @param target - the target
  23193. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  23194. * @see beginAnimation
  23195. */
  23196. Scene.prototype.stopAnimation = function (target, animationName) {
  23197. var animatable = this.getAnimatableByTarget(target);
  23198. if (animatable) {
  23199. animatable.stop(animationName);
  23200. }
  23201. };
  23202. /**
  23203. * Stops and removes all animations that have been applied to the scene
  23204. */
  23205. Scene.prototype.stopAllAnimations = function () {
  23206. if (this._activeAnimatables) {
  23207. for (var i = 0; i < this._activeAnimatables.length; i++) {
  23208. this._activeAnimatables[i].stop();
  23209. }
  23210. this._activeAnimatables = [];
  23211. }
  23212. };
  23213. Scene.prototype._animate = function () {
  23214. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  23215. return;
  23216. }
  23217. // Getting time
  23218. var now = BABYLON.Tools.Now;
  23219. if (!this._animationTimeLast) {
  23220. if (this._pendingData.length > 0) {
  23221. return;
  23222. }
  23223. this._animationTimeLast = now;
  23224. }
  23225. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  23226. this._animationTime += deltaTime;
  23227. this._animationTimeLast = now;
  23228. for (var index = 0; index < this._activeAnimatables.length; index++) {
  23229. this._activeAnimatables[index]._animate(this._animationTime);
  23230. }
  23231. };
  23232. // Matrix
  23233. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  23234. this._useAlternateCameraConfiguration = active;
  23235. };
  23236. Scene.prototype.getViewMatrix = function () {
  23237. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  23238. };
  23239. Scene.prototype.getProjectionMatrix = function () {
  23240. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  23241. };
  23242. Scene.prototype.getTransformMatrix = function () {
  23243. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  23244. };
  23245. Scene.prototype.setTransformMatrix = function (view, projection) {
  23246. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  23247. return;
  23248. }
  23249. this._viewUpdateFlag = view.updateFlag;
  23250. this._projectionUpdateFlag = projection.updateFlag;
  23251. this._viewMatrix = view;
  23252. this._projectionMatrix = projection;
  23253. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  23254. // Update frustum
  23255. if (!this._frustumPlanes) {
  23256. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  23257. }
  23258. else {
  23259. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  23260. }
  23261. if (this.activeCamera && this.activeCamera._alternateCamera) {
  23262. var otherCamera = this.activeCamera._alternateCamera;
  23263. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  23264. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  23265. }
  23266. if (this._sceneUbo.useUbo) {
  23267. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  23268. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  23269. this._sceneUbo.update();
  23270. }
  23271. };
  23272. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  23273. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  23274. return;
  23275. }
  23276. this._alternateViewUpdateFlag = view.updateFlag;
  23277. this._alternateProjectionUpdateFlag = projection.updateFlag;
  23278. this._alternateViewMatrix = view;
  23279. this._alternateProjectionMatrix = projection;
  23280. if (!this._alternateTransformMatrix) {
  23281. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  23282. }
  23283. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  23284. if (!this._alternateSceneUbo) {
  23285. this._createAlternateUbo();
  23286. }
  23287. if (this._alternateSceneUbo.useUbo) {
  23288. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  23289. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  23290. this._alternateSceneUbo.update();
  23291. }
  23292. };
  23293. Scene.prototype.getSceneUniformBuffer = function () {
  23294. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  23295. };
  23296. // Methods
  23297. Scene.prototype.getUniqueId = function () {
  23298. var result = Scene._uniqueIdCounter;
  23299. Scene._uniqueIdCounter++;
  23300. return result;
  23301. };
  23302. Scene.prototype.addMesh = function (newMesh) {
  23303. this.meshes.push(newMesh);
  23304. //notify the collision coordinator
  23305. if (this.collisionCoordinator) {
  23306. this.collisionCoordinator.onMeshAdded(newMesh);
  23307. }
  23308. newMesh._resyncLightSources();
  23309. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  23310. };
  23311. Scene.prototype.removeMesh = function (toRemove) {
  23312. var index = this.meshes.indexOf(toRemove);
  23313. if (index !== -1) {
  23314. // Remove from the scene if mesh found
  23315. this.meshes.splice(index, 1);
  23316. }
  23317. this.onMeshRemovedObservable.notifyObservers(toRemove);
  23318. return index;
  23319. };
  23320. Scene.prototype.addTransformNode = function (newTransformNode) {
  23321. this.transformNodes.push(newTransformNode);
  23322. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  23323. };
  23324. Scene.prototype.removeTransformNode = function (toRemove) {
  23325. var index = this.transformNodes.indexOf(toRemove);
  23326. if (index !== -1) {
  23327. // Remove from the scene if found
  23328. this.transformNodes.splice(index, 1);
  23329. }
  23330. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  23331. return index;
  23332. };
  23333. Scene.prototype.removeSkeleton = function (toRemove) {
  23334. var index = this.skeletons.indexOf(toRemove);
  23335. if (index !== -1) {
  23336. // Remove from the scene if found
  23337. this.skeletons.splice(index, 1);
  23338. }
  23339. return index;
  23340. };
  23341. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  23342. var index = this.morphTargetManagers.indexOf(toRemove);
  23343. if (index !== -1) {
  23344. // Remove from the scene if found
  23345. this.morphTargetManagers.splice(index, 1);
  23346. }
  23347. return index;
  23348. };
  23349. Scene.prototype.removeLight = function (toRemove) {
  23350. var index = this.lights.indexOf(toRemove);
  23351. if (index !== -1) {
  23352. // Remove from meshes
  23353. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  23354. var mesh = _a[_i];
  23355. mesh._removeLightSource(toRemove);
  23356. }
  23357. // Remove from the scene if mesh found
  23358. this.lights.splice(index, 1);
  23359. this.sortLightsByPriority();
  23360. }
  23361. this.onLightRemovedObservable.notifyObservers(toRemove);
  23362. return index;
  23363. };
  23364. Scene.prototype.removeCamera = function (toRemove) {
  23365. var index = this.cameras.indexOf(toRemove);
  23366. if (index !== -1) {
  23367. // Remove from the scene if mesh found
  23368. this.cameras.splice(index, 1);
  23369. }
  23370. // Remove from activeCameras
  23371. var index2 = this.activeCameras.indexOf(toRemove);
  23372. if (index2 !== -1) {
  23373. // Remove from the scene if mesh found
  23374. this.activeCameras.splice(index2, 1);
  23375. }
  23376. // Reset the activeCamera
  23377. if (this.activeCamera === toRemove) {
  23378. if (this.cameras.length > 0) {
  23379. this.activeCamera = this.cameras[0];
  23380. }
  23381. else {
  23382. this.activeCamera = null;
  23383. }
  23384. }
  23385. this.onCameraRemovedObservable.notifyObservers(toRemove);
  23386. return index;
  23387. };
  23388. Scene.prototype.removeParticleSystem = function (toRemove) {
  23389. var index = this.particleSystems.indexOf(toRemove);
  23390. if (index !== -1) {
  23391. this.particleSystems.splice(index, 1);
  23392. }
  23393. return index;
  23394. };
  23395. ;
  23396. Scene.prototype.removeAnimation = function (toRemove) {
  23397. var index = this.animations.indexOf(toRemove);
  23398. if (index !== -1) {
  23399. this.animations.splice(index, 1);
  23400. }
  23401. return index;
  23402. };
  23403. ;
  23404. Scene.prototype.removeMultiMaterial = function (toRemove) {
  23405. var index = this.multiMaterials.indexOf(toRemove);
  23406. if (index !== -1) {
  23407. this.multiMaterials.splice(index, 1);
  23408. }
  23409. return index;
  23410. };
  23411. ;
  23412. Scene.prototype.removeMaterial = function (toRemove) {
  23413. var index = this.materials.indexOf(toRemove);
  23414. if (index !== -1) {
  23415. this.materials.splice(index, 1);
  23416. }
  23417. return index;
  23418. };
  23419. ;
  23420. Scene.prototype.removeLensFlareSystem = function (toRemove) {
  23421. var index = this.lensFlareSystems.indexOf(toRemove);
  23422. if (index !== -1) {
  23423. this.lensFlareSystems.splice(index, 1);
  23424. }
  23425. return index;
  23426. };
  23427. ;
  23428. Scene.prototype.removeActionManager = function (toRemove) {
  23429. var index = this._actionManagers.indexOf(toRemove);
  23430. if (index !== -1) {
  23431. this._actionManagers.splice(index, 1);
  23432. }
  23433. return index;
  23434. };
  23435. ;
  23436. Scene.prototype.addLight = function (newLight) {
  23437. this.lights.push(newLight);
  23438. this.sortLightsByPriority();
  23439. // Add light to all meshes (To support if the light is removed and then readded)
  23440. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  23441. var mesh = _a[_i];
  23442. if (mesh._lightSources.indexOf(newLight) === -1) {
  23443. mesh._lightSources.push(newLight);
  23444. mesh._resyncLightSources();
  23445. }
  23446. }
  23447. this.onNewLightAddedObservable.notifyObservers(newLight);
  23448. };
  23449. Scene.prototype.sortLightsByPriority = function () {
  23450. if (this.requireLightSorting) {
  23451. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  23452. }
  23453. };
  23454. Scene.prototype.addCamera = function (newCamera) {
  23455. this.cameras.push(newCamera);
  23456. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  23457. };
  23458. Scene.prototype.addSkeleton = function (newSkeleton) {
  23459. this.skeletons.push(newSkeleton);
  23460. };
  23461. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  23462. this.particleSystems.push(newParticleSystem);
  23463. };
  23464. Scene.prototype.addAnimation = function (newAnimation) {
  23465. this.animations.push(newAnimation);
  23466. };
  23467. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  23468. this.multiMaterials.push(newMultiMaterial);
  23469. };
  23470. Scene.prototype.addMaterial = function (newMaterial) {
  23471. this.materials.push(newMaterial);
  23472. };
  23473. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  23474. this.morphTargetManagers.push(newMorphTargetManager);
  23475. };
  23476. Scene.prototype.addGeometry = function (newGeometrie) {
  23477. this._geometries.push(newGeometrie);
  23478. };
  23479. Scene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  23480. this.lensFlareSystems.push(newLensFlareSystem);
  23481. };
  23482. Scene.prototype.addActionManager = function (newActionManager) {
  23483. this._actionManagers.push(newActionManager);
  23484. };
  23485. /**
  23486. * Switch active camera
  23487. * @param {Camera} newCamera - new active camera
  23488. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  23489. */
  23490. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  23491. if (attachControl === void 0) { attachControl = true; }
  23492. var canvas = this._engine.getRenderingCanvas();
  23493. if (!canvas) {
  23494. return;
  23495. }
  23496. if (this.activeCamera) {
  23497. this.activeCamera.detachControl(canvas);
  23498. }
  23499. this.activeCamera = newCamera;
  23500. if (attachControl) {
  23501. newCamera.attachControl(canvas);
  23502. }
  23503. };
  23504. /**
  23505. * sets the active camera of the scene using its ID
  23506. * @param {string} id - the camera's ID
  23507. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  23508. * @see activeCamera
  23509. */
  23510. Scene.prototype.setActiveCameraByID = function (id) {
  23511. var camera = this.getCameraByID(id);
  23512. if (camera) {
  23513. this.activeCamera = camera;
  23514. return camera;
  23515. }
  23516. return null;
  23517. };
  23518. /**
  23519. * sets the active camera of the scene using its name
  23520. * @param {string} name - the camera's name
  23521. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  23522. * @see activeCamera
  23523. */
  23524. Scene.prototype.setActiveCameraByName = function (name) {
  23525. var camera = this.getCameraByName(name);
  23526. if (camera) {
  23527. this.activeCamera = camera;
  23528. return camera;
  23529. }
  23530. return null;
  23531. };
  23532. /**
  23533. * get an animation group using its name
  23534. * @param {string} the material's name
  23535. * @return {BABYLON.AnimationGroup|null} the animation group or null if none found.
  23536. */
  23537. Scene.prototype.getAnimationGroupByName = function (name) {
  23538. for (var index = 0; index < this.animationGroups.length; index++) {
  23539. if (this.animationGroups[index].name === name) {
  23540. return this.animationGroups[index];
  23541. }
  23542. }
  23543. return null;
  23544. };
  23545. /**
  23546. * get a material using its id
  23547. * @param {string} the material's ID
  23548. * @return {BABYLON.Material|null} the material or null if none found.
  23549. */
  23550. Scene.prototype.getMaterialByID = function (id) {
  23551. for (var index = 0; index < this.materials.length; index++) {
  23552. if (this.materials[index].id === id) {
  23553. return this.materials[index];
  23554. }
  23555. }
  23556. return null;
  23557. };
  23558. /**
  23559. * get a material using its name
  23560. * @param {string} the material's name
  23561. * @return {BABYLON.Material|null} the material or null if none found.
  23562. */
  23563. Scene.prototype.getMaterialByName = function (name) {
  23564. for (var index = 0; index < this.materials.length; index++) {
  23565. if (this.materials[index].name === name) {
  23566. return this.materials[index];
  23567. }
  23568. }
  23569. return null;
  23570. };
  23571. Scene.prototype.getLensFlareSystemByName = function (name) {
  23572. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  23573. if (this.lensFlareSystems[index].name === name) {
  23574. return this.lensFlareSystems[index];
  23575. }
  23576. }
  23577. return null;
  23578. };
  23579. Scene.prototype.getLensFlareSystemByID = function (id) {
  23580. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  23581. if (this.lensFlareSystems[index].id === id) {
  23582. return this.lensFlareSystems[index];
  23583. }
  23584. }
  23585. return null;
  23586. };
  23587. Scene.prototype.getCameraByID = function (id) {
  23588. for (var index = 0; index < this.cameras.length; index++) {
  23589. if (this.cameras[index].id === id) {
  23590. return this.cameras[index];
  23591. }
  23592. }
  23593. return null;
  23594. };
  23595. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  23596. for (var index = 0; index < this.cameras.length; index++) {
  23597. if (this.cameras[index].uniqueId === uniqueId) {
  23598. return this.cameras[index];
  23599. }
  23600. }
  23601. return null;
  23602. };
  23603. /**
  23604. * get a camera using its name
  23605. * @param {string} the camera's name
  23606. * @return {BABYLON.Camera|null} the camera or null if none found.
  23607. */
  23608. Scene.prototype.getCameraByName = function (name) {
  23609. for (var index = 0; index < this.cameras.length; index++) {
  23610. if (this.cameras[index].name === name) {
  23611. return this.cameras[index];
  23612. }
  23613. }
  23614. return null;
  23615. };
  23616. /**
  23617. * get a bone using its id
  23618. * @param {string} the bone's id
  23619. * @return {BABYLON.Bone|null} the bone or null if not found
  23620. */
  23621. Scene.prototype.getBoneByID = function (id) {
  23622. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  23623. var skeleton = this.skeletons[skeletonIndex];
  23624. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  23625. if (skeleton.bones[boneIndex].id === id) {
  23626. return skeleton.bones[boneIndex];
  23627. }
  23628. }
  23629. }
  23630. return null;
  23631. };
  23632. /**
  23633. * get a bone using its id
  23634. * @param {string} the bone's name
  23635. * @return {BABYLON.Bone|null} the bone or null if not found
  23636. */
  23637. Scene.prototype.getBoneByName = function (name) {
  23638. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  23639. var skeleton = this.skeletons[skeletonIndex];
  23640. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  23641. if (skeleton.bones[boneIndex].name === name) {
  23642. return skeleton.bones[boneIndex];
  23643. }
  23644. }
  23645. }
  23646. return null;
  23647. };
  23648. /**
  23649. * get a light node using its name
  23650. * @param {string} the light's name
  23651. * @return {BABYLON.Light|null} the light or null if none found.
  23652. */
  23653. Scene.prototype.getLightByName = function (name) {
  23654. for (var index = 0; index < this.lights.length; index++) {
  23655. if (this.lights[index].name === name) {
  23656. return this.lights[index];
  23657. }
  23658. }
  23659. return null;
  23660. };
  23661. /**
  23662. * get a light node using its ID
  23663. * @param {string} the light's id
  23664. * @return {BABYLON.Light|null} the light or null if none found.
  23665. */
  23666. Scene.prototype.getLightByID = function (id) {
  23667. for (var index = 0; index < this.lights.length; index++) {
  23668. if (this.lights[index].id === id) {
  23669. return this.lights[index];
  23670. }
  23671. }
  23672. return null;
  23673. };
  23674. /**
  23675. * get a light node using its scene-generated unique ID
  23676. * @param {number} the light's unique id
  23677. * @return {BABYLON.Light|null} the light or null if none found.
  23678. */
  23679. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  23680. for (var index = 0; index < this.lights.length; index++) {
  23681. if (this.lights[index].uniqueId === uniqueId) {
  23682. return this.lights[index];
  23683. }
  23684. }
  23685. return null;
  23686. };
  23687. /**
  23688. * get a particle system by id
  23689. * @param id {number} the particle system id
  23690. * @return {BABYLON.IParticleSystem|null} the corresponding system or null if none found.
  23691. */
  23692. Scene.prototype.getParticleSystemByID = function (id) {
  23693. for (var index = 0; index < this.particleSystems.length; index++) {
  23694. if (this.particleSystems[index].id === id) {
  23695. return this.particleSystems[index];
  23696. }
  23697. }
  23698. return null;
  23699. };
  23700. /**
  23701. * get a geometry using its ID
  23702. * @param {string} the geometry's id
  23703. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  23704. */
  23705. Scene.prototype.getGeometryByID = function (id) {
  23706. for (var index = 0; index < this._geometries.length; index++) {
  23707. if (this._geometries[index].id === id) {
  23708. return this._geometries[index];
  23709. }
  23710. }
  23711. return null;
  23712. };
  23713. /**
  23714. * add a new geometry to this scene.
  23715. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  23716. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  23717. * @return {boolean} was the geometry added or not
  23718. */
  23719. Scene.prototype.pushGeometry = function (geometry, force) {
  23720. if (!force && this.getGeometryByID(geometry.id)) {
  23721. return false;
  23722. }
  23723. this._geometries.push(geometry);
  23724. //notify the collision coordinator
  23725. if (this.collisionCoordinator) {
  23726. this.collisionCoordinator.onGeometryAdded(geometry);
  23727. }
  23728. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  23729. return true;
  23730. };
  23731. /**
  23732. * Removes an existing geometry
  23733. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  23734. * @return {boolean} was the geometry removed or not
  23735. */
  23736. Scene.prototype.removeGeometry = function (geometry) {
  23737. var index = this._geometries.indexOf(geometry);
  23738. if (index > -1) {
  23739. this._geometries.splice(index, 1);
  23740. //notify the collision coordinator
  23741. if (this.collisionCoordinator) {
  23742. this.collisionCoordinator.onGeometryDeleted(geometry);
  23743. }
  23744. this.onGeometryRemovedObservable.notifyObservers(geometry);
  23745. return true;
  23746. }
  23747. return false;
  23748. };
  23749. Scene.prototype.getGeometries = function () {
  23750. return this._geometries;
  23751. };
  23752. /**
  23753. * Get the first added mesh found of a given ID
  23754. * @param {string} id - the id to search for
  23755. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  23756. */
  23757. Scene.prototype.getMeshByID = function (id) {
  23758. for (var index = 0; index < this.meshes.length; index++) {
  23759. if (this.meshes[index].id === id) {
  23760. return this.meshes[index];
  23761. }
  23762. }
  23763. return null;
  23764. };
  23765. Scene.prototype.getMeshesByID = function (id) {
  23766. return this.meshes.filter(function (m) {
  23767. return m.id === id;
  23768. });
  23769. };
  23770. /**
  23771. * Get the first added transform node found of a given ID
  23772. * @param {string} id - the id to search for
  23773. * @return {BABYLON.TransformNode|null} the transform node found or null if not found at all.
  23774. */
  23775. Scene.prototype.getTransformNodeByID = function (id) {
  23776. for (var index = 0; index < this.transformNodes.length; index++) {
  23777. if (this.transformNodes[index].id === id) {
  23778. return this.transformNodes[index];
  23779. }
  23780. }
  23781. return null;
  23782. };
  23783. Scene.prototype.getTransformNodesByID = function (id) {
  23784. return this.transformNodes.filter(function (m) {
  23785. return m.id === id;
  23786. });
  23787. };
  23788. /**
  23789. * Get a mesh with its auto-generated unique id
  23790. * @param {number} uniqueId - the unique id to search for
  23791. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  23792. */
  23793. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  23794. for (var index = 0; index < this.meshes.length; index++) {
  23795. if (this.meshes[index].uniqueId === uniqueId) {
  23796. return this.meshes[index];
  23797. }
  23798. }
  23799. return null;
  23800. };
  23801. /**
  23802. * Get a the last added mesh found of a given ID
  23803. * @param {string} id - the id to search for
  23804. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  23805. */
  23806. Scene.prototype.getLastMeshByID = function (id) {
  23807. for (var index = this.meshes.length - 1; index >= 0; index--) {
  23808. if (this.meshes[index].id === id) {
  23809. return this.meshes[index];
  23810. }
  23811. }
  23812. return null;
  23813. };
  23814. /**
  23815. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  23816. * @param {string} id - the id to search for
  23817. * @return {BABYLON.Node|null} the node found or null if not found at all.
  23818. */
  23819. Scene.prototype.getLastEntryByID = function (id) {
  23820. var index;
  23821. for (index = this.meshes.length - 1; index >= 0; index--) {
  23822. if (this.meshes[index].id === id) {
  23823. return this.meshes[index];
  23824. }
  23825. }
  23826. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  23827. if (this.transformNodes[index].id === id) {
  23828. return this.transformNodes[index];
  23829. }
  23830. }
  23831. for (index = this.cameras.length - 1; index >= 0; index--) {
  23832. if (this.cameras[index].id === id) {
  23833. return this.cameras[index];
  23834. }
  23835. }
  23836. for (index = this.lights.length - 1; index >= 0; index--) {
  23837. if (this.lights[index].id === id) {
  23838. return this.lights[index];
  23839. }
  23840. }
  23841. return null;
  23842. };
  23843. Scene.prototype.getNodeByID = function (id) {
  23844. var mesh = this.getMeshByID(id);
  23845. if (mesh) {
  23846. return mesh;
  23847. }
  23848. var light = this.getLightByID(id);
  23849. if (light) {
  23850. return light;
  23851. }
  23852. var camera = this.getCameraByID(id);
  23853. if (camera) {
  23854. return camera;
  23855. }
  23856. var bone = this.getBoneByID(id);
  23857. return bone;
  23858. };
  23859. Scene.prototype.getNodeByName = function (name) {
  23860. var mesh = this.getMeshByName(name);
  23861. if (mesh) {
  23862. return mesh;
  23863. }
  23864. var light = this.getLightByName(name);
  23865. if (light) {
  23866. return light;
  23867. }
  23868. var camera = this.getCameraByName(name);
  23869. if (camera) {
  23870. return camera;
  23871. }
  23872. var bone = this.getBoneByName(name);
  23873. return bone;
  23874. };
  23875. Scene.prototype.getMeshByName = function (name) {
  23876. for (var index = 0; index < this.meshes.length; index++) {
  23877. if (this.meshes[index].name === name) {
  23878. return this.meshes[index];
  23879. }
  23880. }
  23881. return null;
  23882. };
  23883. Scene.prototype.getTransformNodeByName = function (name) {
  23884. for (var index = 0; index < this.transformNodes.length; index++) {
  23885. if (this.transformNodes[index].name === name) {
  23886. return this.transformNodes[index];
  23887. }
  23888. }
  23889. return null;
  23890. };
  23891. Scene.prototype.getSoundByName = function (name) {
  23892. var index;
  23893. if (BABYLON.AudioEngine) {
  23894. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  23895. if (this.mainSoundTrack.soundCollection[index].name === name) {
  23896. return this.mainSoundTrack.soundCollection[index];
  23897. }
  23898. }
  23899. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  23900. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  23901. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  23902. return this.soundTracks[sdIndex].soundCollection[index];
  23903. }
  23904. }
  23905. }
  23906. }
  23907. return null;
  23908. };
  23909. Scene.prototype.getLastSkeletonByID = function (id) {
  23910. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  23911. if (this.skeletons[index].id === id) {
  23912. return this.skeletons[index];
  23913. }
  23914. }
  23915. return null;
  23916. };
  23917. Scene.prototype.getSkeletonById = function (id) {
  23918. for (var index = 0; index < this.skeletons.length; index++) {
  23919. if (this.skeletons[index].id === id) {
  23920. return this.skeletons[index];
  23921. }
  23922. }
  23923. return null;
  23924. };
  23925. Scene.prototype.getSkeletonByName = function (name) {
  23926. for (var index = 0; index < this.skeletons.length; index++) {
  23927. if (this.skeletons[index].name === name) {
  23928. return this.skeletons[index];
  23929. }
  23930. }
  23931. return null;
  23932. };
  23933. Scene.prototype.getMorphTargetManagerById = function (id) {
  23934. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  23935. if (this.morphTargetManagers[index].uniqueId === id) {
  23936. return this.morphTargetManagers[index];
  23937. }
  23938. }
  23939. return null;
  23940. };
  23941. Scene.prototype.isActiveMesh = function (mesh) {
  23942. return (this._activeMeshes.indexOf(mesh) !== -1);
  23943. };
  23944. /**
  23945. * Return a the first highlight layer of the scene with a given name.
  23946. * @param name The name of the highlight layer to look for.
  23947. * @return The highlight layer if found otherwise null.
  23948. */
  23949. Scene.prototype.getHighlightLayerByName = function (name) {
  23950. for (var index = 0; index < this.effectLayers.length; index++) {
  23951. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.HighlightLayer.EffectName) {
  23952. return this.effectLayers[index];
  23953. }
  23954. }
  23955. return null;
  23956. };
  23957. /**
  23958. * Return a the first highlight layer of the scene with a given name.
  23959. * @param name The name of the highlight layer to look for.
  23960. * @return The highlight layer if found otherwise null.
  23961. */
  23962. Scene.prototype.getGlowLayerByName = function (name) {
  23963. for (var index = 0; index < this.effectLayers.length; index++) {
  23964. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.GlowLayer.EffectName) {
  23965. return this.effectLayers[index];
  23966. }
  23967. }
  23968. return null;
  23969. };
  23970. Object.defineProperty(Scene.prototype, "uid", {
  23971. /**
  23972. * Return a unique id as a string which can serve as an identifier for the scene
  23973. */
  23974. get: function () {
  23975. if (!this._uid) {
  23976. this._uid = BABYLON.Tools.RandomId();
  23977. }
  23978. return this._uid;
  23979. },
  23980. enumerable: true,
  23981. configurable: true
  23982. });
  23983. /**
  23984. * Add an externaly attached data from its key.
  23985. * This method call will fail and return false, if such key already exists.
  23986. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  23987. * @param key the unique key that identifies the data
  23988. * @param data the data object to associate to the key for this Engine instance
  23989. * @return true if no such key were already present and the data was added successfully, false otherwise
  23990. */
  23991. Scene.prototype.addExternalData = function (key, data) {
  23992. if (!this._externalData) {
  23993. this._externalData = new BABYLON.StringDictionary();
  23994. }
  23995. return this._externalData.add(key, data);
  23996. };
  23997. /**
  23998. * Get an externaly attached data from its key
  23999. * @param key the unique key that identifies the data
  24000. * @return the associated data, if present (can be null), or undefined if not present
  24001. */
  24002. Scene.prototype.getExternalData = function (key) {
  24003. if (!this._externalData) {
  24004. return null;
  24005. }
  24006. return this._externalData.get(key);
  24007. };
  24008. /**
  24009. * Get an externaly attached data from its key, create it using a factory if it's not already present
  24010. * @param key the unique key that identifies the data
  24011. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  24012. * @return the associated data, can be null if the factory returned null.
  24013. */
  24014. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  24015. if (!this._externalData) {
  24016. this._externalData = new BABYLON.StringDictionary();
  24017. }
  24018. return this._externalData.getOrAddWithFactory(key, factory);
  24019. };
  24020. /**
  24021. * Remove an externaly attached data from the Engine instance
  24022. * @param key the unique key that identifies the data
  24023. * @return true if the data was successfully removed, false if it doesn't exist
  24024. */
  24025. Scene.prototype.removeExternalData = function (key) {
  24026. return this._externalData.remove(key);
  24027. };
  24028. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  24029. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  24030. if (mesh.showSubMeshesBoundingBox) {
  24031. var boundingInfo = subMesh.getBoundingInfo();
  24032. if (boundingInfo !== null && boundingInfo !== undefined) {
  24033. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  24034. }
  24035. }
  24036. var material = subMesh.getMaterial();
  24037. if (material !== null && material !== undefined) {
  24038. // Render targets
  24039. if (material.getRenderTargetTextures !== undefined) {
  24040. if (this._processedMaterials.indexOf(material) === -1) {
  24041. this._processedMaterials.push(material);
  24042. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  24043. }
  24044. }
  24045. // Dispatch
  24046. this._activeIndices.addCount(subMesh.indexCount, false);
  24047. this._renderingManager.dispatch(subMesh, mesh, material);
  24048. }
  24049. }
  24050. };
  24051. /**
  24052. * Clear the processed materials smart array preventing retention point in material dispose.
  24053. */
  24054. Scene.prototype.freeProcessedMaterials = function () {
  24055. this._processedMaterials.dispose();
  24056. };
  24057. /**
  24058. * Clear the active meshes smart array preventing retention point in mesh dispose.
  24059. */
  24060. Scene.prototype.freeActiveMeshes = function () {
  24061. this._activeMeshes.dispose();
  24062. if (this.activeCamera && this.activeCamera._activeMeshes) {
  24063. this.activeCamera._activeMeshes.dispose();
  24064. }
  24065. if (this.activeCameras) {
  24066. for (var i = 0; i < this.activeCameras.length; i++) {
  24067. var activeCamera = this.activeCameras[i];
  24068. if (activeCamera && activeCamera._activeMeshes) {
  24069. activeCamera._activeMeshes.dispose();
  24070. }
  24071. }
  24072. }
  24073. };
  24074. /**
  24075. * Clear the info related to rendering groups preventing retention points during dispose.
  24076. */
  24077. Scene.prototype.freeRenderingGroups = function () {
  24078. if (this._renderingManager) {
  24079. this._renderingManager.freeRenderingGroups();
  24080. }
  24081. if (this.textures) {
  24082. for (var i = 0; i < this.textures.length; i++) {
  24083. var texture = this.textures[i];
  24084. if (texture && texture.renderList) {
  24085. texture.freeRenderingGroups();
  24086. }
  24087. }
  24088. }
  24089. };
  24090. Scene.prototype._isInIntermediateRendering = function () {
  24091. return this._intermediateRendering;
  24092. };
  24093. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  24094. this._activeMeshCandidateProvider = provider;
  24095. };
  24096. Scene.prototype.getActiveMeshCandidateProvider = function () {
  24097. return this._activeMeshCandidateProvider;
  24098. };
  24099. /**
  24100. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  24101. */
  24102. Scene.prototype.freezeActiveMeshes = function () {
  24103. if (!this.activeCamera) {
  24104. return this;
  24105. }
  24106. if (!this._frustumPlanes) {
  24107. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  24108. }
  24109. this._evaluateActiveMeshes();
  24110. this._activeMeshesFrozen = true;
  24111. return this;
  24112. };
  24113. /**
  24114. * Use this function to restart evaluating active meshes on every frame
  24115. */
  24116. Scene.prototype.unfreezeActiveMeshes = function () {
  24117. this._activeMeshesFrozen = false;
  24118. return this;
  24119. };
  24120. Scene.prototype._evaluateActiveMeshes = function () {
  24121. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  24122. return;
  24123. }
  24124. if (!this.activeCamera) {
  24125. return;
  24126. }
  24127. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  24128. this.activeCamera._activeMeshes.reset();
  24129. this._activeMeshes.reset();
  24130. this._renderingManager.reset();
  24131. this._processedMaterials.reset();
  24132. this._activeParticleSystems.reset();
  24133. this._activeSkeletons.reset();
  24134. this._softwareSkinnedMeshes.reset();
  24135. if (this._boundingBoxRenderer) {
  24136. this._boundingBoxRenderer.reset();
  24137. }
  24138. // Meshes
  24139. var meshes;
  24140. var len;
  24141. var checkIsEnabled = true;
  24142. // Determine mesh candidates
  24143. if (this._activeMeshCandidateProvider !== undefined) {
  24144. // Use _activeMeshCandidateProvider
  24145. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  24146. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  24147. if (meshes !== undefined) {
  24148. len = meshes.length;
  24149. }
  24150. else {
  24151. len = 0;
  24152. }
  24153. }
  24154. else if (this._selectionOctree !== undefined) {
  24155. // Octree
  24156. var selection = this._selectionOctree.select(this._frustumPlanes);
  24157. meshes = selection.data;
  24158. len = selection.length;
  24159. }
  24160. else {
  24161. // Full scene traversal
  24162. len = this.meshes.length;
  24163. meshes = this.meshes;
  24164. }
  24165. // Check each mesh
  24166. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  24167. mesh = meshes[meshIndex];
  24168. if (mesh.isBlocked) {
  24169. continue;
  24170. }
  24171. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  24172. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  24173. continue;
  24174. }
  24175. mesh.computeWorldMatrix();
  24176. // Intersections
  24177. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  24178. this._meshesForIntersections.pushNoDuplicate(mesh);
  24179. }
  24180. // Switch to current LOD
  24181. meshLOD = mesh.getLOD(this.activeCamera);
  24182. if (meshLOD === undefined || meshLOD === null) {
  24183. continue;
  24184. }
  24185. mesh._preActivate();
  24186. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  24187. this._activeMeshes.push(mesh);
  24188. this.activeCamera._activeMeshes.push(mesh);
  24189. mesh._activate(this._renderId);
  24190. if (meshLOD !== mesh) {
  24191. meshLOD._activate(this._renderId);
  24192. }
  24193. this._activeMesh(mesh, meshLOD);
  24194. }
  24195. }
  24196. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  24197. // Particle systems
  24198. if (this.particlesEnabled) {
  24199. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  24200. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  24201. var particleSystem = this.particleSystems[particleIndex];
  24202. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  24203. continue;
  24204. }
  24205. var emitter = particleSystem.emitter;
  24206. if (!emitter.position || emitter.isEnabled()) {
  24207. this._activeParticleSystems.push(particleSystem);
  24208. particleSystem.animate();
  24209. this._renderingManager.dispatchParticles(particleSystem);
  24210. }
  24211. }
  24212. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  24213. }
  24214. };
  24215. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  24216. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  24217. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  24218. mesh.skeleton.prepare();
  24219. }
  24220. if (!mesh.computeBonesUsingShaders) {
  24221. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  24222. }
  24223. }
  24224. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  24225. var boundingInfo = sourceMesh.getBoundingInfo();
  24226. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  24227. }
  24228. if (mesh !== undefined && mesh !== null
  24229. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  24230. // Submeshes Octrees
  24231. var len;
  24232. var subMeshes;
  24233. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  24234. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  24235. len = intersections.length;
  24236. subMeshes = intersections.data;
  24237. }
  24238. else {
  24239. subMeshes = mesh.subMeshes;
  24240. len = subMeshes.length;
  24241. }
  24242. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  24243. subMesh = subMeshes[subIndex];
  24244. this._evaluateSubMesh(subMesh, mesh);
  24245. }
  24246. }
  24247. };
  24248. Scene.prototype.updateTransformMatrix = function (force) {
  24249. if (!this.activeCamera) {
  24250. return;
  24251. }
  24252. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  24253. };
  24254. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  24255. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  24256. };
  24257. Scene.prototype._renderForCamera = function (camera, rigParent) {
  24258. if (camera && camera._skipRendering) {
  24259. return;
  24260. }
  24261. var engine = this._engine;
  24262. this.activeCamera = camera;
  24263. if (!this.activeCamera)
  24264. throw new Error("Active camera not set");
  24265. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  24266. // Viewport
  24267. engine.setViewport(this.activeCamera.viewport);
  24268. // Camera
  24269. this.resetCachedMaterial();
  24270. this._renderId++;
  24271. this.updateTransformMatrix();
  24272. if (camera._alternateCamera) {
  24273. this.updateAlternateTransformMatrix(camera._alternateCamera);
  24274. this._alternateRendering = true;
  24275. }
  24276. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  24277. // Meshes
  24278. this._evaluateActiveMeshes();
  24279. // Software skinning
  24280. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  24281. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  24282. mesh.applySkeleton(mesh.skeleton);
  24283. }
  24284. // Render targets
  24285. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  24286. var needsRestoreFrameBuffer = false;
  24287. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  24288. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  24289. }
  24290. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  24291. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  24292. }
  24293. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  24294. this._intermediateRendering = true;
  24295. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  24296. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  24297. var renderTarget = this._renderTargets.data[renderIndex];
  24298. if (renderTarget._shouldRender()) {
  24299. this._renderId++;
  24300. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  24301. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  24302. }
  24303. }
  24304. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  24305. this._intermediateRendering = false;
  24306. this._renderId++;
  24307. needsRestoreFrameBuffer = true; // Restore back buffer
  24308. }
  24309. // Render EffecttLayer Texture
  24310. var stencilState = this._engine.getStencilBuffer();
  24311. var renderEffects = false;
  24312. var needStencil = false;
  24313. if (this.renderTargetsEnabled && this.effectLayers && this.effectLayers.length > 0) {
  24314. this._intermediateRendering = true;
  24315. for (var i = 0; i < this.effectLayers.length; i++) {
  24316. var effectLayer = this.effectLayers[i];
  24317. if (effectLayer.shouldRender() &&
  24318. (!effectLayer.camera ||
  24319. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  24320. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  24321. renderEffects = true;
  24322. needStencil = needStencil || effectLayer.needStencil();
  24323. var renderTarget = effectLayer._mainTexture;
  24324. if (renderTarget._shouldRender()) {
  24325. this._renderId++;
  24326. renderTarget.render(false, false);
  24327. needsRestoreFrameBuffer = true;
  24328. }
  24329. }
  24330. }
  24331. this._intermediateRendering = false;
  24332. this._renderId++;
  24333. }
  24334. if (needsRestoreFrameBuffer) {
  24335. engine.restoreDefaultFramebuffer(); // Restore back buffer
  24336. }
  24337. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  24338. // Prepare Frame
  24339. this.postProcessManager._prepareFrame();
  24340. // Backgrounds
  24341. var layerIndex;
  24342. var layer;
  24343. if (this.layers.length) {
  24344. engine.setDepthBuffer(false);
  24345. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  24346. layer = this.layers[layerIndex];
  24347. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  24348. layer.render();
  24349. }
  24350. }
  24351. engine.setDepthBuffer(true);
  24352. }
  24353. // Activate effect Layer stencil
  24354. if (needStencil) {
  24355. this._engine.setStencilBuffer(true);
  24356. }
  24357. // Render
  24358. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  24359. this._renderingManager.render(null, null, true, true);
  24360. this.onAfterDrawPhaseObservable.notifyObservers(this);
  24361. // Restore effect Layer stencil
  24362. if (needStencil) {
  24363. this._engine.setStencilBuffer(stencilState);
  24364. }
  24365. // Bounding boxes
  24366. if (this._boundingBoxRenderer) {
  24367. this._boundingBoxRenderer.render();
  24368. }
  24369. // Lens flares
  24370. if (this.lensFlaresEnabled) {
  24371. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  24372. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  24373. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  24374. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  24375. lensFlareSystem.render();
  24376. }
  24377. }
  24378. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  24379. }
  24380. // Foregrounds
  24381. if (this.layers.length) {
  24382. engine.setDepthBuffer(false);
  24383. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  24384. layer = this.layers[layerIndex];
  24385. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  24386. layer.render();
  24387. }
  24388. }
  24389. engine.setDepthBuffer(true);
  24390. }
  24391. // Effect Layer
  24392. if (renderEffects) {
  24393. engine.setDepthBuffer(false);
  24394. for (var i = 0; i < this.effectLayers.length; i++) {
  24395. if (this.effectLayers[i].shouldRender()) {
  24396. this.effectLayers[i].render();
  24397. }
  24398. }
  24399. engine.setDepthBuffer(true);
  24400. }
  24401. // Finalize frame
  24402. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  24403. // Reset some special arrays
  24404. this._renderTargets.reset();
  24405. this._alternateRendering = false;
  24406. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  24407. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  24408. };
  24409. Scene.prototype._processSubCameras = function (camera) {
  24410. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  24411. this._renderForCamera(camera);
  24412. return;
  24413. }
  24414. // rig cameras
  24415. for (var index = 0; index < camera._rigCameras.length; index++) {
  24416. this._renderForCamera(camera._rigCameras[index], camera);
  24417. }
  24418. this.activeCamera = camera;
  24419. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  24420. };
  24421. Scene.prototype._checkIntersections = function () {
  24422. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  24423. var sourceMesh = this._meshesForIntersections.data[index];
  24424. if (!sourceMesh.actionManager) {
  24425. continue;
  24426. }
  24427. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  24428. var action = sourceMesh.actionManager.actions[actionIndex];
  24429. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  24430. var parameters = action.getTriggerParameter();
  24431. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  24432. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  24433. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  24434. if (areIntersecting && currentIntersectionInProgress === -1) {
  24435. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  24436. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  24437. sourceMesh._intersectionsInProgress.push(otherMesh);
  24438. }
  24439. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  24440. sourceMesh._intersectionsInProgress.push(otherMesh);
  24441. }
  24442. }
  24443. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  24444. //They intersected, and now they don't.
  24445. //is this trigger an exit trigger? execute an event.
  24446. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  24447. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  24448. }
  24449. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  24450. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  24451. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  24452. }
  24453. }
  24454. }
  24455. }
  24456. }
  24457. };
  24458. Scene.prototype.render = function () {
  24459. if (this.isDisposed) {
  24460. return;
  24461. }
  24462. this._activeParticles.fetchNewFrame();
  24463. this._totalVertices.fetchNewFrame();
  24464. this._activeIndices.fetchNewFrame();
  24465. this._activeBones.fetchNewFrame();
  24466. this._meshesForIntersections.reset();
  24467. this.resetCachedMaterial();
  24468. this.onBeforeAnimationsObservable.notifyObservers(this);
  24469. // Actions
  24470. if (this.actionManager) {
  24471. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  24472. }
  24473. //Simplification Queue
  24474. if (this.simplificationQueue && !this.simplificationQueue.running) {
  24475. this.simplificationQueue.executeNext();
  24476. }
  24477. if (this._engine.isDeterministicLockStep()) {
  24478. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  24479. var defaultFPS = (60.0 / 1000.0);
  24480. var defaultFrameTime = 1000 / 60; // frame time in MS
  24481. if (this._physicsEngine) {
  24482. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  24483. }
  24484. var stepsTaken = 0;
  24485. var maxSubSteps = this._engine.getLockstepMaxSteps();
  24486. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  24487. internalSteps = Math.min(internalSteps, maxSubSteps);
  24488. do {
  24489. this.onBeforeStepObservable.notifyObservers(this);
  24490. // Animations
  24491. this._animationRatio = defaultFrameTime * defaultFPS;
  24492. this._animate();
  24493. this.onAfterAnimationsObservable.notifyObservers(this);
  24494. // Physics
  24495. if (this._physicsEngine) {
  24496. this.onBeforePhysicsObservable.notifyObservers(this);
  24497. this._physicsEngine._step(defaultFrameTime / 1000);
  24498. this.onAfterPhysicsObservable.notifyObservers(this);
  24499. }
  24500. this.onAfterStepObservable.notifyObservers(this);
  24501. this._currentStepId++;
  24502. stepsTaken++;
  24503. deltaTime -= defaultFrameTime;
  24504. } while (deltaTime > 0 && stepsTaken < internalSteps);
  24505. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  24506. }
  24507. else {
  24508. // Animations
  24509. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  24510. this._animationRatio = deltaTime * (60.0 / 1000.0);
  24511. this._animate();
  24512. this.onAfterAnimationsObservable.notifyObservers(this);
  24513. // Physics
  24514. if (this._physicsEngine) {
  24515. this.onBeforePhysicsObservable.notifyObservers(this);
  24516. this._physicsEngine._step(deltaTime / 1000.0);
  24517. this.onAfterPhysicsObservable.notifyObservers(this);
  24518. }
  24519. }
  24520. // update gamepad manager
  24521. if (this._gamepadManager && this._gamepadManager._isMonitoring) {
  24522. this._gamepadManager._checkGamepadsStatus();
  24523. }
  24524. // Update Cameras
  24525. if (this.activeCameras.length > 0) {
  24526. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  24527. var camera = this.activeCameras[cameraIndex];
  24528. camera.update();
  24529. if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  24530. // rig cameras
  24531. for (var index = 0; index < camera._rigCameras.length; index++) {
  24532. camera._rigCameras[index].update();
  24533. }
  24534. }
  24535. }
  24536. }
  24537. else if (this.activeCamera) {
  24538. this.activeCamera.update();
  24539. if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  24540. // rig cameras
  24541. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  24542. this.activeCamera._rigCameras[index].update();
  24543. }
  24544. }
  24545. }
  24546. // Before render
  24547. this.onBeforeRenderObservable.notifyObservers(this);
  24548. // Customs render targets
  24549. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  24550. var engine = this.getEngine();
  24551. var currentActiveCamera = this.activeCamera;
  24552. if (this.renderTargetsEnabled) {
  24553. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  24554. this._intermediateRendering = true;
  24555. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  24556. var renderTarget = this.customRenderTargets[customIndex];
  24557. if (renderTarget._shouldRender()) {
  24558. this._renderId++;
  24559. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  24560. if (!this.activeCamera)
  24561. throw new Error("Active camera not set");
  24562. // Viewport
  24563. engine.setViewport(this.activeCamera.viewport);
  24564. // Camera
  24565. this.updateTransformMatrix();
  24566. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  24567. }
  24568. }
  24569. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  24570. this._intermediateRendering = false;
  24571. this._renderId++;
  24572. }
  24573. // Restore back buffer
  24574. if (this.customRenderTargets.length > 0) {
  24575. engine.restoreDefaultFramebuffer();
  24576. }
  24577. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  24578. this.activeCamera = currentActiveCamera;
  24579. // Procedural textures
  24580. if (this.proceduralTexturesEnabled) {
  24581. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  24582. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  24583. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  24584. if (proceduralTexture._shouldRender()) {
  24585. proceduralTexture.render();
  24586. }
  24587. }
  24588. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  24589. }
  24590. // Clear
  24591. if (this.autoClearDepthAndStencil || this.autoClear) {
  24592. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  24593. }
  24594. // Shadows
  24595. if (this.shadowsEnabled) {
  24596. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  24597. var light = this.lights[lightIndex];
  24598. var shadowGenerator = light.getShadowGenerator();
  24599. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  24600. var shadowMap = (shadowGenerator.getShadowMap());
  24601. if (this.textures.indexOf(shadowMap) !== -1) {
  24602. this._renderTargets.push(shadowMap);
  24603. }
  24604. }
  24605. }
  24606. }
  24607. // Depth renderer
  24608. for (var key in this._depthRenderer) {
  24609. this._renderTargets.push(this._depthRenderer[key].getDepthMap());
  24610. }
  24611. // Geometry renderer
  24612. if (this._geometryBufferRenderer) {
  24613. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  24614. }
  24615. // RenderPipeline
  24616. if (this._postProcessRenderPipelineManager) {
  24617. this._postProcessRenderPipelineManager.update();
  24618. }
  24619. // Multi-cameras?
  24620. if (this.activeCameras.length > 0) {
  24621. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  24622. if (cameraIndex > 0) {
  24623. this._engine.clear(null, false, true, true);
  24624. }
  24625. this._processSubCameras(this.activeCameras[cameraIndex]);
  24626. }
  24627. }
  24628. else {
  24629. if (!this.activeCamera) {
  24630. throw new Error("No camera defined");
  24631. }
  24632. this._processSubCameras(this.activeCamera);
  24633. }
  24634. // Intersection checks
  24635. this._checkIntersections();
  24636. // Update the audio listener attached to the camera
  24637. if (BABYLON.AudioEngine) {
  24638. this._updateAudioParameters();
  24639. }
  24640. // After render
  24641. if (this.afterRender) {
  24642. this.afterRender();
  24643. }
  24644. this.onAfterRenderObservable.notifyObservers(this);
  24645. // Cleaning
  24646. for (var index = 0; index < this._toBeDisposed.length; index++) {
  24647. var data = this._toBeDisposed.data[index];
  24648. if (data) {
  24649. data.dispose();
  24650. }
  24651. this._toBeDisposed[index] = null;
  24652. }
  24653. this._toBeDisposed.reset();
  24654. if (this.dumpNextRenderTargets) {
  24655. this.dumpNextRenderTargets = false;
  24656. }
  24657. this._activeBones.addCount(0, true);
  24658. this._activeIndices.addCount(0, true);
  24659. this._activeParticles.addCount(0, true);
  24660. };
  24661. Scene.prototype._updateAudioParameters = function () {
  24662. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  24663. return;
  24664. }
  24665. var listeningCamera;
  24666. var audioEngine = BABYLON.Engine.audioEngine;
  24667. if (this.activeCameras.length > 0) {
  24668. listeningCamera = this.activeCameras[0];
  24669. }
  24670. else {
  24671. listeningCamera = this.activeCamera;
  24672. }
  24673. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  24674. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  24675. // for VR cameras
  24676. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  24677. listeningCamera = listeningCamera.rigCameras[0];
  24678. }
  24679. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  24680. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  24681. cameraDirection.normalize();
  24682. // To avoid some errors on GearVR
  24683. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  24684. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  24685. }
  24686. var i;
  24687. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  24688. var sound = this.mainSoundTrack.soundCollection[i];
  24689. if (sound.useCustomAttenuation) {
  24690. sound.updateDistanceFromListener();
  24691. }
  24692. }
  24693. for (i = 0; i < this.soundTracks.length; i++) {
  24694. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  24695. sound = this.soundTracks[i].soundCollection[j];
  24696. if (sound.useCustomAttenuation) {
  24697. sound.updateDistanceFromListener();
  24698. }
  24699. }
  24700. }
  24701. }
  24702. };
  24703. Object.defineProperty(Scene.prototype, "audioEnabled", {
  24704. // Audio
  24705. get: function () {
  24706. return this._audioEnabled;
  24707. },
  24708. set: function (value) {
  24709. this._audioEnabled = value;
  24710. if (BABYLON.AudioEngine) {
  24711. if (this._audioEnabled) {
  24712. this._enableAudio();
  24713. }
  24714. else {
  24715. this._disableAudio();
  24716. }
  24717. }
  24718. },
  24719. enumerable: true,
  24720. configurable: true
  24721. });
  24722. Scene.prototype._disableAudio = function () {
  24723. var i;
  24724. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  24725. this.mainSoundTrack.soundCollection[i].pause();
  24726. }
  24727. for (i = 0; i < this.soundTracks.length; i++) {
  24728. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  24729. this.soundTracks[i].soundCollection[j].pause();
  24730. }
  24731. }
  24732. };
  24733. Scene.prototype._enableAudio = function () {
  24734. var i;
  24735. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  24736. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  24737. this.mainSoundTrack.soundCollection[i].play();
  24738. }
  24739. }
  24740. for (i = 0; i < this.soundTracks.length; i++) {
  24741. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  24742. if (this.soundTracks[i].soundCollection[j].isPaused) {
  24743. this.soundTracks[i].soundCollection[j].play();
  24744. }
  24745. }
  24746. }
  24747. };
  24748. Object.defineProperty(Scene.prototype, "headphone", {
  24749. get: function () {
  24750. return this._headphone;
  24751. },
  24752. set: function (value) {
  24753. this._headphone = value;
  24754. if (BABYLON.AudioEngine) {
  24755. if (this._headphone) {
  24756. this._switchAudioModeForHeadphones();
  24757. }
  24758. else {
  24759. this._switchAudioModeForNormalSpeakers();
  24760. }
  24761. }
  24762. },
  24763. enumerable: true,
  24764. configurable: true
  24765. });
  24766. Scene.prototype._switchAudioModeForHeadphones = function () {
  24767. this.mainSoundTrack.switchPanningModelToHRTF();
  24768. for (var i = 0; i < this.soundTracks.length; i++) {
  24769. this.soundTracks[i].switchPanningModelToHRTF();
  24770. }
  24771. };
  24772. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  24773. this.mainSoundTrack.switchPanningModelToEqualPower();
  24774. for (var i = 0; i < this.soundTracks.length; i++) {
  24775. this.soundTracks[i].switchPanningModelToEqualPower();
  24776. }
  24777. };
  24778. /**
  24779. * Creates a depth renderer a given camera which contains a depth map which can be used for post processing.
  24780. * @param camera The camera to create the depth renderer on (default: scene's active camera)
  24781. * @returns the created depth renderer
  24782. */
  24783. Scene.prototype.enableDepthRenderer = function (camera) {
  24784. camera = camera || this.activeCamera;
  24785. if (!camera) {
  24786. throw "No camera available to enable depth renderer";
  24787. }
  24788. if (!this._depthRenderer[camera.id]) {
  24789. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, BABYLON.Engine.TEXTURETYPE_FLOAT, camera);
  24790. }
  24791. return this._depthRenderer[camera.id];
  24792. };
  24793. /**
  24794. * Disables a depth renderer for a given camera
  24795. * @param camera The camera to disable the depth renderer on (default: scene's active camera)
  24796. */
  24797. Scene.prototype.disableDepthRenderer = function (camera) {
  24798. camera = camera || this.activeCamera;
  24799. if (!camera || !this._depthRenderer[camera.id]) {
  24800. return;
  24801. }
  24802. this._depthRenderer[camera.id].dispose();
  24803. delete this._depthRenderer[camera.id];
  24804. };
  24805. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  24806. if (ratio === void 0) { ratio = 1; }
  24807. if (this._geometryBufferRenderer) {
  24808. return this._geometryBufferRenderer;
  24809. }
  24810. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  24811. if (!this._geometryBufferRenderer.isSupported) {
  24812. this._geometryBufferRenderer = null;
  24813. }
  24814. return this._geometryBufferRenderer;
  24815. };
  24816. Scene.prototype.disableGeometryBufferRenderer = function () {
  24817. if (!this._geometryBufferRenderer) {
  24818. return;
  24819. }
  24820. this._geometryBufferRenderer.dispose();
  24821. this._geometryBufferRenderer = null;
  24822. };
  24823. Scene.prototype.freezeMaterials = function () {
  24824. for (var i = 0; i < this.materials.length; i++) {
  24825. this.materials[i].freeze();
  24826. }
  24827. };
  24828. Scene.prototype.unfreezeMaterials = function () {
  24829. for (var i = 0; i < this.materials.length; i++) {
  24830. this.materials[i].unfreeze();
  24831. }
  24832. };
  24833. Scene.prototype.dispose = function () {
  24834. this.beforeRender = null;
  24835. this.afterRender = null;
  24836. this.skeletons = [];
  24837. this.morphTargetManagers = [];
  24838. this.importedMeshesFiles = new Array();
  24839. this.stopAllAnimations();
  24840. this.resetCachedMaterial();
  24841. for (var key in this._depthRenderer) {
  24842. this._depthRenderer[key].dispose();
  24843. }
  24844. if (this._gamepadManager) {
  24845. this._gamepadManager.dispose();
  24846. this._gamepadManager = null;
  24847. }
  24848. // Smart arrays
  24849. if (this.activeCamera) {
  24850. this.activeCamera._activeMeshes.dispose();
  24851. this.activeCamera = null;
  24852. }
  24853. this._activeMeshes.dispose();
  24854. this._renderingManager.dispose();
  24855. this._processedMaterials.dispose();
  24856. this._activeParticleSystems.dispose();
  24857. this._activeSkeletons.dispose();
  24858. this._softwareSkinnedMeshes.dispose();
  24859. this._renderTargets.dispose();
  24860. if (this._boundingBoxRenderer) {
  24861. this._boundingBoxRenderer.dispose();
  24862. }
  24863. this._meshesForIntersections.dispose();
  24864. this._toBeDisposed.dispose();
  24865. // Abort active requests
  24866. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  24867. var request = _a[_i];
  24868. request.abort();
  24869. }
  24870. // Debug layer
  24871. if (this._debugLayer) {
  24872. this._debugLayer.hide();
  24873. }
  24874. // Events
  24875. this.onDisposeObservable.notifyObservers(this);
  24876. this.onDisposeObservable.clear();
  24877. this.onBeforeRenderObservable.clear();
  24878. this.onAfterRenderObservable.clear();
  24879. this.OnBeforeRenderTargetsRenderObservable.clear();
  24880. this.OnAfterRenderTargetsRenderObservable.clear();
  24881. this.onAfterStepObservable.clear();
  24882. this.onBeforeStepObservable.clear();
  24883. this.onBeforeActiveMeshesEvaluationObservable.clear();
  24884. this.onAfterActiveMeshesEvaluationObservable.clear();
  24885. this.onBeforeParticlesRenderingObservable.clear();
  24886. this.onAfterParticlesRenderingObservable.clear();
  24887. this.onBeforeSpritesRenderingObservable.clear();
  24888. this.onAfterSpritesRenderingObservable.clear();
  24889. this.onBeforeDrawPhaseObservable.clear();
  24890. this.onAfterDrawPhaseObservable.clear();
  24891. this.onBeforePhysicsObservable.clear();
  24892. this.onAfterPhysicsObservable.clear();
  24893. this.onBeforeAnimationsObservable.clear();
  24894. this.onAfterAnimationsObservable.clear();
  24895. this.onDataLoadedObservable.clear();
  24896. this.detachControl();
  24897. // Release sounds & sounds tracks
  24898. if (BABYLON.AudioEngine) {
  24899. this.disposeSounds();
  24900. }
  24901. // VR Helper
  24902. if (this.VRHelper) {
  24903. this.VRHelper.dispose();
  24904. }
  24905. // Detach cameras
  24906. var canvas = this._engine.getRenderingCanvas();
  24907. if (canvas) {
  24908. var index;
  24909. for (index = 0; index < this.cameras.length; index++) {
  24910. this.cameras[index].detachControl(canvas);
  24911. }
  24912. }
  24913. // Release animation groups
  24914. while (this.animationGroups.length) {
  24915. this.animationGroups[0].dispose();
  24916. }
  24917. // Release lights
  24918. while (this.lights.length) {
  24919. this.lights[0].dispose();
  24920. }
  24921. // Release meshes
  24922. while (this.meshes.length) {
  24923. this.meshes[0].dispose(true);
  24924. }
  24925. while (this.transformNodes.length) {
  24926. this.removeTransformNode(this.transformNodes[0]);
  24927. }
  24928. // Release cameras
  24929. while (this.cameras.length) {
  24930. this.cameras[0].dispose();
  24931. }
  24932. // Release materials
  24933. if (this.defaultMaterial) {
  24934. this.defaultMaterial.dispose();
  24935. }
  24936. while (this.multiMaterials.length) {
  24937. this.multiMaterials[0].dispose();
  24938. }
  24939. while (this.materials.length) {
  24940. this.materials[0].dispose();
  24941. }
  24942. // Release particles
  24943. while (this.particleSystems.length) {
  24944. this.particleSystems[0].dispose();
  24945. }
  24946. // Release sprites
  24947. while (this.spriteManagers.length) {
  24948. this.spriteManagers[0].dispose();
  24949. }
  24950. // Release postProcesses
  24951. while (this.postProcesses.length) {
  24952. this.postProcesses[0].dispose();
  24953. }
  24954. // Release layers
  24955. while (this.layers.length) {
  24956. this.layers[0].dispose();
  24957. }
  24958. while (this.effectLayers.length) {
  24959. this.effectLayers[0].dispose();
  24960. }
  24961. // Release textures
  24962. while (this.textures.length) {
  24963. this.textures[0].dispose();
  24964. }
  24965. // Release UBO
  24966. this._sceneUbo.dispose();
  24967. if (this._alternateSceneUbo) {
  24968. this._alternateSceneUbo.dispose();
  24969. }
  24970. // Post-processes
  24971. this.postProcessManager.dispose();
  24972. if (this._postProcessRenderPipelineManager) {
  24973. this._postProcessRenderPipelineManager.dispose();
  24974. }
  24975. // Physics
  24976. if (this._physicsEngine) {
  24977. this.disablePhysicsEngine();
  24978. }
  24979. // Remove from engine
  24980. index = this._engine.scenes.indexOf(this);
  24981. if (index > -1) {
  24982. this._engine.scenes.splice(index, 1);
  24983. }
  24984. this._engine.wipeCaches(true);
  24985. this._isDisposed = true;
  24986. };
  24987. Object.defineProperty(Scene.prototype, "isDisposed", {
  24988. get: function () {
  24989. return this._isDisposed;
  24990. },
  24991. enumerable: true,
  24992. configurable: true
  24993. });
  24994. // Release sounds & sounds tracks
  24995. Scene.prototype.disposeSounds = function () {
  24996. if (!this._mainSoundTrack) {
  24997. return;
  24998. }
  24999. this.mainSoundTrack.dispose();
  25000. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  25001. this.soundTracks[scIndex].dispose();
  25002. }
  25003. };
  25004. // Octrees
  25005. /**
  25006. * Get the world extend vectors with an optional filter
  25007. *
  25008. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  25009. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  25010. */
  25011. Scene.prototype.getWorldExtends = function (filterPredicate) {
  25012. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  25013. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  25014. filterPredicate = filterPredicate || (function () { return true; });
  25015. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  25016. mesh.computeWorldMatrix(true);
  25017. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  25018. return;
  25019. }
  25020. var boundingInfo = mesh.getBoundingInfo();
  25021. var minBox = boundingInfo.boundingBox.minimumWorld;
  25022. var maxBox = boundingInfo.boundingBox.maximumWorld;
  25023. BABYLON.Tools.CheckExtends(minBox, min, max);
  25024. BABYLON.Tools.CheckExtends(maxBox, min, max);
  25025. });
  25026. return {
  25027. min: min,
  25028. max: max
  25029. };
  25030. };
  25031. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  25032. if (maxCapacity === void 0) { maxCapacity = 64; }
  25033. if (maxDepth === void 0) { maxDepth = 2; }
  25034. if (!this._selectionOctree) {
  25035. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  25036. }
  25037. var worldExtends = this.getWorldExtends();
  25038. // Update octree
  25039. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  25040. return this._selectionOctree;
  25041. };
  25042. // Picking
  25043. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  25044. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  25045. var result = BABYLON.Ray.Zero();
  25046. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  25047. return result;
  25048. };
  25049. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  25050. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  25051. var engine = this._engine;
  25052. if (!camera) {
  25053. if (!this.activeCamera)
  25054. throw new Error("Active camera not set");
  25055. camera = this.activeCamera;
  25056. }
  25057. var cameraViewport = camera.viewport;
  25058. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  25059. // Moving coordinates to local viewport world
  25060. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  25061. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  25062. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  25063. return this;
  25064. };
  25065. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  25066. var result = BABYLON.Ray.Zero();
  25067. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  25068. return result;
  25069. };
  25070. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  25071. if (!BABYLON.PickingInfo) {
  25072. return this;
  25073. }
  25074. var engine = this._engine;
  25075. if (!camera) {
  25076. if (!this.activeCamera)
  25077. throw new Error("Active camera not set");
  25078. camera = this.activeCamera;
  25079. }
  25080. var cameraViewport = camera.viewport;
  25081. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  25082. var identity = BABYLON.Matrix.Identity();
  25083. // Moving coordinates to local viewport world
  25084. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  25085. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  25086. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  25087. return this;
  25088. };
  25089. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  25090. if (!BABYLON.PickingInfo) {
  25091. return null;
  25092. }
  25093. var pickingInfo = null;
  25094. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  25095. var mesh = this.meshes[meshIndex];
  25096. if (predicate) {
  25097. if (!predicate(mesh)) {
  25098. continue;
  25099. }
  25100. }
  25101. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  25102. continue;
  25103. }
  25104. var world = mesh.getWorldMatrix();
  25105. var ray = rayFunction(world);
  25106. var result = mesh.intersects(ray, fastCheck);
  25107. if (!result || !result.hit)
  25108. continue;
  25109. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  25110. continue;
  25111. pickingInfo = result;
  25112. if (fastCheck) {
  25113. break;
  25114. }
  25115. }
  25116. return pickingInfo || new BABYLON.PickingInfo();
  25117. };
  25118. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  25119. if (!BABYLON.PickingInfo) {
  25120. return null;
  25121. }
  25122. var pickingInfos = new Array();
  25123. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  25124. var mesh = this.meshes[meshIndex];
  25125. if (predicate) {
  25126. if (!predicate(mesh)) {
  25127. continue;
  25128. }
  25129. }
  25130. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  25131. continue;
  25132. }
  25133. var world = mesh.getWorldMatrix();
  25134. var ray = rayFunction(world);
  25135. var result = mesh.intersects(ray, false);
  25136. if (!result || !result.hit)
  25137. continue;
  25138. pickingInfos.push(result);
  25139. }
  25140. return pickingInfos;
  25141. };
  25142. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  25143. if (!BABYLON.PickingInfo) {
  25144. return null;
  25145. }
  25146. var pickingInfo = null;
  25147. if (!camera) {
  25148. if (!this.activeCamera) {
  25149. return null;
  25150. }
  25151. camera = this.activeCamera;
  25152. }
  25153. if (this.spriteManagers.length > 0) {
  25154. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  25155. var spriteManager = this.spriteManagers[spriteIndex];
  25156. if (!spriteManager.isPickable) {
  25157. continue;
  25158. }
  25159. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  25160. if (!result || !result.hit)
  25161. continue;
  25162. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  25163. continue;
  25164. pickingInfo = result;
  25165. if (fastCheck) {
  25166. break;
  25167. }
  25168. }
  25169. }
  25170. return pickingInfo || new BABYLON.PickingInfo();
  25171. };
  25172. /** Launch a ray to try to pick a mesh in the scene
  25173. * @param x position on screen
  25174. * @param y position on screen
  25175. * @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
  25176. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  25177. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  25178. */
  25179. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  25180. var _this = this;
  25181. if (!BABYLON.PickingInfo) {
  25182. return null;
  25183. }
  25184. return this._internalPick(function (world) {
  25185. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  25186. return _this._tempPickingRay;
  25187. }, predicate, fastCheck);
  25188. };
  25189. /** Launch a ray to try to pick a sprite in the scene
  25190. * @param x position on screen
  25191. * @param y position on screen
  25192. * @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
  25193. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  25194. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  25195. */
  25196. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  25197. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  25198. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  25199. };
  25200. /** Use the given ray to pick a mesh in the scene
  25201. * @param ray The ray to use to pick meshes
  25202. * @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
  25203. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  25204. */
  25205. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  25206. var _this = this;
  25207. return this._internalPick(function (world) {
  25208. if (!_this._pickWithRayInverseMatrix) {
  25209. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  25210. }
  25211. world.invertToRef(_this._pickWithRayInverseMatrix);
  25212. if (!_this._cachedRayForTransform) {
  25213. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  25214. }
  25215. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  25216. return _this._cachedRayForTransform;
  25217. }, predicate, fastCheck);
  25218. };
  25219. /**
  25220. * Launch a ray to try to pick a mesh in the scene
  25221. * @param x X position on screen
  25222. * @param y Y position on screen
  25223. * @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
  25224. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  25225. */
  25226. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  25227. var _this = this;
  25228. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  25229. };
  25230. /**
  25231. * Launch a ray to try to pick a mesh in the scene
  25232. * @param ray Ray to use
  25233. * @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
  25234. */
  25235. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  25236. var _this = this;
  25237. return this._internalMultiPick(function (world) {
  25238. if (!_this._pickWithRayInverseMatrix) {
  25239. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  25240. }
  25241. world.invertToRef(_this._pickWithRayInverseMatrix);
  25242. if (!_this._cachedRayForTransform) {
  25243. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  25244. }
  25245. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  25246. return _this._cachedRayForTransform;
  25247. }, predicate);
  25248. };
  25249. Scene.prototype.setPointerOverMesh = function (mesh) {
  25250. if (this._pointerOverMesh === mesh) {
  25251. return;
  25252. }
  25253. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  25254. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  25255. }
  25256. this._pointerOverMesh = mesh;
  25257. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  25258. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  25259. }
  25260. };
  25261. Scene.prototype.getPointerOverMesh = function () {
  25262. return this._pointerOverMesh;
  25263. };
  25264. Scene.prototype.setPointerOverSprite = function (sprite) {
  25265. if (this._pointerOverSprite === sprite) {
  25266. return;
  25267. }
  25268. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  25269. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  25270. }
  25271. this._pointerOverSprite = sprite;
  25272. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  25273. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  25274. }
  25275. };
  25276. Scene.prototype.getPointerOverSprite = function () {
  25277. return this._pointerOverSprite;
  25278. };
  25279. // Physics
  25280. Scene.prototype.getPhysicsEngine = function () {
  25281. return this._physicsEngine;
  25282. };
  25283. /**
  25284. * Enables physics to the current scene
  25285. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  25286. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  25287. * @return {boolean} was the physics engine initialized
  25288. */
  25289. Scene.prototype.enablePhysics = function (gravity, plugin) {
  25290. if (gravity === void 0) { gravity = null; }
  25291. if (this._physicsEngine) {
  25292. return true;
  25293. }
  25294. try {
  25295. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  25296. return true;
  25297. }
  25298. catch (e) {
  25299. BABYLON.Tools.Error(e.message);
  25300. return false;
  25301. }
  25302. };
  25303. Scene.prototype.disablePhysicsEngine = function () {
  25304. if (!this._physicsEngine) {
  25305. return;
  25306. }
  25307. this._physicsEngine.dispose();
  25308. this._physicsEngine = null;
  25309. };
  25310. Scene.prototype.isPhysicsEnabled = function () {
  25311. return this._physicsEngine !== undefined;
  25312. };
  25313. Scene.prototype.deleteCompoundImpostor = function (compound) {
  25314. var mesh = compound.parts[0].mesh;
  25315. if (mesh.physicsImpostor) {
  25316. mesh.physicsImpostor.dispose();
  25317. mesh.physicsImpostor = null;
  25318. }
  25319. };
  25320. // Misc.
  25321. Scene.prototype._rebuildGeometries = function () {
  25322. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  25323. var geometry = _a[_i];
  25324. geometry._rebuild();
  25325. }
  25326. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  25327. var mesh = _c[_b];
  25328. mesh._rebuild();
  25329. }
  25330. if (this.postProcessManager) {
  25331. this.postProcessManager._rebuild();
  25332. }
  25333. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  25334. var layer = _e[_d];
  25335. layer._rebuild();
  25336. }
  25337. for (var _f = 0, _g = this.effectLayers; _f < _g.length; _f++) {
  25338. var effectLayer = _g[_f];
  25339. effectLayer._rebuild();
  25340. }
  25341. if (this._boundingBoxRenderer) {
  25342. this._boundingBoxRenderer._rebuild();
  25343. }
  25344. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  25345. var system = _j[_h];
  25346. system.rebuild();
  25347. }
  25348. if (this._postProcessRenderPipelineManager) {
  25349. this._postProcessRenderPipelineManager._rebuild();
  25350. }
  25351. };
  25352. Scene.prototype._rebuildTextures = function () {
  25353. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  25354. var texture = _a[_i];
  25355. texture._rebuild();
  25356. }
  25357. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  25358. };
  25359. /**
  25360. * Creates a default light for the scene.
  25361. * @param replace Whether to replace the existing lights in the scene.
  25362. */
  25363. Scene.prototype.createDefaultLight = function (replace) {
  25364. if (replace === void 0) { replace = false; }
  25365. // Dispose existing light in replace mode.
  25366. if (replace) {
  25367. if (this.lights) {
  25368. for (var i = 0; i < this.lights.length; i++) {
  25369. this.lights[i].dispose();
  25370. }
  25371. }
  25372. }
  25373. // Light
  25374. if (this.lights.length === 0) {
  25375. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  25376. }
  25377. };
  25378. /**
  25379. * Creates a default camera for the scene.
  25380. * @param createArcRotateCamera Whether to create an arc rotate or a free camera.
  25381. * @param replace Whether to replace the existing active camera in the scene.
  25382. * @param attachCameraControls Whether to attach camera controls to the canvas.
  25383. */
  25384. Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  25385. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  25386. if (replace === void 0) { replace = false; }
  25387. if (attachCameraControls === void 0) { attachCameraControls = false; }
  25388. // Dispose existing camera in replace mode.
  25389. if (replace) {
  25390. if (this.activeCamera) {
  25391. this.activeCamera.dispose();
  25392. this.activeCamera = null;
  25393. }
  25394. }
  25395. // Camera
  25396. if (!this.activeCamera) {
  25397. var worldExtends = this.getWorldExtends();
  25398. var worldSize = worldExtends.max.subtract(worldExtends.min);
  25399. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  25400. var camera;
  25401. var radius = worldSize.length() * 1.5;
  25402. // empty scene scenario!
  25403. if (!isFinite(radius)) {
  25404. radius = 1;
  25405. worldCenter.copyFromFloats(0, 0, 0);
  25406. }
  25407. if (createArcRotateCamera) {
  25408. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  25409. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  25410. arcRotateCamera.wheelPrecision = 100 / radius;
  25411. camera = arcRotateCamera;
  25412. }
  25413. else {
  25414. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  25415. freeCamera.setTarget(worldCenter);
  25416. camera = freeCamera;
  25417. }
  25418. camera.minZ = radius * 0.01;
  25419. camera.maxZ = radius * 1000;
  25420. camera.speed = radius * 0.2;
  25421. this.activeCamera = camera;
  25422. var canvas = this.getEngine().getRenderingCanvas();
  25423. if (attachCameraControls && canvas) {
  25424. camera.attachControl(canvas);
  25425. }
  25426. }
  25427. };
  25428. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  25429. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  25430. if (replace === void 0) { replace = false; }
  25431. if (attachCameraControls === void 0) { attachCameraControls = false; }
  25432. this.createDefaultLight(replace);
  25433. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  25434. };
  25435. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur) {
  25436. if (pbr === void 0) { pbr = false; }
  25437. if (scale === void 0) { scale = 1000; }
  25438. if (blur === void 0) { blur = 0; }
  25439. if (environmentTexture) {
  25440. this.environmentTexture = environmentTexture;
  25441. }
  25442. if (!this.environmentTexture) {
  25443. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  25444. return null;
  25445. }
  25446. // Skybox
  25447. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  25448. if (pbr) {
  25449. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  25450. hdrSkyboxMaterial.backFaceCulling = false;
  25451. hdrSkyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  25452. if (hdrSkyboxMaterial.reflectionTexture) {
  25453. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  25454. }
  25455. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  25456. hdrSkyboxMaterial.disableLighting = true;
  25457. hdrSkyboxMaterial.twoSidedLighting = true;
  25458. hdrSkybox.infiniteDistance = true;
  25459. hdrSkybox.material = hdrSkyboxMaterial;
  25460. }
  25461. else {
  25462. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  25463. skyboxMaterial.backFaceCulling = false;
  25464. skyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  25465. if (skyboxMaterial.reflectionTexture) {
  25466. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  25467. }
  25468. skyboxMaterial.disableLighting = true;
  25469. hdrSkybox.infiniteDistance = true;
  25470. hdrSkybox.material = skyboxMaterial;
  25471. }
  25472. return hdrSkybox;
  25473. };
  25474. Scene.prototype.createDefaultEnvironment = function (options) {
  25475. if (BABYLON.EnvironmentHelper) {
  25476. return new BABYLON.EnvironmentHelper(options, this);
  25477. }
  25478. return null;
  25479. };
  25480. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  25481. if (webVROptions === void 0) { webVROptions = {}; }
  25482. return new BABYLON.VRExperienceHelper(this, webVROptions);
  25483. };
  25484. // Tags
  25485. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  25486. if (tagsQuery === undefined) {
  25487. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  25488. return list;
  25489. }
  25490. var listByTags = [];
  25491. forEach = forEach || (function (item) { return; });
  25492. for (var i in list) {
  25493. var item = list[i];
  25494. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  25495. listByTags.push(item);
  25496. forEach(item);
  25497. }
  25498. }
  25499. return listByTags;
  25500. };
  25501. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  25502. return this._getByTags(this.meshes, tagsQuery, forEach);
  25503. };
  25504. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  25505. return this._getByTags(this.cameras, tagsQuery, forEach);
  25506. };
  25507. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  25508. return this._getByTags(this.lights, tagsQuery, forEach);
  25509. };
  25510. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  25511. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  25512. };
  25513. /**
  25514. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  25515. * This allowed control for front to back rendering or reversly depending of the special needs.
  25516. *
  25517. * @param renderingGroupId The rendering group id corresponding to its index
  25518. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  25519. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  25520. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  25521. */
  25522. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  25523. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  25524. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  25525. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  25526. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  25527. };
  25528. /**
  25529. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  25530. *
  25531. * @param renderingGroupId The rendering group id corresponding to its index
  25532. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  25533. * @param depth Automatically clears depth between groups if true and autoClear is true.
  25534. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  25535. */
  25536. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  25537. if (depth === void 0) { depth = true; }
  25538. if (stencil === void 0) { stencil = true; }
  25539. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  25540. };
  25541. /**
  25542. * Will flag all materials as dirty to trigger new shader compilation
  25543. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  25544. */
  25545. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  25546. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  25547. var material = _a[_i];
  25548. if (predicate && !predicate(material)) {
  25549. continue;
  25550. }
  25551. material.markAsDirty(flag);
  25552. }
  25553. };
  25554. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  25555. var _this = this;
  25556. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  25557. this._activeRequests.push(request);
  25558. request.onCompleteObservable.add(function (request) {
  25559. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  25560. });
  25561. return request;
  25562. };
  25563. /** @ignore */
  25564. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  25565. var _this = this;
  25566. return new Promise(function (resolve, reject) {
  25567. _this._loadFile(url, function (data) {
  25568. resolve(data);
  25569. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  25570. reject(exception);
  25571. });
  25572. });
  25573. };
  25574. // Statics
  25575. Scene._FOGMODE_NONE = 0;
  25576. Scene._FOGMODE_EXP = 1;
  25577. Scene._FOGMODE_EXP2 = 2;
  25578. Scene._FOGMODE_LINEAR = 3;
  25579. Scene._uniqueIdCounter = 0;
  25580. Scene.MinDeltaTime = 1.0;
  25581. Scene.MaxDeltaTime = 1000.0;
  25582. /** The distance in pixel that you have to move to prevent some events */
  25583. Scene.DragMovementThreshold = 10; // in pixels
  25584. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  25585. Scene.LongPressDelay = 500; // in milliseconds
  25586. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  25587. Scene.DoubleClickDelay = 300; // in milliseconds
  25588. /** If you need to check double click without raising a single click at first click, enable this flag */
  25589. Scene.ExclusiveDoubleClickMode = false;
  25590. return Scene;
  25591. }());
  25592. BABYLON.Scene = Scene;
  25593. })(BABYLON || (BABYLON = {}));
  25594. //# sourceMappingURL=babylon.scene.js.map
  25595. var BABYLON;
  25596. (function (BABYLON) {
  25597. /**
  25598. * Set of assets to keep when moving a scene into an asset container.
  25599. */
  25600. var KeepAssets = /** @class */ (function () {
  25601. function KeepAssets() {
  25602. /**
  25603. * Cameras to keep.
  25604. */
  25605. this.cameras = new Array();
  25606. /**
  25607. * Lights to keep.
  25608. */
  25609. this.lights = new Array();
  25610. /**
  25611. * Meshes to keep.
  25612. */
  25613. this.meshes = new Array();
  25614. /**
  25615. * Skeletons to keep.
  25616. */
  25617. this.skeletons = new Array();
  25618. /**
  25619. * ParticleSystems to keep.
  25620. */
  25621. this.particleSystems = new Array();
  25622. /**
  25623. * Animations to keep.
  25624. */
  25625. this.animations = new Array();
  25626. /**
  25627. * MultiMaterials to keep.
  25628. */
  25629. this.multiMaterials = new Array();
  25630. /**
  25631. * Materials to keep.
  25632. */
  25633. this.materials = new Array();
  25634. /**
  25635. * MorphTargetManagers to keep.
  25636. */
  25637. this.morphTargetManagers = new Array();
  25638. /**
  25639. * Geometries to keep.
  25640. */
  25641. this.geometries = new Array();
  25642. /**
  25643. * TransformNodes to keep.
  25644. */
  25645. this.transformNodes = new Array();
  25646. /**
  25647. * LensFlareSystems to keep.
  25648. */
  25649. this.lensFlareSystems = new Array();
  25650. /**
  25651. * ShadowGenerators to keep.
  25652. */
  25653. this.shadowGenerators = new Array();
  25654. /**
  25655. * ActionManagers to keep.
  25656. */
  25657. this.actionManagers = new Array();
  25658. /**
  25659. * Sounds to keep.
  25660. */
  25661. this.sounds = new Array();
  25662. }
  25663. return KeepAssets;
  25664. }());
  25665. BABYLON.KeepAssets = KeepAssets;
  25666. /**
  25667. * Container with a set of assets that can be added or removed from a scene.
  25668. */
  25669. var AssetContainer = /** @class */ (function () {
  25670. /**
  25671. * Instantiates an AssetContainer.
  25672. * @param scene The scene the AssetContainer belongs to.
  25673. */
  25674. function AssetContainer(scene) {
  25675. // Objects
  25676. /**
  25677. * Cameras populated in the container.
  25678. */
  25679. this.cameras = new Array();
  25680. /**
  25681. * Lights populated in the container.
  25682. */
  25683. this.lights = new Array();
  25684. /**
  25685. * Meshes populated in the container.
  25686. */
  25687. this.meshes = new Array();
  25688. /**
  25689. * Skeletons populated in the container.
  25690. */
  25691. this.skeletons = new Array();
  25692. /**
  25693. * ParticleSystems populated in the container.
  25694. */
  25695. this.particleSystems = new Array();
  25696. /**
  25697. * Animations populated in the container.
  25698. */
  25699. this.animations = new Array();
  25700. /**
  25701. * MultiMaterials populated in the container.
  25702. */
  25703. this.multiMaterials = new Array();
  25704. /**
  25705. * Materials populated in the container.
  25706. */
  25707. this.materials = new Array();
  25708. /**
  25709. * MorphTargetManagers populated in the container.
  25710. */
  25711. this.morphTargetManagers = new Array();
  25712. /**
  25713. * Geometries populated in the container.
  25714. */
  25715. this.geometries = new Array();
  25716. /**
  25717. * TransformNodes populated in the container.
  25718. */
  25719. this.transformNodes = new Array();
  25720. /**
  25721. * LensFlareSystems populated in the container.
  25722. */
  25723. this.lensFlareSystems = new Array();
  25724. /**
  25725. * ShadowGenerators populated in the container.
  25726. */
  25727. this.shadowGenerators = new Array();
  25728. /**
  25729. * ActionManagers populated in the container.
  25730. */
  25731. this.actionManagers = new Array();
  25732. /**
  25733. * Sounds populated in the container.
  25734. */
  25735. this.sounds = new Array();
  25736. this.scene = scene;
  25737. }
  25738. /**
  25739. * Adds all the assets from the container to the scene.
  25740. */
  25741. AssetContainer.prototype.addAllToScene = function () {
  25742. var _this = this;
  25743. this.cameras.forEach(function (o) {
  25744. _this.scene.addCamera(o);
  25745. });
  25746. this.lights.forEach(function (o) {
  25747. _this.scene.addLight(o);
  25748. });
  25749. this.meshes.forEach(function (o) {
  25750. _this.scene.addMesh(o);
  25751. });
  25752. this.skeletons.forEach(function (o) {
  25753. _this.scene.addSkeleton(o);
  25754. });
  25755. this.particleSystems.forEach(function (o) {
  25756. _this.scene.addParticleSystem(o);
  25757. });
  25758. this.animations.forEach(function (o) {
  25759. _this.scene.addAnimation(o);
  25760. });
  25761. this.multiMaterials.forEach(function (o) {
  25762. _this.scene.addMultiMaterial(o);
  25763. });
  25764. this.materials.forEach(function (o) {
  25765. _this.scene.addMaterial(o);
  25766. });
  25767. this.morphTargetManagers.forEach(function (o) {
  25768. _this.scene.addMorphTargetManager(o);
  25769. });
  25770. this.geometries.forEach(function (o) {
  25771. _this.scene.addGeometry(o);
  25772. });
  25773. this.transformNodes.forEach(function (o) {
  25774. _this.scene.addTransformNode(o);
  25775. });
  25776. this.lensFlareSystems.forEach(function (o) {
  25777. _this.scene.addLensFlareSystem(o);
  25778. });
  25779. this.actionManagers.forEach(function (o) {
  25780. _this.scene.addActionManager(o);
  25781. });
  25782. this.sounds.forEach(function (o) {
  25783. o.play();
  25784. o.autoplay = true;
  25785. _this.scene.mainSoundTrack.AddSound(o);
  25786. });
  25787. };
  25788. /**
  25789. * Removes all the assets in the container from the scene
  25790. */
  25791. AssetContainer.prototype.removeAllFromScene = function () {
  25792. var _this = this;
  25793. this.cameras.forEach(function (o) {
  25794. _this.scene.removeCamera(o);
  25795. });
  25796. this.lights.forEach(function (o) {
  25797. _this.scene.removeLight(o);
  25798. });
  25799. this.meshes.forEach(function (o) {
  25800. _this.scene.removeMesh(o);
  25801. });
  25802. this.skeletons.forEach(function (o) {
  25803. _this.scene.removeSkeleton(o);
  25804. });
  25805. this.particleSystems.forEach(function (o) {
  25806. _this.scene.removeParticleSystem(o);
  25807. });
  25808. this.animations.forEach(function (o) {
  25809. _this.scene.removeAnimation(o);
  25810. });
  25811. this.multiMaterials.forEach(function (o) {
  25812. _this.scene.removeMultiMaterial(o);
  25813. });
  25814. this.materials.forEach(function (o) {
  25815. _this.scene.removeMaterial(o);
  25816. });
  25817. this.morphTargetManagers.forEach(function (o) {
  25818. _this.scene.removeMorphTargetManager(o);
  25819. });
  25820. this.geometries.forEach(function (o) {
  25821. _this.scene.removeGeometry(o);
  25822. });
  25823. this.transformNodes.forEach(function (o) {
  25824. _this.scene.removeTransformNode(o);
  25825. });
  25826. this.lensFlareSystems.forEach(function (o) {
  25827. _this.scene.removeLensFlareSystem(o);
  25828. });
  25829. this.actionManagers.forEach(function (o) {
  25830. _this.scene.removeActionManager(o);
  25831. });
  25832. this.sounds.forEach(function (o) {
  25833. o.stop();
  25834. o.autoplay = false;
  25835. _this.scene.mainSoundTrack.RemoveSound(o);
  25836. });
  25837. };
  25838. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  25839. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  25840. var asset = sourceAssets_1[_i];
  25841. var move = true;
  25842. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  25843. var keepAsset = keepAssets_1[_a];
  25844. if (asset === keepAsset) {
  25845. move = false;
  25846. break;
  25847. }
  25848. }
  25849. if (move) {
  25850. targetAssets.push(asset);
  25851. }
  25852. }
  25853. };
  25854. /**
  25855. * Removes all the assets contained in the scene and adds them to the container.
  25856. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  25857. */
  25858. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  25859. if (keepAssets === undefined) {
  25860. keepAssets = new KeepAssets();
  25861. }
  25862. this._moveAssets(this.scene.cameras, this.cameras, keepAssets.cameras);
  25863. this._moveAssets(this.scene.meshes, this.meshes, keepAssets.meshes);
  25864. this._moveAssets(this.scene.getGeometries(), this.geometries, keepAssets.geometries);
  25865. this._moveAssets(this.scene.materials, this.materials, keepAssets.materials);
  25866. this._moveAssets(this.scene._actionManagers, this.actionManagers, keepAssets.actionManagers);
  25867. this._moveAssets(this.scene.animations, this.animations, keepAssets.animations);
  25868. this._moveAssets(this.scene.lensFlareSystems, this.lensFlareSystems, keepAssets.lensFlareSystems);
  25869. this._moveAssets(this.scene.lights, this.lights, keepAssets.lights);
  25870. this._moveAssets(this.scene.morphTargetManagers, this.morphTargetManagers, keepAssets.morphTargetManagers);
  25871. this._moveAssets(this.scene.multiMaterials, this.multiMaterials, keepAssets.multiMaterials);
  25872. this._moveAssets(this.scene.skeletons, this.skeletons, keepAssets.skeletons);
  25873. this._moveAssets(this.scene.particleSystems, this.particleSystems, keepAssets.particleSystems);
  25874. this._moveAssets(this.scene.mainSoundTrack.soundCollection, this.sounds, keepAssets.sounds);
  25875. this._moveAssets(this.scene.transformNodes, this.transformNodes, keepAssets.transformNodes);
  25876. this.removeAllFromScene();
  25877. };
  25878. return AssetContainer;
  25879. }());
  25880. BABYLON.AssetContainer = AssetContainer;
  25881. })(BABYLON || (BABYLON = {}));
  25882. //# sourceMappingURL=babylon.assetContainer.js.map
  25883. var BABYLON;
  25884. (function (BABYLON) {
  25885. var Buffer = /** @class */ (function () {
  25886. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  25887. if (instanced === void 0) { instanced = false; }
  25888. if (engine instanceof BABYLON.Mesh) {
  25889. this._engine = engine.getScene().getEngine();
  25890. }
  25891. else {
  25892. this._engine = engine;
  25893. }
  25894. this._updatable = updatable;
  25895. this._instanced = instanced;
  25896. this._data = data;
  25897. this._strideSize = stride;
  25898. if (!postponeInternalCreation) {
  25899. this.create();
  25900. }
  25901. }
  25902. /**
  25903. * Create a new {BABYLON.VertexBuffer} based on the current buffer
  25904. * @param kind defines the vertex buffer kind (position, normal, etc.)
  25905. * @param offset defines offset in the buffer (0 by default)
  25906. * @param size defines the size in floats of attributes (position is 3 for instance)
  25907. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  25908. * @param instanced defines if the vertex buffer contains indexed data
  25909. * @returns the new vertex buffer
  25910. */
  25911. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced) {
  25912. // a lot of these parameters are ignored as they are overriden by the buffer
  25913. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, instanced === undefined ? this._instanced : instanced, offset, size);
  25914. };
  25915. // Properties
  25916. Buffer.prototype.isUpdatable = function () {
  25917. return this._updatable;
  25918. };
  25919. Buffer.prototype.getData = function () {
  25920. return this._data;
  25921. };
  25922. Buffer.prototype.getBuffer = function () {
  25923. return this._buffer;
  25924. };
  25925. Buffer.prototype.getStrideSize = function () {
  25926. return this._strideSize;
  25927. };
  25928. // public getIsInstanced(): boolean {
  25929. // return this._instanced;
  25930. // }
  25931. // public get instanceDivisor(): number {
  25932. // return this._instanceDivisor;
  25933. // }
  25934. // public set instanceDivisor(value: number) {
  25935. // this._instanceDivisor = value;
  25936. // if (value == 0) {
  25937. // this._instanced = false;
  25938. // } else {
  25939. // this._instanced = true;
  25940. // }
  25941. // }
  25942. // Methods
  25943. Buffer.prototype.create = function (data) {
  25944. if (data === void 0) { data = null; }
  25945. if (!data && this._buffer) {
  25946. return; // nothing to do
  25947. }
  25948. data = data || this._data;
  25949. if (!data) {
  25950. return;
  25951. }
  25952. if (!this._buffer) {
  25953. if (this._updatable) {
  25954. this._buffer = this._engine.createDynamicVertexBuffer(data);
  25955. this._data = data;
  25956. }
  25957. else {
  25958. this._buffer = this._engine.createVertexBuffer(data);
  25959. }
  25960. }
  25961. else if (this._updatable) {
  25962. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  25963. this._data = data;
  25964. }
  25965. };
  25966. Buffer.prototype._rebuild = function () {
  25967. this._buffer = null;
  25968. this.create(this._data);
  25969. };
  25970. Buffer.prototype.update = function (data) {
  25971. this.create(data);
  25972. };
  25973. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  25974. if (!this._buffer) {
  25975. return;
  25976. }
  25977. if (this._updatable) {
  25978. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  25979. this._data = null;
  25980. }
  25981. };
  25982. Buffer.prototype.dispose = function () {
  25983. if (!this._buffer) {
  25984. return;
  25985. }
  25986. if (this._engine._releaseBuffer(this._buffer)) {
  25987. this._buffer = null;
  25988. }
  25989. };
  25990. return Buffer;
  25991. }());
  25992. BABYLON.Buffer = Buffer;
  25993. })(BABYLON || (BABYLON = {}));
  25994. //# sourceMappingURL=babylon.buffer.js.map
  25995. var BABYLON;
  25996. (function (BABYLON) {
  25997. var VertexBuffer = /** @class */ (function () {
  25998. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  25999. if (data instanceof BABYLON.Buffer) {
  26000. if (!stride) {
  26001. stride = data.getStrideSize();
  26002. }
  26003. this._buffer = data;
  26004. this._ownsBuffer = false;
  26005. }
  26006. else {
  26007. if (!stride) {
  26008. stride = VertexBuffer.DeduceStride(kind);
  26009. }
  26010. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  26011. this._ownsBuffer = true;
  26012. }
  26013. this._stride = stride;
  26014. this._instanced = instanced !== undefined ? instanced : false;
  26015. this._instanceDivisor = instanced ? 1 : 0;
  26016. this._offset = offset ? offset : 0;
  26017. this._size = size ? size : stride;
  26018. this._kind = kind;
  26019. }
  26020. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  26021. /**
  26022. * Gets or sets the instance divisor when in instanced mode
  26023. */
  26024. get: function () {
  26025. return this._instanceDivisor;
  26026. },
  26027. set: function (value) {
  26028. this._instanceDivisor = value;
  26029. if (value == 0) {
  26030. this._instanced = false;
  26031. }
  26032. else {
  26033. this._instanced = true;
  26034. }
  26035. },
  26036. enumerable: true,
  26037. configurable: true
  26038. });
  26039. VertexBuffer.prototype._rebuild = function () {
  26040. if (!this._buffer) {
  26041. return;
  26042. }
  26043. this._buffer._rebuild();
  26044. };
  26045. /**
  26046. * Returns the kind of the VertexBuffer (string).
  26047. */
  26048. VertexBuffer.prototype.getKind = function () {
  26049. return this._kind;
  26050. };
  26051. // Properties
  26052. /**
  26053. * Boolean : is the VertexBuffer updatable ?
  26054. */
  26055. VertexBuffer.prototype.isUpdatable = function () {
  26056. return this._buffer.isUpdatable();
  26057. };
  26058. /**
  26059. * Returns an array of numbers or a Float32Array containing the VertexBuffer data.
  26060. */
  26061. VertexBuffer.prototype.getData = function () {
  26062. return this._buffer.getData();
  26063. };
  26064. /**
  26065. * Returns the WebGLBuffer associated to the VertexBuffer.
  26066. */
  26067. VertexBuffer.prototype.getBuffer = function () {
  26068. return this._buffer.getBuffer();
  26069. };
  26070. /**
  26071. * Returns the stride of the VertexBuffer (integer).
  26072. */
  26073. VertexBuffer.prototype.getStrideSize = function () {
  26074. return this._stride;
  26075. };
  26076. /**
  26077. * Returns the offset (integer).
  26078. */
  26079. VertexBuffer.prototype.getOffset = function () {
  26080. return this._offset;
  26081. };
  26082. /**
  26083. * Returns the VertexBuffer total size (integer).
  26084. */
  26085. VertexBuffer.prototype.getSize = function () {
  26086. return this._size;
  26087. };
  26088. /**
  26089. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  26090. */
  26091. VertexBuffer.prototype.getIsInstanced = function () {
  26092. return this._instanced;
  26093. };
  26094. /**
  26095. * Returns the instancing divisor, zero for non-instanced (integer).
  26096. */
  26097. VertexBuffer.prototype.getInstanceDivisor = function () {
  26098. return this._instanceDivisor;
  26099. };
  26100. // Methods
  26101. /**
  26102. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  26103. * Returns the created WebGLBuffer.
  26104. */
  26105. VertexBuffer.prototype.create = function (data) {
  26106. return this._buffer.create(data);
  26107. };
  26108. /**
  26109. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  26110. * This function will create a new buffer if the current one is not updatable
  26111. * Returns the updated WebGLBuffer.
  26112. */
  26113. VertexBuffer.prototype.update = function (data) {
  26114. return this._buffer.update(data);
  26115. };
  26116. /**
  26117. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  26118. * Returns the directly updated WebGLBuffer.
  26119. */
  26120. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  26121. return this._buffer.updateDirectly(data, offset);
  26122. };
  26123. /**
  26124. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  26125. */
  26126. VertexBuffer.prototype.dispose = function () {
  26127. if (this._ownsBuffer) {
  26128. this._buffer.dispose();
  26129. }
  26130. };
  26131. Object.defineProperty(VertexBuffer, "PositionKind", {
  26132. get: function () {
  26133. return VertexBuffer._PositionKind;
  26134. },
  26135. enumerable: true,
  26136. configurable: true
  26137. });
  26138. Object.defineProperty(VertexBuffer, "NormalKind", {
  26139. get: function () {
  26140. return VertexBuffer._NormalKind;
  26141. },
  26142. enumerable: true,
  26143. configurable: true
  26144. });
  26145. Object.defineProperty(VertexBuffer, "TangentKind", {
  26146. get: function () {
  26147. return VertexBuffer._TangentKind;
  26148. },
  26149. enumerable: true,
  26150. configurable: true
  26151. });
  26152. Object.defineProperty(VertexBuffer, "UVKind", {
  26153. get: function () {
  26154. return VertexBuffer._UVKind;
  26155. },
  26156. enumerable: true,
  26157. configurable: true
  26158. });
  26159. Object.defineProperty(VertexBuffer, "UV2Kind", {
  26160. get: function () {
  26161. return VertexBuffer._UV2Kind;
  26162. },
  26163. enumerable: true,
  26164. configurable: true
  26165. });
  26166. Object.defineProperty(VertexBuffer, "UV3Kind", {
  26167. get: function () {
  26168. return VertexBuffer._UV3Kind;
  26169. },
  26170. enumerable: true,
  26171. configurable: true
  26172. });
  26173. Object.defineProperty(VertexBuffer, "UV4Kind", {
  26174. get: function () {
  26175. return VertexBuffer._UV4Kind;
  26176. },
  26177. enumerable: true,
  26178. configurable: true
  26179. });
  26180. Object.defineProperty(VertexBuffer, "UV5Kind", {
  26181. get: function () {
  26182. return VertexBuffer._UV5Kind;
  26183. },
  26184. enumerable: true,
  26185. configurable: true
  26186. });
  26187. Object.defineProperty(VertexBuffer, "UV6Kind", {
  26188. get: function () {
  26189. return VertexBuffer._UV6Kind;
  26190. },
  26191. enumerable: true,
  26192. configurable: true
  26193. });
  26194. Object.defineProperty(VertexBuffer, "ColorKind", {
  26195. get: function () {
  26196. return VertexBuffer._ColorKind;
  26197. },
  26198. enumerable: true,
  26199. configurable: true
  26200. });
  26201. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  26202. get: function () {
  26203. return VertexBuffer._MatricesIndicesKind;
  26204. },
  26205. enumerable: true,
  26206. configurable: true
  26207. });
  26208. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  26209. get: function () {
  26210. return VertexBuffer._MatricesWeightsKind;
  26211. },
  26212. enumerable: true,
  26213. configurable: true
  26214. });
  26215. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  26216. get: function () {
  26217. return VertexBuffer._MatricesIndicesExtraKind;
  26218. },
  26219. enumerable: true,
  26220. configurable: true
  26221. });
  26222. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  26223. get: function () {
  26224. return VertexBuffer._MatricesWeightsExtraKind;
  26225. },
  26226. enumerable: true,
  26227. configurable: true
  26228. });
  26229. /**
  26230. * Deduces the stride given a kind.
  26231. * @param kind The kind string to deduce
  26232. * @returns The deduced stride
  26233. */
  26234. VertexBuffer.DeduceStride = function (kind) {
  26235. switch (kind) {
  26236. case VertexBuffer.UVKind:
  26237. case VertexBuffer.UV2Kind:
  26238. case VertexBuffer.UV3Kind:
  26239. case VertexBuffer.UV4Kind:
  26240. case VertexBuffer.UV5Kind:
  26241. case VertexBuffer.UV6Kind:
  26242. return 2;
  26243. case VertexBuffer.NormalKind:
  26244. case VertexBuffer.PositionKind:
  26245. return 3;
  26246. case VertexBuffer.ColorKind:
  26247. case VertexBuffer.MatricesIndicesKind:
  26248. case VertexBuffer.MatricesIndicesExtraKind:
  26249. case VertexBuffer.MatricesWeightsKind:
  26250. case VertexBuffer.MatricesWeightsExtraKind:
  26251. case VertexBuffer.TangentKind:
  26252. return 4;
  26253. default:
  26254. throw new Error("Invalid kind '" + kind + "'");
  26255. }
  26256. };
  26257. // Enums
  26258. VertexBuffer._PositionKind = "position";
  26259. VertexBuffer._NormalKind = "normal";
  26260. VertexBuffer._TangentKind = "tangent";
  26261. VertexBuffer._UVKind = "uv";
  26262. VertexBuffer._UV2Kind = "uv2";
  26263. VertexBuffer._UV3Kind = "uv3";
  26264. VertexBuffer._UV4Kind = "uv4";
  26265. VertexBuffer._UV5Kind = "uv5";
  26266. VertexBuffer._UV6Kind = "uv6";
  26267. VertexBuffer._ColorKind = "color";
  26268. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  26269. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  26270. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  26271. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  26272. return VertexBuffer;
  26273. }());
  26274. BABYLON.VertexBuffer = VertexBuffer;
  26275. })(BABYLON || (BABYLON = {}));
  26276. //# sourceMappingURL=babylon.vertexBuffer.js.map
  26277. var BABYLON;
  26278. (function (BABYLON) {
  26279. /**
  26280. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  26281. */
  26282. var DummyInternalTextureTracker = /** @class */ (function () {
  26283. function DummyInternalTextureTracker() {
  26284. /**
  26285. * Gets or set the previous tracker in the list
  26286. */
  26287. this.previous = null;
  26288. /**
  26289. * Gets or set the next tracker in the list
  26290. */
  26291. this.next = null;
  26292. }
  26293. return DummyInternalTextureTracker;
  26294. }());
  26295. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  26296. })(BABYLON || (BABYLON = {}));
  26297. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  26298. var BABYLON;
  26299. (function (BABYLON) {
  26300. /**
  26301. * Class used to store data associated with WebGL texture data for the engine
  26302. * This class should not be used directly
  26303. */
  26304. var InternalTexture = /** @class */ (function () {
  26305. /**
  26306. * Creates a new InternalTexture
  26307. * @param engine defines the engine to use
  26308. * @param dataSource defines the type of data that will be used
  26309. */
  26310. function InternalTexture(engine, dataSource) {
  26311. /**
  26312. * Observable called when the texture is loaded
  26313. */
  26314. this.onLoadedObservable = new BABYLON.Observable();
  26315. /**
  26316. * Gets or set the previous tracker in the list
  26317. */
  26318. this.previous = null;
  26319. /**
  26320. * Gets or set the next tracker in the list
  26321. */
  26322. this.next = null;
  26323. // Private
  26324. /** @ignore */
  26325. this._initialSlot = -1;
  26326. /** @ignore */
  26327. this._designatedSlot = -1;
  26328. /** @ignore */
  26329. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  26330. /** @ignore */
  26331. this._comparisonFunction = 0;
  26332. /** @ignore */
  26333. this._references = 1;
  26334. this._engine = engine;
  26335. this._dataSource = dataSource;
  26336. this._webGLTexture = engine._createTexture();
  26337. }
  26338. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  26339. /**
  26340. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  26341. */
  26342. get: function () {
  26343. return this._dataSource;
  26344. },
  26345. enumerable: true,
  26346. configurable: true
  26347. });
  26348. /**
  26349. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  26350. */
  26351. InternalTexture.prototype.incrementReferences = function () {
  26352. this._references++;
  26353. };
  26354. /**
  26355. * Change the size of the texture (not the size of the content)
  26356. * @param width defines the new width
  26357. * @param height defines the new height
  26358. * @param depth defines the new depth (1 by default)
  26359. */
  26360. InternalTexture.prototype.updateSize = function (width, height, depth) {
  26361. if (depth === void 0) { depth = 1; }
  26362. this.width = width;
  26363. this.height = height;
  26364. this.depth = depth;
  26365. this.baseWidth = width;
  26366. this.baseHeight = height;
  26367. this.baseDepth = depth;
  26368. this._size = width * height * depth;
  26369. };
  26370. /** @ignore */
  26371. InternalTexture.prototype._rebuild = function () {
  26372. var _this = this;
  26373. var proxy;
  26374. this.isReady = false;
  26375. this._cachedCoordinatesMode = null;
  26376. this._cachedWrapU = null;
  26377. this._cachedWrapV = null;
  26378. this._cachedAnisotropicFilteringLevel = null;
  26379. switch (this._dataSource) {
  26380. case InternalTexture.DATASOURCE_TEMP:
  26381. return;
  26382. case InternalTexture.DATASOURCE_URL:
  26383. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  26384. _this.isReady = true;
  26385. }, null, this._buffer, undefined, this.format);
  26386. proxy._swapAndDie(this);
  26387. return;
  26388. case InternalTexture.DATASOURCE_RAW:
  26389. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  26390. proxy._swapAndDie(this);
  26391. this.isReady = true;
  26392. return;
  26393. case InternalTexture.DATASOURCE_RAW3D:
  26394. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  26395. proxy._swapAndDie(this);
  26396. this.isReady = true;
  26397. return;
  26398. case InternalTexture.DATASOURCE_DYNAMIC:
  26399. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  26400. proxy._swapAndDie(this);
  26401. // The engine will make sure to update content so no need to flag it as isReady = true
  26402. return;
  26403. case InternalTexture.DATASOURCE_RENDERTARGET:
  26404. var options = new BABYLON.RenderTargetCreationOptions();
  26405. options.generateDepthBuffer = this._generateDepthBuffer;
  26406. options.generateMipMaps = this.generateMipMaps;
  26407. options.generateStencilBuffer = this._generateStencilBuffer;
  26408. options.samplingMode = this.samplingMode;
  26409. options.type = this.type;
  26410. if (this.isCube) {
  26411. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  26412. }
  26413. else {
  26414. var size = {
  26415. width: this.width,
  26416. height: this.height
  26417. };
  26418. proxy = this._engine.createRenderTargetTexture(size, options);
  26419. }
  26420. proxy._swapAndDie(this);
  26421. this.isReady = true;
  26422. return;
  26423. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  26424. var depthTextureOptions = {
  26425. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  26426. comparisonFunction: this._comparisonFunction,
  26427. generateStencil: this._generateStencilBuffer,
  26428. };
  26429. if (this.isCube) {
  26430. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  26431. }
  26432. else {
  26433. proxy = this._engine.createDepthStencilCubeTexture(this.width, depthTextureOptions);
  26434. }
  26435. proxy._swapAndDie(this);
  26436. this.isReady = true;
  26437. return;
  26438. case InternalTexture.DATASOURCE_CUBE:
  26439. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  26440. _this.isReady = true;
  26441. }, null, this.format, this._extension);
  26442. proxy._swapAndDie(this);
  26443. return;
  26444. case InternalTexture.DATASOURCE_CUBERAW:
  26445. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  26446. proxy._swapAndDie(this);
  26447. this.isReady = true;
  26448. return;
  26449. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  26450. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  26451. if (proxy) {
  26452. proxy._swapAndDie(_this);
  26453. }
  26454. _this.isReady = true;
  26455. }, null, this.format, this._extension);
  26456. return;
  26457. }
  26458. };
  26459. InternalTexture.prototype._swapAndDie = function (target) {
  26460. target._webGLTexture = this._webGLTexture;
  26461. if (this._framebuffer) {
  26462. target._framebuffer = this._framebuffer;
  26463. }
  26464. if (this._depthStencilBuffer) {
  26465. target._depthStencilBuffer = this._depthStencilBuffer;
  26466. }
  26467. if (this._lodTextureHigh) {
  26468. if (target._lodTextureHigh) {
  26469. target._lodTextureHigh.dispose();
  26470. }
  26471. target._lodTextureHigh = this._lodTextureHigh;
  26472. }
  26473. if (this._lodTextureMid) {
  26474. if (target._lodTextureMid) {
  26475. target._lodTextureMid.dispose();
  26476. }
  26477. target._lodTextureMid = this._lodTextureMid;
  26478. }
  26479. if (this._lodTextureLow) {
  26480. if (target._lodTextureLow) {
  26481. target._lodTextureLow.dispose();
  26482. }
  26483. target._lodTextureLow = this._lodTextureLow;
  26484. }
  26485. var cache = this._engine.getLoadedTexturesCache();
  26486. var index = cache.indexOf(this);
  26487. if (index !== -1) {
  26488. cache.splice(index, 1);
  26489. }
  26490. };
  26491. /**
  26492. * Dispose the current allocated resources
  26493. */
  26494. InternalTexture.prototype.dispose = function () {
  26495. if (!this._webGLTexture) {
  26496. return;
  26497. }
  26498. this._references--;
  26499. if (this._references === 0) {
  26500. this._engine._releaseTexture(this);
  26501. this._webGLTexture = null;
  26502. this.previous = null;
  26503. this.next = null;
  26504. }
  26505. };
  26506. /**
  26507. * The source of the texture data is unknown
  26508. */
  26509. InternalTexture.DATASOURCE_UNKNOWN = 0;
  26510. /**
  26511. * Texture data comes from an URL
  26512. */
  26513. InternalTexture.DATASOURCE_URL = 1;
  26514. /**
  26515. * Texture data is only used for temporary storage
  26516. */
  26517. InternalTexture.DATASOURCE_TEMP = 2;
  26518. /**
  26519. * Texture data comes from raw data (ArrayBuffer)
  26520. */
  26521. InternalTexture.DATASOURCE_RAW = 3;
  26522. /**
  26523. * Texture content is dynamic (video or dynamic texture)
  26524. */
  26525. InternalTexture.DATASOURCE_DYNAMIC = 4;
  26526. /**
  26527. * Texture content is generated by rendering to it
  26528. */
  26529. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  26530. /**
  26531. * Texture content is part of a multi render target process
  26532. */
  26533. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  26534. /**
  26535. * Texture data comes from a cube data file
  26536. */
  26537. InternalTexture.DATASOURCE_CUBE = 7;
  26538. /**
  26539. * Texture data comes from a raw cube data
  26540. */
  26541. InternalTexture.DATASOURCE_CUBERAW = 8;
  26542. /**
  26543. * Texture data come from a prefiltered cube data file
  26544. */
  26545. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  26546. /**
  26547. * Texture content is raw 3D data
  26548. */
  26549. InternalTexture.DATASOURCE_RAW3D = 10;
  26550. /**
  26551. * Texture content is a depth texture
  26552. */
  26553. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  26554. return InternalTexture;
  26555. }());
  26556. BABYLON.InternalTexture = InternalTexture;
  26557. })(BABYLON || (BABYLON = {}));
  26558. //# sourceMappingURL=babylon.internalTexture.js.map
  26559. var BABYLON;
  26560. (function (BABYLON) {
  26561. var BaseTexture = /** @class */ (function () {
  26562. function BaseTexture(scene) {
  26563. this._hasAlpha = false;
  26564. this.getAlphaFromRGB = false;
  26565. this.level = 1;
  26566. this.coordinatesIndex = 0;
  26567. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  26568. /**
  26569. * | Value | Type | Description |
  26570. * | ----- | ------------------ | ----------- |
  26571. * | 0 | CLAMP_ADDRESSMODE | |
  26572. * | 1 | WRAP_ADDRESSMODE | |
  26573. * | 2 | MIRROR_ADDRESSMODE | |
  26574. */
  26575. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  26576. /**
  26577. * | Value | Type | Description |
  26578. * | ----- | ------------------ | ----------- |
  26579. * | 0 | CLAMP_ADDRESSMODE | |
  26580. * | 1 | WRAP_ADDRESSMODE | |
  26581. * | 2 | MIRROR_ADDRESSMODE | |
  26582. */
  26583. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  26584. /**
  26585. * | Value | Type | Description |
  26586. * | ----- | ------------------ | ----------- |
  26587. * | 0 | CLAMP_ADDRESSMODE | |
  26588. * | 1 | WRAP_ADDRESSMODE | |
  26589. * | 2 | MIRROR_ADDRESSMODE | |
  26590. */
  26591. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  26592. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  26593. this.isCube = false;
  26594. this.is3D = false;
  26595. this.gammaSpace = true;
  26596. this.invertZ = false;
  26597. this.lodLevelInAlpha = false;
  26598. this.lodGenerationOffset = 0.0;
  26599. this.lodGenerationScale = 0.8;
  26600. this.isRenderTarget = false;
  26601. this.animations = new Array();
  26602. /**
  26603. * An event triggered when the texture is disposed.
  26604. * @type {BABYLON.Observable}
  26605. */
  26606. this.onDisposeObservable = new BABYLON.Observable();
  26607. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  26608. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  26609. if (this._scene) {
  26610. this._scene.textures.push(this);
  26611. }
  26612. this._uid = null;
  26613. }
  26614. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  26615. get: function () {
  26616. return this._hasAlpha;
  26617. },
  26618. set: function (value) {
  26619. if (this._hasAlpha === value) {
  26620. return;
  26621. }
  26622. this._hasAlpha = value;
  26623. if (this._scene) {
  26624. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  26625. }
  26626. },
  26627. enumerable: true,
  26628. configurable: true
  26629. });
  26630. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  26631. get: function () {
  26632. return this._coordinatesMode;
  26633. },
  26634. /**
  26635. * How a texture is mapped.
  26636. *
  26637. * | Value | Type | Description |
  26638. * | ----- | ----------------------------------- | ----------- |
  26639. * | 0 | EXPLICIT_MODE | |
  26640. * | 1 | SPHERICAL_MODE | |
  26641. * | 2 | PLANAR_MODE | |
  26642. * | 3 | CUBIC_MODE | |
  26643. * | 4 | PROJECTION_MODE | |
  26644. * | 5 | SKYBOX_MODE | |
  26645. * | 6 | INVCUBIC_MODE | |
  26646. * | 7 | EQUIRECTANGULAR_MODE | |
  26647. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  26648. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  26649. */
  26650. set: function (value) {
  26651. if (this._coordinatesMode === value) {
  26652. return;
  26653. }
  26654. this._coordinatesMode = value;
  26655. if (this._scene) {
  26656. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  26657. }
  26658. },
  26659. enumerable: true,
  26660. configurable: true
  26661. });
  26662. Object.defineProperty(BaseTexture.prototype, "uid", {
  26663. get: function () {
  26664. if (!this._uid) {
  26665. this._uid = BABYLON.Tools.RandomId();
  26666. }
  26667. return this._uid;
  26668. },
  26669. enumerable: true,
  26670. configurable: true
  26671. });
  26672. BaseTexture.prototype.toString = function () {
  26673. return this.name;
  26674. };
  26675. BaseTexture.prototype.getClassName = function () {
  26676. return "BaseTexture";
  26677. };
  26678. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  26679. set: function (callback) {
  26680. if (this._onDisposeObserver) {
  26681. this.onDisposeObservable.remove(this._onDisposeObserver);
  26682. }
  26683. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  26684. },
  26685. enumerable: true,
  26686. configurable: true
  26687. });
  26688. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  26689. get: function () {
  26690. return true;
  26691. },
  26692. enumerable: true,
  26693. configurable: true
  26694. });
  26695. BaseTexture.prototype.getScene = function () {
  26696. return this._scene;
  26697. };
  26698. BaseTexture.prototype.getTextureMatrix = function () {
  26699. return BABYLON.Matrix.IdentityReadOnly;
  26700. };
  26701. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  26702. return BABYLON.Matrix.IdentityReadOnly;
  26703. };
  26704. BaseTexture.prototype.getInternalTexture = function () {
  26705. return this._texture;
  26706. };
  26707. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  26708. return !this.isBlocking || this.isReady();
  26709. };
  26710. BaseTexture.prototype.isReady = function () {
  26711. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  26712. this.delayLoad();
  26713. return false;
  26714. }
  26715. if (this._texture) {
  26716. return this._texture.isReady;
  26717. }
  26718. return false;
  26719. };
  26720. BaseTexture.prototype.getSize = function () {
  26721. if (this._texture && this._texture.width) {
  26722. return new BABYLON.Size(this._texture.width, this._texture.height);
  26723. }
  26724. if (this._texture && this._texture._size) {
  26725. return new BABYLON.Size(this._texture._size, this._texture._size);
  26726. }
  26727. return BABYLON.Size.Zero();
  26728. };
  26729. BaseTexture.prototype.getBaseSize = function () {
  26730. if (!this.isReady() || !this._texture)
  26731. return BABYLON.Size.Zero();
  26732. if (this._texture._size) {
  26733. return new BABYLON.Size(this._texture._size, this._texture._size);
  26734. }
  26735. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  26736. };
  26737. BaseTexture.prototype.scale = function (ratio) {
  26738. };
  26739. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  26740. get: function () {
  26741. return false;
  26742. },
  26743. enumerable: true,
  26744. configurable: true
  26745. });
  26746. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  26747. if (!this._scene) {
  26748. return null;
  26749. }
  26750. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  26751. for (var index = 0; index < texturesCache.length; index++) {
  26752. var texturesCacheEntry = texturesCache[index];
  26753. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  26754. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  26755. texturesCacheEntry.incrementReferences();
  26756. return texturesCacheEntry;
  26757. }
  26758. }
  26759. }
  26760. return null;
  26761. };
  26762. BaseTexture.prototype._rebuild = function () {
  26763. };
  26764. BaseTexture.prototype.delayLoad = function () {
  26765. };
  26766. BaseTexture.prototype.clone = function () {
  26767. return null;
  26768. };
  26769. Object.defineProperty(BaseTexture.prototype, "textureType", {
  26770. get: function () {
  26771. if (!this._texture) {
  26772. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  26773. }
  26774. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  26775. },
  26776. enumerable: true,
  26777. configurable: true
  26778. });
  26779. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  26780. get: function () {
  26781. if (!this._texture) {
  26782. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  26783. }
  26784. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  26785. },
  26786. enumerable: true,
  26787. configurable: true
  26788. });
  26789. BaseTexture.prototype.readPixels = function (faceIndex) {
  26790. if (faceIndex === void 0) { faceIndex = 0; }
  26791. if (!this._texture) {
  26792. return null;
  26793. }
  26794. var size = this.getSize();
  26795. var scene = this.getScene();
  26796. if (!scene) {
  26797. return null;
  26798. }
  26799. var engine = scene.getEngine();
  26800. if (this._texture.isCube) {
  26801. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  26802. }
  26803. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  26804. };
  26805. BaseTexture.prototype.releaseInternalTexture = function () {
  26806. if (this._texture) {
  26807. this._texture.dispose();
  26808. this._texture = null;
  26809. }
  26810. };
  26811. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  26812. get: function () {
  26813. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  26814. return null;
  26815. }
  26816. if (!this._texture._sphericalPolynomial) {
  26817. this._texture._sphericalPolynomial =
  26818. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  26819. }
  26820. return this._texture._sphericalPolynomial;
  26821. },
  26822. set: function (value) {
  26823. if (this._texture) {
  26824. this._texture._sphericalPolynomial = value;
  26825. }
  26826. },
  26827. enumerable: true,
  26828. configurable: true
  26829. });
  26830. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  26831. get: function () {
  26832. if (this._texture) {
  26833. return this._texture._lodTextureHigh;
  26834. }
  26835. return null;
  26836. },
  26837. enumerable: true,
  26838. configurable: true
  26839. });
  26840. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  26841. get: function () {
  26842. if (this._texture) {
  26843. return this._texture._lodTextureMid;
  26844. }
  26845. return null;
  26846. },
  26847. enumerable: true,
  26848. configurable: true
  26849. });
  26850. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  26851. get: function () {
  26852. if (this._texture) {
  26853. return this._texture._lodTextureLow;
  26854. }
  26855. return null;
  26856. },
  26857. enumerable: true,
  26858. configurable: true
  26859. });
  26860. BaseTexture.prototype.dispose = function () {
  26861. if (!this._scene) {
  26862. return;
  26863. }
  26864. // Animations
  26865. this._scene.stopAnimation(this);
  26866. // Remove from scene
  26867. this._scene._removePendingData(this);
  26868. var index = this._scene.textures.indexOf(this);
  26869. if (index >= 0) {
  26870. this._scene.textures.splice(index, 1);
  26871. }
  26872. if (this._texture === undefined) {
  26873. return;
  26874. }
  26875. // Release
  26876. this.releaseInternalTexture();
  26877. // Callback
  26878. this.onDisposeObservable.notifyObservers(this);
  26879. this.onDisposeObservable.clear();
  26880. };
  26881. BaseTexture.prototype.serialize = function () {
  26882. if (!this.name) {
  26883. return null;
  26884. }
  26885. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  26886. // Animations
  26887. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  26888. return serializationObject;
  26889. };
  26890. BaseTexture.WhenAllReady = function (textures, callback) {
  26891. var numRemaining = textures.length;
  26892. if (numRemaining === 0) {
  26893. callback();
  26894. return;
  26895. }
  26896. var _loop_1 = function () {
  26897. texture = textures[i];
  26898. if (texture.isReady()) {
  26899. if (--numRemaining === 0) {
  26900. callback();
  26901. }
  26902. }
  26903. else {
  26904. onLoadObservable = texture.onLoadObservable;
  26905. var onLoadCallback_1 = function () {
  26906. onLoadObservable.removeCallback(onLoadCallback_1);
  26907. if (--numRemaining === 0) {
  26908. callback();
  26909. }
  26910. };
  26911. onLoadObservable.add(onLoadCallback_1);
  26912. }
  26913. };
  26914. var texture, onLoadObservable;
  26915. for (var i = 0; i < textures.length; i++) {
  26916. _loop_1();
  26917. }
  26918. };
  26919. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  26920. __decorate([
  26921. BABYLON.serialize()
  26922. ], BaseTexture.prototype, "name", void 0);
  26923. __decorate([
  26924. BABYLON.serialize("hasAlpha")
  26925. ], BaseTexture.prototype, "_hasAlpha", void 0);
  26926. __decorate([
  26927. BABYLON.serialize()
  26928. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  26929. __decorate([
  26930. BABYLON.serialize()
  26931. ], BaseTexture.prototype, "level", void 0);
  26932. __decorate([
  26933. BABYLON.serialize()
  26934. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  26935. __decorate([
  26936. BABYLON.serialize("coordinatesMode")
  26937. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  26938. __decorate([
  26939. BABYLON.serialize()
  26940. ], BaseTexture.prototype, "wrapU", void 0);
  26941. __decorate([
  26942. BABYLON.serialize()
  26943. ], BaseTexture.prototype, "wrapV", void 0);
  26944. __decorate([
  26945. BABYLON.serialize()
  26946. ], BaseTexture.prototype, "wrapR", void 0);
  26947. __decorate([
  26948. BABYLON.serialize()
  26949. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  26950. __decorate([
  26951. BABYLON.serialize()
  26952. ], BaseTexture.prototype, "isCube", void 0);
  26953. __decorate([
  26954. BABYLON.serialize()
  26955. ], BaseTexture.prototype, "is3D", void 0);
  26956. __decorate([
  26957. BABYLON.serialize()
  26958. ], BaseTexture.prototype, "gammaSpace", void 0);
  26959. __decorate([
  26960. BABYLON.serialize()
  26961. ], BaseTexture.prototype, "invertZ", void 0);
  26962. __decorate([
  26963. BABYLON.serialize()
  26964. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  26965. __decorate([
  26966. BABYLON.serialize()
  26967. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  26968. __decorate([
  26969. BABYLON.serialize()
  26970. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  26971. __decorate([
  26972. BABYLON.serialize()
  26973. ], BaseTexture.prototype, "isRenderTarget", void 0);
  26974. return BaseTexture;
  26975. }());
  26976. BABYLON.BaseTexture = BaseTexture;
  26977. })(BABYLON || (BABYLON = {}));
  26978. //# sourceMappingURL=babylon.baseTexture.js.map
  26979. var BABYLON;
  26980. (function (BABYLON) {
  26981. var Texture = /** @class */ (function (_super) {
  26982. __extends(Texture, _super);
  26983. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  26984. if (noMipmap === void 0) { noMipmap = false; }
  26985. if (invertY === void 0) { invertY = true; }
  26986. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  26987. if (onLoad === void 0) { onLoad = null; }
  26988. if (onError === void 0) { onError = null; }
  26989. if (buffer === void 0) { buffer = null; }
  26990. if (deleteBuffer === void 0) { deleteBuffer = false; }
  26991. var _this = _super.call(this, scene) || this;
  26992. _this.uOffset = 0;
  26993. _this.vOffset = 0;
  26994. _this.uScale = 1.0;
  26995. _this.vScale = 1.0;
  26996. _this.uAng = 0;
  26997. _this.vAng = 0;
  26998. _this.wAng = 0;
  26999. _this._isBlocking = true;
  27000. _this.name = url || "";
  27001. _this.url = url;
  27002. _this._noMipmap = noMipmap;
  27003. _this._invertY = invertY;
  27004. _this._samplingMode = samplingMode;
  27005. _this._buffer = buffer;
  27006. _this._deleteBuffer = deleteBuffer;
  27007. if (format) {
  27008. _this._format = format;
  27009. }
  27010. scene = _this.getScene();
  27011. if (!scene) {
  27012. return _this;
  27013. }
  27014. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  27015. var load = function () {
  27016. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  27017. _this.onLoadObservable.notifyObservers(_this);
  27018. }
  27019. if (onLoad) {
  27020. onLoad();
  27021. }
  27022. if (!_this.isBlocking && scene) {
  27023. scene.resetCachedMaterial();
  27024. }
  27025. };
  27026. if (!_this.url) {
  27027. _this._delayedOnLoad = load;
  27028. _this._delayedOnError = onError;
  27029. return _this;
  27030. }
  27031. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  27032. if (!_this._texture) {
  27033. if (!scene.useDelayedTextureLoading) {
  27034. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  27035. if (deleteBuffer) {
  27036. delete _this._buffer;
  27037. }
  27038. }
  27039. else {
  27040. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  27041. _this._delayedOnLoad = load;
  27042. _this._delayedOnError = onError;
  27043. }
  27044. }
  27045. else {
  27046. if (_this._texture.isReady) {
  27047. BABYLON.Tools.SetImmediate(function () { return load(); });
  27048. }
  27049. else {
  27050. _this._texture.onLoadedObservable.add(load);
  27051. }
  27052. }
  27053. return _this;
  27054. }
  27055. Object.defineProperty(Texture.prototype, "noMipmap", {
  27056. get: function () {
  27057. return this._noMipmap;
  27058. },
  27059. enumerable: true,
  27060. configurable: true
  27061. });
  27062. Object.defineProperty(Texture.prototype, "isBlocking", {
  27063. get: function () {
  27064. return this._isBlocking;
  27065. },
  27066. set: function (value) {
  27067. this._isBlocking = value;
  27068. },
  27069. enumerable: true,
  27070. configurable: true
  27071. });
  27072. Object.defineProperty(Texture.prototype, "samplingMode", {
  27073. get: function () {
  27074. return this._samplingMode;
  27075. },
  27076. enumerable: true,
  27077. configurable: true
  27078. });
  27079. Texture.prototype.updateURL = function (url) {
  27080. this.url = url;
  27081. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  27082. this.delayLoad();
  27083. };
  27084. Texture.prototype.delayLoad = function () {
  27085. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  27086. return;
  27087. }
  27088. var scene = this.getScene();
  27089. if (!scene) {
  27090. return;
  27091. }
  27092. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  27093. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  27094. if (!this._texture) {
  27095. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  27096. if (this._deleteBuffer) {
  27097. delete this._buffer;
  27098. }
  27099. }
  27100. else {
  27101. if (this._delayedOnLoad) {
  27102. if (this._texture.isReady) {
  27103. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  27104. }
  27105. else {
  27106. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  27107. }
  27108. }
  27109. }
  27110. this._delayedOnLoad = null;
  27111. this._delayedOnError = null;
  27112. };
  27113. Texture.prototype.updateSamplingMode = function (samplingMode) {
  27114. if (!this._texture) {
  27115. return;
  27116. }
  27117. var scene = this.getScene();
  27118. if (!scene) {
  27119. return;
  27120. }
  27121. this._samplingMode = samplingMode;
  27122. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  27123. };
  27124. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  27125. x *= this.uScale;
  27126. y *= this.vScale;
  27127. x -= 0.5 * this.uScale;
  27128. y -= 0.5 * this.vScale;
  27129. z -= 0.5;
  27130. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  27131. t.x += 0.5 * this.uScale + this.uOffset;
  27132. t.y += 0.5 * this.vScale + this.vOffset;
  27133. t.z += 0.5;
  27134. };
  27135. Texture.prototype.getTextureMatrix = function () {
  27136. var _this = this;
  27137. if (this.uOffset === this._cachedUOffset &&
  27138. this.vOffset === this._cachedVOffset &&
  27139. this.uScale === this._cachedUScale &&
  27140. this.vScale === this._cachedVScale &&
  27141. this.uAng === this._cachedUAng &&
  27142. this.vAng === this._cachedVAng &&
  27143. this.wAng === this._cachedWAng) {
  27144. return this._cachedTextureMatrix;
  27145. }
  27146. this._cachedUOffset = this.uOffset;
  27147. this._cachedVOffset = this.vOffset;
  27148. this._cachedUScale = this.uScale;
  27149. this._cachedVScale = this.vScale;
  27150. this._cachedUAng = this.uAng;
  27151. this._cachedVAng = this.vAng;
  27152. this._cachedWAng = this.wAng;
  27153. if (!this._cachedTextureMatrix) {
  27154. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  27155. this._rowGenerationMatrix = new BABYLON.Matrix();
  27156. this._t0 = BABYLON.Vector3.Zero();
  27157. this._t1 = BABYLON.Vector3.Zero();
  27158. this._t2 = BABYLON.Vector3.Zero();
  27159. }
  27160. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  27161. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  27162. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  27163. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  27164. this._t1.subtractInPlace(this._t0);
  27165. this._t2.subtractInPlace(this._t0);
  27166. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  27167. this._cachedTextureMatrix.m[0] = this._t1.x;
  27168. this._cachedTextureMatrix.m[1] = this._t1.y;
  27169. this._cachedTextureMatrix.m[2] = this._t1.z;
  27170. this._cachedTextureMatrix.m[4] = this._t2.x;
  27171. this._cachedTextureMatrix.m[5] = this._t2.y;
  27172. this._cachedTextureMatrix.m[6] = this._t2.z;
  27173. this._cachedTextureMatrix.m[8] = this._t0.x;
  27174. this._cachedTextureMatrix.m[9] = this._t0.y;
  27175. this._cachedTextureMatrix.m[10] = this._t0.z;
  27176. var scene = this.getScene();
  27177. if (!scene) {
  27178. return this._cachedTextureMatrix;
  27179. }
  27180. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  27181. return mat.hasTexture(_this);
  27182. });
  27183. return this._cachedTextureMatrix;
  27184. };
  27185. Texture.prototype.getReflectionTextureMatrix = function () {
  27186. var _this = this;
  27187. var scene = this.getScene();
  27188. if (!scene) {
  27189. return this._cachedTextureMatrix;
  27190. }
  27191. if (this.uOffset === this._cachedUOffset &&
  27192. this.vOffset === this._cachedVOffset &&
  27193. this.uScale === this._cachedUScale &&
  27194. this.vScale === this._cachedVScale &&
  27195. this.coordinatesMode === this._cachedCoordinatesMode) {
  27196. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  27197. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  27198. return this._cachedTextureMatrix;
  27199. }
  27200. }
  27201. else {
  27202. return this._cachedTextureMatrix;
  27203. }
  27204. }
  27205. if (!this._cachedTextureMatrix) {
  27206. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  27207. }
  27208. if (!this._projectionModeMatrix) {
  27209. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  27210. }
  27211. this._cachedUOffset = this.uOffset;
  27212. this._cachedVOffset = this.vOffset;
  27213. this._cachedUScale = this.uScale;
  27214. this._cachedVScale = this.vScale;
  27215. this._cachedCoordinatesMode = this.coordinatesMode;
  27216. switch (this.coordinatesMode) {
  27217. case Texture.PLANAR_MODE:
  27218. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  27219. this._cachedTextureMatrix[0] = this.uScale;
  27220. this._cachedTextureMatrix[5] = this.vScale;
  27221. this._cachedTextureMatrix[12] = this.uOffset;
  27222. this._cachedTextureMatrix[13] = this.vOffset;
  27223. break;
  27224. case Texture.PROJECTION_MODE:
  27225. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  27226. this._projectionModeMatrix.m[0] = 0.5;
  27227. this._projectionModeMatrix.m[5] = -0.5;
  27228. this._projectionModeMatrix.m[10] = 0.0;
  27229. this._projectionModeMatrix.m[12] = 0.5;
  27230. this._projectionModeMatrix.m[13] = 0.5;
  27231. this._projectionModeMatrix.m[14] = 1.0;
  27232. this._projectionModeMatrix.m[15] = 1.0;
  27233. var projectionMatrix = scene.getProjectionMatrix();
  27234. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  27235. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  27236. break;
  27237. default:
  27238. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  27239. break;
  27240. }
  27241. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  27242. return (mat.getActiveTextures().indexOf(_this) !== -1);
  27243. });
  27244. return this._cachedTextureMatrix;
  27245. };
  27246. Texture.prototype.clone = function () {
  27247. var _this = this;
  27248. return BABYLON.SerializationHelper.Clone(function () {
  27249. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  27250. }, this);
  27251. };
  27252. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  27253. get: function () {
  27254. if (!this._onLoadObservable) {
  27255. this._onLoadObservable = new BABYLON.Observable();
  27256. }
  27257. return this._onLoadObservable;
  27258. },
  27259. enumerable: true,
  27260. configurable: true
  27261. });
  27262. Texture.prototype.serialize = function () {
  27263. var serializationObject = _super.prototype.serialize.call(this);
  27264. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  27265. serializationObject.base64String = this._buffer;
  27266. serializationObject.name = serializationObject.name.replace("data:", "");
  27267. }
  27268. return serializationObject;
  27269. };
  27270. Texture.prototype.getClassName = function () {
  27271. return "Texture";
  27272. };
  27273. Texture.prototype.dispose = function () {
  27274. _super.prototype.dispose.call(this);
  27275. if (this.onLoadObservable) {
  27276. this.onLoadObservable.clear();
  27277. this._onLoadObservable = null;
  27278. }
  27279. this._delayedOnLoad = null;
  27280. this._delayedOnError = null;
  27281. };
  27282. // Statics
  27283. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  27284. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  27285. if (onLoad === void 0) { onLoad = null; }
  27286. if (onError === void 0) { onError = null; }
  27287. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  27288. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  27289. };
  27290. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  27291. if (parsedTexture.customType) {
  27292. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  27293. // Update Sampling Mode
  27294. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  27295. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  27296. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  27297. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  27298. }
  27299. }
  27300. return parsedCustomTexture;
  27301. }
  27302. if (parsedTexture.isCube) {
  27303. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  27304. }
  27305. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  27306. return null;
  27307. }
  27308. var texture = BABYLON.SerializationHelper.Parse(function () {
  27309. var generateMipMaps = true;
  27310. if (parsedTexture.noMipmap) {
  27311. generateMipMaps = false;
  27312. }
  27313. if (parsedTexture.mirrorPlane) {
  27314. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  27315. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  27316. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  27317. return mirrorTexture;
  27318. }
  27319. else if (parsedTexture.isRenderTarget) {
  27320. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  27321. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  27322. return renderTargetTexture;
  27323. }
  27324. else {
  27325. var texture;
  27326. if (parsedTexture.base64String) {
  27327. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  27328. }
  27329. else {
  27330. var url = rootUrl + parsedTexture.name;
  27331. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  27332. url = parsedTexture.url;
  27333. }
  27334. texture = new Texture(url, scene, !generateMipMaps);
  27335. }
  27336. return texture;
  27337. }
  27338. }, parsedTexture, scene);
  27339. // Update Sampling Mode
  27340. if (parsedTexture.samplingMode) {
  27341. var sampling = parsedTexture.samplingMode;
  27342. if (texture._samplingMode !== sampling) {
  27343. texture.updateSamplingMode(sampling);
  27344. }
  27345. }
  27346. // Animations
  27347. if (parsedTexture.animations) {
  27348. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  27349. var parsedAnimation = parsedTexture.animations[animationIndex];
  27350. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  27351. }
  27352. }
  27353. return texture;
  27354. };
  27355. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  27356. if (deleteBuffer === void 0) { deleteBuffer = false; }
  27357. if (noMipmap === void 0) { noMipmap = false; }
  27358. if (invertY === void 0) { invertY = true; }
  27359. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  27360. if (onLoad === void 0) { onLoad = null; }
  27361. if (onError === void 0) { onError = null; }
  27362. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  27363. if (name.substr(0, 5) !== "data:") {
  27364. name = "data:" + name;
  27365. }
  27366. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  27367. };
  27368. // Constants
  27369. Texture.NEAREST_SAMPLINGMODE = 1;
  27370. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  27371. Texture.BILINEAR_SAMPLINGMODE = 2;
  27372. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  27373. Texture.TRILINEAR_SAMPLINGMODE = 3;
  27374. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  27375. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  27376. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  27377. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  27378. Texture.NEAREST_LINEAR = 7;
  27379. Texture.NEAREST_NEAREST = 8;
  27380. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  27381. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  27382. Texture.LINEAR_LINEAR = 11;
  27383. Texture.LINEAR_NEAREST = 12;
  27384. Texture.EXPLICIT_MODE = 0;
  27385. Texture.SPHERICAL_MODE = 1;
  27386. Texture.PLANAR_MODE = 2;
  27387. Texture.CUBIC_MODE = 3;
  27388. Texture.PROJECTION_MODE = 4;
  27389. Texture.SKYBOX_MODE = 5;
  27390. Texture.INVCUBIC_MODE = 6;
  27391. Texture.EQUIRECTANGULAR_MODE = 7;
  27392. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  27393. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  27394. Texture.CLAMP_ADDRESSMODE = 0;
  27395. Texture.WRAP_ADDRESSMODE = 1;
  27396. Texture.MIRROR_ADDRESSMODE = 2;
  27397. /**
  27398. * Gets or sets a boolean which defines if the texture url must be build from the serialized URL instead of just using the name and loading them side by side with the scene file
  27399. */
  27400. Texture.UseSerializedUrlIfAny = false;
  27401. __decorate([
  27402. BABYLON.serialize()
  27403. ], Texture.prototype, "url", void 0);
  27404. __decorate([
  27405. BABYLON.serialize()
  27406. ], Texture.prototype, "uOffset", void 0);
  27407. __decorate([
  27408. BABYLON.serialize()
  27409. ], Texture.prototype, "vOffset", void 0);
  27410. __decorate([
  27411. BABYLON.serialize()
  27412. ], Texture.prototype, "uScale", void 0);
  27413. __decorate([
  27414. BABYLON.serialize()
  27415. ], Texture.prototype, "vScale", void 0);
  27416. __decorate([
  27417. BABYLON.serialize()
  27418. ], Texture.prototype, "uAng", void 0);
  27419. __decorate([
  27420. BABYLON.serialize()
  27421. ], Texture.prototype, "vAng", void 0);
  27422. __decorate([
  27423. BABYLON.serialize()
  27424. ], Texture.prototype, "wAng", void 0);
  27425. __decorate([
  27426. BABYLON.serialize()
  27427. ], Texture.prototype, "isBlocking", null);
  27428. return Texture;
  27429. }(BABYLON.BaseTexture));
  27430. BABYLON.Texture = Texture;
  27431. })(BABYLON || (BABYLON = {}));
  27432. //# sourceMappingURL=babylon.texture.js.map
  27433. var BABYLON;
  27434. (function (BABYLON) {
  27435. var _InstancesBatch = /** @class */ (function () {
  27436. function _InstancesBatch() {
  27437. this.mustReturn = false;
  27438. this.visibleInstances = new Array();
  27439. this.renderSelf = new Array();
  27440. }
  27441. return _InstancesBatch;
  27442. }());
  27443. BABYLON._InstancesBatch = _InstancesBatch;
  27444. var Mesh = /** @class */ (function (_super) {
  27445. __extends(Mesh, _super);
  27446. /**
  27447. * @constructor
  27448. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  27449. * @param {Scene} scene The scene to add this mesh to.
  27450. * @param {Node} parent The parent of this mesh, if it has one
  27451. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  27452. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  27453. * When false, achieved by calling a clone(), also passing False.
  27454. * This will make creation of children, recursive.
  27455. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  27456. */
  27457. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  27458. if (scene === void 0) { scene = null; }
  27459. if (parent === void 0) { parent = null; }
  27460. if (source === void 0) { source = null; }
  27461. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  27462. var _this = _super.call(this, name, scene) || this;
  27463. // Events
  27464. /**
  27465. * An event triggered before rendering the mesh
  27466. * @type {BABYLON.Observable}
  27467. */
  27468. _this.onBeforeRenderObservable = new BABYLON.Observable();
  27469. /**
  27470. * An event triggered after rendering the mesh
  27471. * @type {BABYLON.Observable}
  27472. */
  27473. _this.onAfterRenderObservable = new BABYLON.Observable();
  27474. /**
  27475. * An event triggered before drawing the mesh
  27476. * @type {BABYLON.Observable}
  27477. */
  27478. _this.onBeforeDrawObservable = new BABYLON.Observable();
  27479. // Members
  27480. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  27481. _this.instances = new Array();
  27482. _this._LODLevels = new Array();
  27483. _this._visibleInstances = {};
  27484. _this._renderIdForInstances = new Array();
  27485. _this._batchCache = new _InstancesBatch();
  27486. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  27487. // Use by builder only to know what orientation were the mesh build in.
  27488. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  27489. _this.overrideMaterialSideOrientation = null;
  27490. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  27491. // Will be used to save a source mesh reference, If any
  27492. _this._source = null;
  27493. scene = _this.getScene();
  27494. if (source) {
  27495. // Source mesh
  27496. _this._source = source;
  27497. // Geometry
  27498. if (source._geometry) {
  27499. source._geometry.applyToMesh(_this);
  27500. }
  27501. // Deep copy
  27502. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId", "source", "metadata"], ["_poseMatrix", "_source"]);
  27503. // Metadata
  27504. if (source.metadata && source.metadata.clone) {
  27505. _this.metadata = source.metadata.clone();
  27506. }
  27507. else {
  27508. _this.metadata = source.metadata;
  27509. }
  27510. // Tags
  27511. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  27512. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  27513. }
  27514. // Parent
  27515. _this.parent = source.parent;
  27516. // Pivot
  27517. _this.setPivotMatrix(source.getPivotMatrix());
  27518. _this.id = name + "." + source.id;
  27519. // Material
  27520. _this.material = source.material;
  27521. var index;
  27522. if (!doNotCloneChildren) {
  27523. // Children
  27524. var directDescendants = source.getDescendants(true);
  27525. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  27526. var child = directDescendants[index_1];
  27527. if (child.clone) {
  27528. child.clone(name + "." + child.name, _this);
  27529. }
  27530. }
  27531. }
  27532. // Physics clone
  27533. var physicsEngine = _this.getScene().getPhysicsEngine();
  27534. if (clonePhysicsImpostor && physicsEngine) {
  27535. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  27536. if (impostor) {
  27537. _this.physicsImpostor = impostor.clone(_this);
  27538. }
  27539. }
  27540. // Particles
  27541. for (index = 0; index < scene.particleSystems.length; index++) {
  27542. var system = scene.particleSystems[index];
  27543. if (system.emitter === source) {
  27544. system.clone(system.name, _this);
  27545. }
  27546. }
  27547. _this.computeWorldMatrix(true);
  27548. }
  27549. // Parent
  27550. if (parent !== null) {
  27551. _this.parent = parent;
  27552. }
  27553. return _this;
  27554. }
  27555. Object.defineProperty(Mesh, "FRONTSIDE", {
  27556. /**
  27557. * Mesh side orientation : usually the external or front surface
  27558. */
  27559. get: function () {
  27560. return Mesh._FRONTSIDE;
  27561. },
  27562. enumerable: true,
  27563. configurable: true
  27564. });
  27565. Object.defineProperty(Mesh, "BACKSIDE", {
  27566. /**
  27567. * Mesh side orientation : usually the internal or back surface
  27568. */
  27569. get: function () {
  27570. return Mesh._BACKSIDE;
  27571. },
  27572. enumerable: true,
  27573. configurable: true
  27574. });
  27575. Object.defineProperty(Mesh, "DOUBLESIDE", {
  27576. /**
  27577. * Mesh side orientation : both internal and external or front and back surfaces
  27578. */
  27579. get: function () {
  27580. return Mesh._DOUBLESIDE;
  27581. },
  27582. enumerable: true,
  27583. configurable: true
  27584. });
  27585. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  27586. /**
  27587. * Mesh side orientation : by default, `FRONTSIDE`
  27588. */
  27589. get: function () {
  27590. return Mesh._DEFAULTSIDE;
  27591. },
  27592. enumerable: true,
  27593. configurable: true
  27594. });
  27595. Object.defineProperty(Mesh, "NO_CAP", {
  27596. /**
  27597. * Mesh cap setting : no cap
  27598. */
  27599. get: function () {
  27600. return Mesh._NO_CAP;
  27601. },
  27602. enumerable: true,
  27603. configurable: true
  27604. });
  27605. Object.defineProperty(Mesh, "CAP_START", {
  27606. /**
  27607. * Mesh cap setting : one cap at the beginning of the mesh
  27608. */
  27609. get: function () {
  27610. return Mesh._CAP_START;
  27611. },
  27612. enumerable: true,
  27613. configurable: true
  27614. });
  27615. Object.defineProperty(Mesh, "CAP_END", {
  27616. /**
  27617. * Mesh cap setting : one cap at the end of the mesh
  27618. */
  27619. get: function () {
  27620. return Mesh._CAP_END;
  27621. },
  27622. enumerable: true,
  27623. configurable: true
  27624. });
  27625. Object.defineProperty(Mesh, "CAP_ALL", {
  27626. /**
  27627. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  27628. */
  27629. get: function () {
  27630. return Mesh._CAP_ALL;
  27631. },
  27632. enumerable: true,
  27633. configurable: true
  27634. });
  27635. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  27636. set: function (callback) {
  27637. if (this._onBeforeDrawObserver) {
  27638. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  27639. }
  27640. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  27641. },
  27642. enumerable: true,
  27643. configurable: true
  27644. });
  27645. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  27646. get: function () {
  27647. return this._morphTargetManager;
  27648. },
  27649. set: function (value) {
  27650. if (this._morphTargetManager === value) {
  27651. return;
  27652. }
  27653. this._morphTargetManager = value;
  27654. this._syncGeometryWithMorphTargetManager();
  27655. },
  27656. enumerable: true,
  27657. configurable: true
  27658. });
  27659. Object.defineProperty(Mesh.prototype, "source", {
  27660. get: function () {
  27661. return this._source;
  27662. },
  27663. enumerable: true,
  27664. configurable: true
  27665. });
  27666. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  27667. get: function () {
  27668. return this._unIndexed;
  27669. },
  27670. set: function (value) {
  27671. if (this._unIndexed !== value) {
  27672. this._unIndexed = value;
  27673. this._markSubMeshesAsAttributesDirty();
  27674. }
  27675. },
  27676. enumerable: true,
  27677. configurable: true
  27678. });
  27679. // Methods
  27680. /**
  27681. * Returns the string "Mesh".
  27682. */
  27683. Mesh.prototype.getClassName = function () {
  27684. return "Mesh";
  27685. };
  27686. /**
  27687. * Returns a string.
  27688. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  27689. */
  27690. Mesh.prototype.toString = function (fullDetails) {
  27691. var ret = _super.prototype.toString.call(this, fullDetails);
  27692. ret += ", n vertices: " + this.getTotalVertices();
  27693. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  27694. if (this.animations) {
  27695. for (var i = 0; i < this.animations.length; i++) {
  27696. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  27697. }
  27698. }
  27699. if (fullDetails) {
  27700. if (this._geometry) {
  27701. var ib = this.getIndices();
  27702. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27703. if (vb && ib) {
  27704. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  27705. }
  27706. }
  27707. else {
  27708. ret += ", flat shading: UNKNOWN";
  27709. }
  27710. }
  27711. return ret;
  27712. };
  27713. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  27714. /**
  27715. * True if the mesh has some Levels Of Details (LOD).
  27716. * Returns a boolean.
  27717. */
  27718. get: function () {
  27719. return this._LODLevels.length > 0;
  27720. },
  27721. enumerable: true,
  27722. configurable: true
  27723. });
  27724. /**
  27725. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  27726. * @returns an array of {BABYLON.MeshLODLevel}
  27727. */
  27728. Mesh.prototype.getLODLevels = function () {
  27729. return this._LODLevels;
  27730. };
  27731. Mesh.prototype._sortLODLevels = function () {
  27732. this._LODLevels.sort(function (a, b) {
  27733. if (a.distance < b.distance) {
  27734. return 1;
  27735. }
  27736. if (a.distance > b.distance) {
  27737. return -1;
  27738. }
  27739. return 0;
  27740. });
  27741. };
  27742. /**
  27743. * Add a mesh as LOD level triggered at the given distance.
  27744. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  27745. * @param {number} distance The distance from the center of the object to show this level
  27746. * @param {Mesh} mesh The mesh to be added as LOD level
  27747. * @return {Mesh} This mesh (for chaining)
  27748. */
  27749. Mesh.prototype.addLODLevel = function (distance, mesh) {
  27750. if (mesh && mesh._masterMesh) {
  27751. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  27752. return this;
  27753. }
  27754. var level = new BABYLON.MeshLODLevel(distance, mesh);
  27755. this._LODLevels.push(level);
  27756. if (mesh) {
  27757. mesh._masterMesh = this;
  27758. }
  27759. this._sortLODLevels();
  27760. return this;
  27761. };
  27762. /**
  27763. * Returns the LOD level mesh at the passed distance or null if not found.
  27764. * It is related to the method `addLODLevel(distance, mesh)`.
  27765. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  27766. * Returns an object Mesh or `null`.
  27767. */
  27768. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  27769. for (var index = 0; index < this._LODLevels.length; index++) {
  27770. var level = this._LODLevels[index];
  27771. if (level.distance === distance) {
  27772. return level.mesh;
  27773. }
  27774. }
  27775. return null;
  27776. };
  27777. /**
  27778. * Remove a mesh from the LOD array
  27779. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  27780. * @param {Mesh} mesh The mesh to be removed.
  27781. * @return {Mesh} This mesh (for chaining)
  27782. */
  27783. Mesh.prototype.removeLODLevel = function (mesh) {
  27784. for (var index = 0; index < this._LODLevels.length; index++) {
  27785. if (this._LODLevels[index].mesh === mesh) {
  27786. this._LODLevels.splice(index, 1);
  27787. if (mesh) {
  27788. mesh._masterMesh = null;
  27789. }
  27790. }
  27791. }
  27792. this._sortLODLevels();
  27793. return this;
  27794. };
  27795. /**
  27796. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  27797. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  27798. */
  27799. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  27800. if (!this._LODLevels || this._LODLevels.length === 0) {
  27801. return this;
  27802. }
  27803. var bSphere;
  27804. if (boundingSphere) {
  27805. bSphere = boundingSphere;
  27806. }
  27807. else {
  27808. var boundingInfo = this.getBoundingInfo();
  27809. bSphere = boundingInfo.boundingSphere;
  27810. }
  27811. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  27812. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  27813. if (this.onLODLevelSelection) {
  27814. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  27815. }
  27816. return this;
  27817. }
  27818. for (var index = 0; index < this._LODLevels.length; index++) {
  27819. var level = this._LODLevels[index];
  27820. if (level.distance < distanceToCamera) {
  27821. if (level.mesh) {
  27822. level.mesh._preActivate();
  27823. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  27824. }
  27825. if (this.onLODLevelSelection) {
  27826. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  27827. }
  27828. return level.mesh;
  27829. }
  27830. }
  27831. if (this.onLODLevelSelection) {
  27832. this.onLODLevelSelection(distanceToCamera, this, this);
  27833. }
  27834. return this;
  27835. };
  27836. Object.defineProperty(Mesh.prototype, "geometry", {
  27837. /**
  27838. * Returns the mesh internal Geometry object.
  27839. */
  27840. get: function () {
  27841. return this._geometry;
  27842. },
  27843. enumerable: true,
  27844. configurable: true
  27845. });
  27846. /**
  27847. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  27848. */
  27849. Mesh.prototype.getTotalVertices = function () {
  27850. if (this._geometry === null || this._geometry === undefined) {
  27851. return 0;
  27852. }
  27853. return this._geometry.getTotalVertices();
  27854. };
  27855. /**
  27856. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  27857. * If `copywhenShared` is true (default false) and if the mesh geometry is shared among some other meshes, the returned array is a copy of the internal one.
  27858. * You can force the copy with forceCopy === true
  27859. * Returns null if the mesh has no geometry or no vertex buffer.
  27860. * Possible `kind` values :
  27861. * - BABYLON.VertexBuffer.PositionKind
  27862. * - BABYLON.VertexBuffer.UVKind
  27863. * - BABYLON.VertexBuffer.UV2Kind
  27864. * - BABYLON.VertexBuffer.UV3Kind
  27865. * - BABYLON.VertexBuffer.UV4Kind
  27866. * - BABYLON.VertexBuffer.UV5Kind
  27867. * - BABYLON.VertexBuffer.UV6Kind
  27868. * - BABYLON.VertexBuffer.ColorKind
  27869. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27870. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27871. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27872. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27873. */
  27874. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  27875. if (!this._geometry) {
  27876. return null;
  27877. }
  27878. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  27879. };
  27880. /**
  27881. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  27882. * Returns `null` if the mesh has no geometry.
  27883. * Possible `kind` values :
  27884. * - BABYLON.VertexBuffer.PositionKind
  27885. * - BABYLON.VertexBuffer.UVKind
  27886. * - BABYLON.VertexBuffer.UV2Kind
  27887. * - BABYLON.VertexBuffer.UV3Kind
  27888. * - BABYLON.VertexBuffer.UV4Kind
  27889. * - BABYLON.VertexBuffer.UV5Kind
  27890. * - BABYLON.VertexBuffer.UV6Kind
  27891. * - BABYLON.VertexBuffer.ColorKind
  27892. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27893. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27894. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27895. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27896. */
  27897. Mesh.prototype.getVertexBuffer = function (kind) {
  27898. if (!this._geometry) {
  27899. return null;
  27900. }
  27901. return this._geometry.getVertexBuffer(kind);
  27902. };
  27903. /**
  27904. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  27905. * Possible `kind` values :
  27906. * - BABYLON.VertexBuffer.PositionKind
  27907. * - BABYLON.VertexBuffer.UVKind
  27908. * - BABYLON.VertexBuffer.UV2Kind
  27909. * - BABYLON.VertexBuffer.UV3Kind
  27910. * - BABYLON.VertexBuffer.UV4Kind
  27911. * - BABYLON.VertexBuffer.UV5Kind
  27912. * - BABYLON.VertexBuffer.UV6Kind
  27913. * - BABYLON.VertexBuffer.ColorKind
  27914. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27915. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27916. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27917. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27918. */
  27919. Mesh.prototype.isVerticesDataPresent = function (kind) {
  27920. if (!this._geometry) {
  27921. if (this._delayInfo) {
  27922. return this._delayInfo.indexOf(kind) !== -1;
  27923. }
  27924. return false;
  27925. }
  27926. return this._geometry.isVerticesDataPresent(kind);
  27927. };
  27928. /**
  27929. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  27930. * Possible `kind` values :
  27931. * - BABYLON.VertexBuffer.PositionKind
  27932. * - BABYLON.VertexBuffer.UVKind
  27933. * - BABYLON.VertexBuffer.UV2Kind
  27934. * - BABYLON.VertexBuffer.UV3Kind
  27935. * - BABYLON.VertexBuffer.UV4Kind
  27936. * - BABYLON.VertexBuffer.UV5Kind
  27937. * - BABYLON.VertexBuffer.UV6Kind
  27938. * - BABYLON.VertexBuffer.ColorKind
  27939. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27940. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27941. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27942. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27943. */
  27944. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  27945. if (!this._geometry) {
  27946. if (this._delayInfo) {
  27947. return this._delayInfo.indexOf(kind) !== -1;
  27948. }
  27949. return false;
  27950. }
  27951. return this._geometry.isVertexBufferUpdatable(kind);
  27952. };
  27953. /**
  27954. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  27955. * Possible `kind` values :
  27956. * - BABYLON.VertexBuffer.PositionKind
  27957. * - BABYLON.VertexBuffer.UVKind
  27958. * - BABYLON.VertexBuffer.UV2Kind
  27959. * - BABYLON.VertexBuffer.UV3Kind
  27960. * - BABYLON.VertexBuffer.UV4Kind
  27961. * - BABYLON.VertexBuffer.UV5Kind
  27962. * - BABYLON.VertexBuffer.UV6Kind
  27963. * - BABYLON.VertexBuffer.ColorKind
  27964. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27965. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27966. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27967. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27968. */
  27969. Mesh.prototype.getVerticesDataKinds = function () {
  27970. if (!this._geometry) {
  27971. var result = new Array();
  27972. if (this._delayInfo) {
  27973. this._delayInfo.forEach(function (kind, index, array) {
  27974. result.push(kind);
  27975. });
  27976. }
  27977. return result;
  27978. }
  27979. return this._geometry.getVerticesDataKinds();
  27980. };
  27981. /**
  27982. * Returns a positive integer : the total number of indices in this mesh geometry.
  27983. * Returns zero if the mesh has no geometry.
  27984. */
  27985. Mesh.prototype.getTotalIndices = function () {
  27986. if (!this._geometry) {
  27987. return 0;
  27988. }
  27989. return this._geometry.getTotalIndices();
  27990. };
  27991. /**
  27992. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  27993. * If the parameter `copyWhenShared` is true (default false) and and if the mesh geometry is shared among some other meshes, the returned array is a copy of the internal one.
  27994. * Returns an empty array if the mesh has no geometry.
  27995. */
  27996. Mesh.prototype.getIndices = function (copyWhenShared) {
  27997. if (!this._geometry) {
  27998. return [];
  27999. }
  28000. return this._geometry.getIndices(copyWhenShared);
  28001. };
  28002. Object.defineProperty(Mesh.prototype, "isBlocked", {
  28003. get: function () {
  28004. return this._masterMesh !== null && this._masterMesh !== undefined;
  28005. },
  28006. enumerable: true,
  28007. configurable: true
  28008. });
  28009. /**
  28010. * Determine if the current mesh is ready to be rendered
  28011. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  28012. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  28013. * @returns true if all associated assets are ready (material, textures, shaders)
  28014. */
  28015. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  28016. if (completeCheck === void 0) { completeCheck = false; }
  28017. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  28018. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  28019. return false;
  28020. }
  28021. if (!_super.prototype.isReady.call(this, completeCheck)) {
  28022. return false;
  28023. }
  28024. if (!this.subMeshes || this.subMeshes.length === 0) {
  28025. return true;
  28026. }
  28027. if (!completeCheck) {
  28028. return true;
  28029. }
  28030. var engine = this.getEngine();
  28031. var scene = this.getScene();
  28032. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  28033. this.computeWorldMatrix();
  28034. var mat = this.material || scene.defaultMaterial;
  28035. if (mat) {
  28036. if (mat.storeEffectOnSubMeshes) {
  28037. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  28038. var subMesh = _a[_i];
  28039. var effectiveMaterial = subMesh.getMaterial();
  28040. if (effectiveMaterial) {
  28041. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  28042. return false;
  28043. }
  28044. }
  28045. }
  28046. }
  28047. else {
  28048. if (!mat.isReady(this, hardwareInstancedRendering)) {
  28049. return false;
  28050. }
  28051. }
  28052. }
  28053. // Shadows
  28054. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  28055. var light = _c[_b];
  28056. var generator = light.getShadowGenerator();
  28057. if (generator) {
  28058. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  28059. var subMesh = _e[_d];
  28060. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  28061. return false;
  28062. }
  28063. }
  28064. }
  28065. }
  28066. // LOD
  28067. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  28068. var lod = _g[_f];
  28069. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  28070. return false;
  28071. }
  28072. }
  28073. return true;
  28074. };
  28075. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  28076. /**
  28077. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  28078. * This property is pertinent only for updatable parametric shapes.
  28079. */
  28080. get: function () {
  28081. return this._areNormalsFrozen;
  28082. },
  28083. enumerable: true,
  28084. configurable: true
  28085. });
  28086. /**
  28087. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  28088. * It has no effect at all on other shapes.
  28089. * It prevents the mesh normals from being recomputed on next `positions` array update.
  28090. * Returns the Mesh.
  28091. */
  28092. Mesh.prototype.freezeNormals = function () {
  28093. this._areNormalsFrozen = true;
  28094. return this;
  28095. };
  28096. /**
  28097. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  28098. * It has no effect at all on other shapes.
  28099. * It reactivates the mesh normals computation if it was previously frozen.
  28100. * Returns the Mesh.
  28101. */
  28102. Mesh.prototype.unfreezeNormals = function () {
  28103. this._areNormalsFrozen = false;
  28104. return this;
  28105. };
  28106. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  28107. /**
  28108. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  28109. */
  28110. set: function (count) {
  28111. this._overridenInstanceCount = count;
  28112. },
  28113. enumerable: true,
  28114. configurable: true
  28115. });
  28116. // Methods
  28117. Mesh.prototype._preActivate = function () {
  28118. var sceneRenderId = this.getScene().getRenderId();
  28119. if (this._preActivateId === sceneRenderId) {
  28120. return this;
  28121. }
  28122. this._preActivateId = sceneRenderId;
  28123. this._visibleInstances = null;
  28124. return this;
  28125. };
  28126. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  28127. if (this._visibleInstances) {
  28128. this._visibleInstances.intermediateDefaultRenderId = renderId;
  28129. }
  28130. return this;
  28131. };
  28132. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  28133. if (!this._visibleInstances) {
  28134. this._visibleInstances = {};
  28135. this._visibleInstances.defaultRenderId = renderId;
  28136. this._visibleInstances.selfDefaultRenderId = this._renderId;
  28137. }
  28138. if (!this._visibleInstances[renderId]) {
  28139. this._visibleInstances[renderId] = new Array();
  28140. }
  28141. this._visibleInstances[renderId].push(instance);
  28142. return this;
  28143. };
  28144. /**
  28145. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  28146. * This means the mesh underlying bounding box and sphere are recomputed.
  28147. * Returns the Mesh.
  28148. */
  28149. Mesh.prototype.refreshBoundingInfo = function () {
  28150. return this._refreshBoundingInfo(false);
  28151. };
  28152. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  28153. if (this._boundingInfo && this._boundingInfo.isLocked) {
  28154. return this;
  28155. }
  28156. var data = this._getPositionData(applySkeleton);
  28157. if (data) {
  28158. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  28159. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  28160. }
  28161. if (this.subMeshes) {
  28162. for (var index = 0; index < this.subMeshes.length; index++) {
  28163. this.subMeshes[index].refreshBoundingInfo();
  28164. }
  28165. }
  28166. this._updateBoundingInfo();
  28167. return this;
  28168. };
  28169. Mesh.prototype._getPositionData = function (applySkeleton) {
  28170. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28171. if (data && applySkeleton && this.skeleton) {
  28172. data = BABYLON.Tools.Slice(data);
  28173. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  28174. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  28175. if (matricesWeightsData && matricesIndicesData) {
  28176. var needExtras = this.numBoneInfluencers > 4;
  28177. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  28178. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  28179. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  28180. var tempVector = BABYLON.Tmp.Vector3[0];
  28181. var finalMatrix = BABYLON.Tmp.Matrix[0];
  28182. var tempMatrix = BABYLON.Tmp.Matrix[1];
  28183. var matWeightIdx = 0;
  28184. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  28185. finalMatrix.reset();
  28186. var inf;
  28187. var weight;
  28188. for (inf = 0; inf < 4; inf++) {
  28189. weight = matricesWeightsData[matWeightIdx + inf];
  28190. if (weight <= 0)
  28191. break;
  28192. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  28193. finalMatrix.addToSelf(tempMatrix);
  28194. }
  28195. if (needExtras) {
  28196. for (inf = 0; inf < 4; inf++) {
  28197. weight = matricesWeightsExtraData[matWeightIdx + inf];
  28198. if (weight <= 0)
  28199. break;
  28200. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  28201. finalMatrix.addToSelf(tempMatrix);
  28202. }
  28203. }
  28204. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  28205. tempVector.toArray(data, index);
  28206. }
  28207. }
  28208. }
  28209. return data;
  28210. };
  28211. Mesh.prototype._createGlobalSubMesh = function (force) {
  28212. var totalVertices = this.getTotalVertices();
  28213. if (!totalVertices || !this.getIndices()) {
  28214. return null;
  28215. }
  28216. // Check if we need to recreate the submeshes
  28217. if (this.subMeshes && this.subMeshes.length > 0) {
  28218. var ib = this.getIndices();
  28219. if (!ib) {
  28220. return null;
  28221. }
  28222. var totalIndices = ib.length;
  28223. var needToRecreate = false;
  28224. if (force) {
  28225. needToRecreate = true;
  28226. }
  28227. else {
  28228. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  28229. var submesh = _a[_i];
  28230. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  28231. needToRecreate = true;
  28232. break;
  28233. }
  28234. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  28235. needToRecreate = true;
  28236. break;
  28237. }
  28238. }
  28239. }
  28240. if (!needToRecreate) {
  28241. return this.subMeshes[0];
  28242. }
  28243. }
  28244. this.releaseSubMeshes();
  28245. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  28246. };
  28247. Mesh.prototype.subdivide = function (count) {
  28248. if (count < 1) {
  28249. return;
  28250. }
  28251. var totalIndices = this.getTotalIndices();
  28252. var subdivisionSize = (totalIndices / count) | 0;
  28253. var offset = 0;
  28254. // Ensure that subdivisionSize is a multiple of 3
  28255. while (subdivisionSize % 3 !== 0) {
  28256. subdivisionSize++;
  28257. }
  28258. this.releaseSubMeshes();
  28259. for (var index = 0; index < count; index++) {
  28260. if (offset >= totalIndices) {
  28261. break;
  28262. }
  28263. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  28264. offset += subdivisionSize;
  28265. }
  28266. this.synchronizeInstances();
  28267. };
  28268. /**
  28269. * Sets the vertex data of the mesh geometry for the requested `kind`.
  28270. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  28271. * The `data` are either a numeric array either a Float32Array.
  28272. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  28273. * The parameter `stride` is an optional positive integer, it is usually automatically deducted from the `kind` (3 for positions or normals, 2 for UV, etc).
  28274. * Note that a new underlying VertexBuffer object is created each call.
  28275. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  28276. *
  28277. * Possible `kind` values :
  28278. * - BABYLON.VertexBuffer.PositionKind
  28279. * - BABYLON.VertexBuffer.UVKind
  28280. * - BABYLON.VertexBuffer.UV2Kind
  28281. * - BABYLON.VertexBuffer.UV3Kind
  28282. * - BABYLON.VertexBuffer.UV4Kind
  28283. * - BABYLON.VertexBuffer.UV5Kind
  28284. * - BABYLON.VertexBuffer.UV6Kind
  28285. * - BABYLON.VertexBuffer.ColorKind
  28286. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28287. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28288. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28289. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28290. *
  28291. * Returns the Mesh.
  28292. */
  28293. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  28294. if (updatable === void 0) { updatable = false; }
  28295. if (!this._geometry) {
  28296. var vertexData = new BABYLON.VertexData();
  28297. vertexData.set(data, kind);
  28298. var scene = this.getScene();
  28299. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  28300. }
  28301. else {
  28302. this._geometry.setVerticesData(kind, data, updatable, stride);
  28303. }
  28304. return this;
  28305. };
  28306. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  28307. if (updatable === void 0) { updatable = true; }
  28308. var vb = this.getVertexBuffer(kind);
  28309. if (!vb || vb.isUpdatable() === updatable) {
  28310. return;
  28311. }
  28312. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  28313. };
  28314. /**
  28315. * Sets the mesh VertexBuffer.
  28316. * Returns the Mesh.
  28317. */
  28318. Mesh.prototype.setVerticesBuffer = function (buffer) {
  28319. if (!this._geometry) {
  28320. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  28321. }
  28322. this._geometry.setVerticesBuffer(buffer);
  28323. return this;
  28324. };
  28325. /**
  28326. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  28327. * If the mesh has no geometry, it is simply returned as it is.
  28328. * The `data` are either a numeric array either a Float32Array.
  28329. * No new underlying VertexBuffer object is created.
  28330. * If the `kind` is the `PositionKind` and if `updateExtends` is true, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  28331. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  28332. *
  28333. * Possible `kind` values :
  28334. * - BABYLON.VertexBuffer.PositionKind
  28335. * - BABYLON.VertexBuffer.UVKind
  28336. * - BABYLON.VertexBuffer.UV2Kind
  28337. * - BABYLON.VertexBuffer.UV3Kind
  28338. * - BABYLON.VertexBuffer.UV4Kind
  28339. * - BABYLON.VertexBuffer.UV5Kind
  28340. * - BABYLON.VertexBuffer.UV6Kind
  28341. * - BABYLON.VertexBuffer.ColorKind
  28342. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28343. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28344. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28345. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28346. *
  28347. * Returns the Mesh.
  28348. */
  28349. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  28350. if (!this._geometry) {
  28351. return this;
  28352. }
  28353. if (!makeItUnique) {
  28354. this._geometry.updateVerticesData(kind, data, updateExtends);
  28355. }
  28356. else {
  28357. this.makeGeometryUnique();
  28358. this.updateVerticesData(kind, data, updateExtends, false);
  28359. }
  28360. return this;
  28361. };
  28362. /**
  28363. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  28364. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  28365. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  28366. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  28367. * Returns the Mesh.
  28368. */
  28369. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  28370. if (computeNormals === void 0) { computeNormals = true; }
  28371. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28372. if (!positions) {
  28373. return this;
  28374. }
  28375. positionFunction(positions);
  28376. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  28377. if (computeNormals) {
  28378. var indices = this.getIndices();
  28379. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28380. if (!normals) {
  28381. return this;
  28382. }
  28383. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  28384. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  28385. }
  28386. return this;
  28387. };
  28388. /**
  28389. * Creates a un-shared specific occurence of the geometry for the mesh.
  28390. * Returns the Mesh.
  28391. */
  28392. Mesh.prototype.makeGeometryUnique = function () {
  28393. if (!this._geometry) {
  28394. return this;
  28395. }
  28396. var oldGeometry = this._geometry;
  28397. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  28398. oldGeometry.releaseForMesh(this, true);
  28399. geometry.applyToMesh(this);
  28400. return this;
  28401. };
  28402. /**
  28403. * Sets the mesh indices.
  28404. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  28405. * Type is Uint16Array by default unless the mesh has more than 65536 vertices.
  28406. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  28407. * This method creates a new index buffer each call.
  28408. * Returns the Mesh.
  28409. */
  28410. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  28411. if (totalVertices === void 0) { totalVertices = null; }
  28412. if (updatable === void 0) { updatable = false; }
  28413. if (!this._geometry) {
  28414. var vertexData = new BABYLON.VertexData();
  28415. vertexData.indices = indices;
  28416. var scene = this.getScene();
  28417. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  28418. }
  28419. else {
  28420. this._geometry.setIndices(indices, totalVertices, updatable);
  28421. }
  28422. return this;
  28423. };
  28424. /**
  28425. * Update the current index buffer
  28426. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  28427. * Returns the Mesh.
  28428. */
  28429. Mesh.prototype.updateIndices = function (indices, offset) {
  28430. if (!this._geometry) {
  28431. return this;
  28432. }
  28433. this._geometry.updateIndices(indices, offset);
  28434. return this;
  28435. };
  28436. /**
  28437. * Invert the geometry to move from a right handed system to a left handed one.
  28438. * Returns the Mesh.
  28439. */
  28440. Mesh.prototype.toLeftHanded = function () {
  28441. if (!this._geometry) {
  28442. return this;
  28443. }
  28444. this._geometry.toLeftHanded();
  28445. return this;
  28446. };
  28447. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  28448. if (!this._geometry) {
  28449. return this;
  28450. }
  28451. var engine = this.getScene().getEngine();
  28452. // Wireframe
  28453. var indexToBind;
  28454. if (this._unIndexed) {
  28455. indexToBind = null;
  28456. }
  28457. else {
  28458. switch (fillMode) {
  28459. case BABYLON.Material.PointFillMode:
  28460. indexToBind = null;
  28461. break;
  28462. case BABYLON.Material.WireFrameFillMode:
  28463. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  28464. break;
  28465. default:
  28466. case BABYLON.Material.TriangleFillMode:
  28467. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  28468. break;
  28469. }
  28470. }
  28471. // VBOs
  28472. this._geometry._bind(effect, indexToBind);
  28473. return this;
  28474. };
  28475. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  28476. if (alternate === void 0) { alternate = false; }
  28477. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  28478. return this;
  28479. }
  28480. this.onBeforeDrawObservable.notifyObservers(this);
  28481. var scene = this.getScene();
  28482. var engine = scene.getEngine();
  28483. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  28484. // or triangles as points
  28485. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  28486. }
  28487. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  28488. // Triangles as wireframe
  28489. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  28490. }
  28491. else {
  28492. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  28493. }
  28494. if (scene._isAlternateRenderingEnabled && !alternate) {
  28495. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  28496. if (!effect || !scene.activeCamera) {
  28497. return this;
  28498. }
  28499. scene._switchToAlternateCameraConfiguration(true);
  28500. this._effectiveMaterial.bindView(effect);
  28501. this._effectiveMaterial.bindViewProjection(effect);
  28502. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  28503. this._draw(subMesh, fillMode, instancesCount, true);
  28504. engine.setViewport(scene.activeCamera.viewport);
  28505. scene._switchToAlternateCameraConfiguration(false);
  28506. this._effectiveMaterial.bindView(effect);
  28507. this._effectiveMaterial.bindViewProjection(effect);
  28508. }
  28509. return this;
  28510. };
  28511. /**
  28512. * Registers for this mesh a javascript function called just before the rendering process.
  28513. * This function is passed the current mesh.
  28514. * Return the Mesh.
  28515. */
  28516. Mesh.prototype.registerBeforeRender = function (func) {
  28517. this.onBeforeRenderObservable.add(func);
  28518. return this;
  28519. };
  28520. /**
  28521. * Disposes a previously registered javascript function called before the rendering.
  28522. * This function is passed the current mesh.
  28523. * Returns the Mesh.
  28524. */
  28525. Mesh.prototype.unregisterBeforeRender = function (func) {
  28526. this.onBeforeRenderObservable.removeCallback(func);
  28527. return this;
  28528. };
  28529. /**
  28530. * Registers for this mesh a javascript function called just after the rendering is complete.
  28531. * This function is passed the current mesh.
  28532. * Returns the Mesh.
  28533. */
  28534. Mesh.prototype.registerAfterRender = function (func) {
  28535. this.onAfterRenderObservable.add(func);
  28536. return this;
  28537. };
  28538. /**
  28539. * Disposes a previously registered javascript function called after the rendering.
  28540. * This function is passed the current mesh.
  28541. * Return the Mesh.
  28542. */
  28543. Mesh.prototype.unregisterAfterRender = function (func) {
  28544. this.onAfterRenderObservable.removeCallback(func);
  28545. return this;
  28546. };
  28547. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  28548. var scene = this.getScene();
  28549. this._batchCache.mustReturn = false;
  28550. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  28551. this._batchCache.visibleInstances[subMeshId] = null;
  28552. if (this._visibleInstances) {
  28553. var currentRenderId = scene.getRenderId();
  28554. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  28555. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  28556. var selfRenderId = this._renderId;
  28557. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  28558. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  28559. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  28560. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  28561. }
  28562. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  28563. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  28564. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  28565. this._batchCache.mustReturn = true;
  28566. return this._batchCache;
  28567. }
  28568. if (currentRenderId !== selfRenderId) {
  28569. this._batchCache.renderSelf[subMeshId] = false;
  28570. }
  28571. }
  28572. this._renderIdForInstances[subMeshId] = currentRenderId;
  28573. }
  28574. return this._batchCache;
  28575. };
  28576. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  28577. var visibleInstances = batch.visibleInstances[subMesh._id];
  28578. if (!visibleInstances) {
  28579. return this;
  28580. }
  28581. var matricesCount = visibleInstances.length + 1;
  28582. var bufferSize = matricesCount * 16 * 4;
  28583. var currentInstancesBufferSize = this._instancesBufferSize;
  28584. var instancesBuffer = this._instancesBuffer;
  28585. while (this._instancesBufferSize < bufferSize) {
  28586. this._instancesBufferSize *= 2;
  28587. }
  28588. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  28589. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  28590. }
  28591. var offset = 0;
  28592. var instancesCount = 0;
  28593. var world = this.getWorldMatrix();
  28594. if (batch.renderSelf[subMesh._id]) {
  28595. world.copyToArray(this._instancesData, offset);
  28596. offset += 16;
  28597. instancesCount++;
  28598. }
  28599. if (visibleInstances) {
  28600. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  28601. var instance = visibleInstances[instanceIndex];
  28602. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  28603. offset += 16;
  28604. instancesCount++;
  28605. }
  28606. }
  28607. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  28608. if (instancesBuffer) {
  28609. instancesBuffer.dispose();
  28610. }
  28611. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  28612. this._instancesBuffer = instancesBuffer;
  28613. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  28614. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  28615. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  28616. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  28617. }
  28618. else {
  28619. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  28620. }
  28621. this._bind(subMesh, effect, fillMode);
  28622. this._draw(subMesh, fillMode, instancesCount);
  28623. engine.unbindInstanceAttributes();
  28624. return this;
  28625. };
  28626. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  28627. var scene = this.getScene();
  28628. var engine = scene.getEngine();
  28629. if (hardwareInstancedRendering) {
  28630. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  28631. }
  28632. else {
  28633. if (batch.renderSelf[subMesh._id]) {
  28634. // Draw
  28635. if (onBeforeDraw) {
  28636. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  28637. }
  28638. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  28639. }
  28640. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  28641. if (visibleInstancesForSubMesh) {
  28642. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  28643. var instance = visibleInstancesForSubMesh[instanceIndex];
  28644. // World
  28645. var world = instance.getWorldMatrix();
  28646. if (onBeforeDraw) {
  28647. onBeforeDraw(true, world, effectiveMaterial);
  28648. }
  28649. // Draw
  28650. this._draw(subMesh, fillMode);
  28651. }
  28652. }
  28653. }
  28654. return this;
  28655. };
  28656. /**
  28657. * Triggers the draw call for the mesh.
  28658. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  28659. * Returns the Mesh.
  28660. */
  28661. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  28662. this.checkOcclusionQuery();
  28663. if (this._isOccluded) {
  28664. return this;
  28665. }
  28666. var scene = this.getScene();
  28667. // Managing instances
  28668. var batch = this._getInstancesRenderList(subMesh._id);
  28669. if (batch.mustReturn) {
  28670. return this;
  28671. }
  28672. // Checking geometry state
  28673. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  28674. return this;
  28675. }
  28676. this.onBeforeRenderObservable.notifyObservers(this);
  28677. var engine = scene.getEngine();
  28678. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  28679. // Material
  28680. var material = subMesh.getMaterial();
  28681. if (!material) {
  28682. return this;
  28683. }
  28684. this._effectiveMaterial = material;
  28685. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  28686. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  28687. return this;
  28688. }
  28689. }
  28690. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  28691. return this;
  28692. }
  28693. // Alpha mode
  28694. if (enableAlphaMode) {
  28695. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  28696. }
  28697. // Outline - step 1
  28698. var savedDepthWrite = engine.getDepthWrite();
  28699. if (this.renderOutline) {
  28700. engine.setDepthWrite(false);
  28701. scene.getOutlineRenderer().render(subMesh, batch);
  28702. engine.setDepthWrite(savedDepthWrite);
  28703. }
  28704. var effect;
  28705. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  28706. effect = subMesh.effect;
  28707. }
  28708. else {
  28709. effect = this._effectiveMaterial.getEffect();
  28710. }
  28711. if (!effect) {
  28712. return this;
  28713. }
  28714. var sideOrientation = this.overrideMaterialSideOrientation;
  28715. if (sideOrientation == null) {
  28716. sideOrientation = this._effectiveMaterial.sideOrientation;
  28717. if (this._getWorldMatrixDeterminant() < 0) {
  28718. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  28719. }
  28720. }
  28721. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  28722. if (this._effectiveMaterial.forceDepthWrite) {
  28723. engine.setDepthWrite(true);
  28724. }
  28725. // Bind
  28726. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  28727. if (!hardwareInstancedRendering) {
  28728. this._bind(subMesh, effect, fillMode);
  28729. }
  28730. var world = this.getWorldMatrix();
  28731. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  28732. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  28733. }
  28734. else {
  28735. this._effectiveMaterial.bind(world, this);
  28736. }
  28737. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  28738. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  28739. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  28740. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  28741. }
  28742. // Draw
  28743. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  28744. // Unbind
  28745. this._effectiveMaterial.unbind();
  28746. // Outline - step 2
  28747. if (this.renderOutline && savedDepthWrite) {
  28748. engine.setDepthWrite(true);
  28749. engine.setColorWrite(false);
  28750. scene.getOutlineRenderer().render(subMesh, batch);
  28751. engine.setColorWrite(true);
  28752. }
  28753. // Overlay
  28754. if (this.renderOverlay) {
  28755. var currentMode = engine.getAlphaMode();
  28756. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  28757. scene.getOutlineRenderer().render(subMesh, batch, true);
  28758. engine.setAlphaMode(currentMode);
  28759. }
  28760. this.onAfterRenderObservable.notifyObservers(this);
  28761. return this;
  28762. };
  28763. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  28764. if (isInstance && effectiveMaterial) {
  28765. effectiveMaterial.bindOnlyWorldMatrix(world);
  28766. }
  28767. };
  28768. /**
  28769. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  28770. */
  28771. Mesh.prototype.getEmittedParticleSystems = function () {
  28772. var results = new Array();
  28773. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  28774. var particleSystem = this.getScene().particleSystems[index];
  28775. if (particleSystem.emitter === this) {
  28776. results.push(particleSystem);
  28777. }
  28778. }
  28779. return results;
  28780. };
  28781. /**
  28782. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  28783. */
  28784. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  28785. var results = new Array();
  28786. var descendants = this.getDescendants();
  28787. descendants.push(this);
  28788. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  28789. var particleSystem = this.getScene().particleSystems[index];
  28790. var emitter = particleSystem.emitter;
  28791. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  28792. results.push(particleSystem);
  28793. }
  28794. }
  28795. return results;
  28796. };
  28797. Mesh.prototype._checkDelayState = function () {
  28798. var scene = this.getScene();
  28799. if (this._geometry) {
  28800. this._geometry.load(scene);
  28801. }
  28802. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  28803. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  28804. this._queueLoad(scene);
  28805. }
  28806. return this;
  28807. };
  28808. Mesh.prototype._queueLoad = function (scene) {
  28809. var _this = this;
  28810. scene._addPendingData(this);
  28811. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  28812. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  28813. if (data instanceof ArrayBuffer) {
  28814. _this._delayLoadingFunction(data, _this);
  28815. }
  28816. else {
  28817. _this._delayLoadingFunction(JSON.parse(data), _this);
  28818. }
  28819. _this.instances.forEach(function (instance) {
  28820. instance._syncSubMeshes();
  28821. });
  28822. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  28823. scene._removePendingData(_this);
  28824. }, function () { }, scene.database, getBinaryData);
  28825. return this;
  28826. };
  28827. /**
  28828. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  28829. */
  28830. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  28831. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  28832. return false;
  28833. }
  28834. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  28835. return false;
  28836. }
  28837. this._checkDelayState();
  28838. return true;
  28839. };
  28840. /**
  28841. * Sets the mesh material by the material or multiMaterial `id` property.
  28842. * The material `id` is a string identifying the material or the multiMaterial.
  28843. * This method returns the Mesh.
  28844. */
  28845. Mesh.prototype.setMaterialByID = function (id) {
  28846. var materials = this.getScene().materials;
  28847. var index;
  28848. for (index = materials.length - 1; index > -1; index--) {
  28849. if (materials[index].id === id) {
  28850. this.material = materials[index];
  28851. return this;
  28852. }
  28853. }
  28854. // Multi
  28855. var multiMaterials = this.getScene().multiMaterials;
  28856. for (index = multiMaterials.length - 1; index > -1; index--) {
  28857. if (multiMaterials[index].id === id) {
  28858. this.material = multiMaterials[index];
  28859. return this;
  28860. }
  28861. }
  28862. return this;
  28863. };
  28864. /**
  28865. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  28866. */
  28867. Mesh.prototype.getAnimatables = function () {
  28868. var results = new Array();
  28869. if (this.material) {
  28870. results.push(this.material);
  28871. }
  28872. if (this.skeleton) {
  28873. results.push(this.skeleton);
  28874. }
  28875. return results;
  28876. };
  28877. /**
  28878. * Modifies the mesh geometry according to the passed transformation matrix.
  28879. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  28880. * The mesh normals are modified accordingly the same transformation.
  28881. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  28882. * Note that, under the hood, this method sets a new VertexBuffer each call.
  28883. * Returns the Mesh.
  28884. */
  28885. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  28886. // Position
  28887. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  28888. return this;
  28889. }
  28890. var submeshes = this.subMeshes.splice(0);
  28891. this._resetPointsArrayCache();
  28892. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28893. var temp = new Array();
  28894. var index;
  28895. for (index = 0; index < data.length; index += 3) {
  28896. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  28897. }
  28898. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  28899. // Normals
  28900. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  28901. return this;
  28902. }
  28903. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28904. temp = [];
  28905. for (index = 0; index < data.length; index += 3) {
  28906. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  28907. }
  28908. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  28909. // flip faces?
  28910. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  28911. this.flipFaces();
  28912. }
  28913. // Restore submeshes
  28914. this.releaseSubMeshes();
  28915. this.subMeshes = submeshes;
  28916. return this;
  28917. };
  28918. /**
  28919. * Modifies the mesh geometry according to its own current World Matrix.
  28920. * The mesh World Matrix is then reset.
  28921. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  28922. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  28923. * Note that, under the hood, this method sets a new VertexBuffer each call.
  28924. * Returns the Mesh.
  28925. */
  28926. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  28927. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  28928. this.scaling.copyFromFloats(1, 1, 1);
  28929. this.position.copyFromFloats(0, 0, 0);
  28930. this.rotation.copyFromFloats(0, 0, 0);
  28931. //only if quaternion is already set
  28932. if (this.rotationQuaternion) {
  28933. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  28934. }
  28935. this._worldMatrix = BABYLON.Matrix.Identity();
  28936. return this;
  28937. };
  28938. Object.defineProperty(Mesh.prototype, "_positions", {
  28939. // Cache
  28940. get: function () {
  28941. if (this._geometry) {
  28942. return this._geometry._positions;
  28943. }
  28944. return null;
  28945. },
  28946. enumerable: true,
  28947. configurable: true
  28948. });
  28949. Mesh.prototype._resetPointsArrayCache = function () {
  28950. if (this._geometry) {
  28951. this._geometry._resetPointsArrayCache();
  28952. }
  28953. return this;
  28954. };
  28955. Mesh.prototype._generatePointsArray = function () {
  28956. if (this._geometry) {
  28957. return this._geometry._generatePointsArray();
  28958. }
  28959. return false;
  28960. };
  28961. /**
  28962. * Returns a new Mesh object generated from the current mesh properties.
  28963. * This method must not get confused with createInstance().
  28964. * The parameter `name` is a string, the name given to the new mesh.
  28965. * The optional parameter `newParent` can be any Node object (default `null`).
  28966. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  28967. * The parameter `clonePhysicsImpostor` (default `true`) allows/denies the cloning in the same time of the original mesh `body` used by the physics engine, if any.
  28968. */
  28969. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  28970. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  28971. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  28972. };
  28973. /**
  28974. * Releases resources associated with this mesh.
  28975. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  28976. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  28977. */
  28978. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  28979. var _this = this;
  28980. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  28981. this.morphTargetManager = null;
  28982. if (this._geometry) {
  28983. this._geometry.releaseForMesh(this, true);
  28984. }
  28985. // Sources
  28986. var meshes = this.getScene().meshes;
  28987. meshes.forEach(function (abstractMesh) {
  28988. var mesh = abstractMesh;
  28989. if (mesh._source && mesh._source === _this) {
  28990. mesh._source = null;
  28991. }
  28992. });
  28993. this._source = null;
  28994. // Instances
  28995. if (this._instancesBuffer) {
  28996. this._instancesBuffer.dispose();
  28997. this._instancesBuffer = null;
  28998. }
  28999. while (this.instances.length) {
  29000. this.instances[0].dispose();
  29001. }
  29002. // Effect layers.
  29003. var effectLayers = this.getScene().effectLayers;
  29004. for (var i = 0; i < effectLayers.length; i++) {
  29005. var effectLayer = effectLayers[i];
  29006. if (effectLayer) {
  29007. effectLayer._disposeMesh(this);
  29008. }
  29009. }
  29010. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  29011. };
  29012. /**
  29013. * Modifies the mesh geometry according to a displacement map.
  29014. * A displacement map is a colored image. Each pixel color value (actually a gradient computed from red, green, blue values) will give the displacement to apply to each mesh vertex.
  29015. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  29016. * This method returns nothing.
  29017. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  29018. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  29019. * The parameter `onSuccess` is an optional Javascript function to be called just after the mesh is modified. It is passed the modified mesh and must return nothing.
  29020. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  29021. * The parameter `uvScale` is an optional vector2 used to scale UV.
  29022. *
  29023. * Returns the Mesh.
  29024. */
  29025. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  29026. var _this = this;
  29027. var scene = this.getScene();
  29028. var onload = function (img) {
  29029. // Getting height map data
  29030. var canvas = document.createElement("canvas");
  29031. var context = canvas.getContext("2d");
  29032. var heightMapWidth = img.width;
  29033. var heightMapHeight = img.height;
  29034. canvas.width = heightMapWidth;
  29035. canvas.height = heightMapHeight;
  29036. context.drawImage(img, 0, 0);
  29037. // Create VertexData from map data
  29038. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  29039. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  29040. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  29041. //execute success callback, if set
  29042. if (onSuccess) {
  29043. onSuccess(_this);
  29044. }
  29045. };
  29046. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  29047. return this;
  29048. };
  29049. /**
  29050. * Modifies the mesh geometry according to a displacementMap buffer.
  29051. * A displacement map is a colored image. Each pixel color value (actually a gradient computed from red, green, blue values) will give the displacement to apply to each mesh vertex.
  29052. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  29053. * This method returns nothing.
  29054. * The parameter `buffer` is a `Uint8Array` buffer containing series of `Uint8` lower than 255, the red, green, blue and alpha values of each successive pixel.
  29055. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  29056. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  29057. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  29058. * The parameter `uvScale` is an optional vector2 used to scale UV.
  29059. *
  29060. * Returns the Mesh.
  29061. */
  29062. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  29063. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  29064. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  29065. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  29066. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  29067. return this;
  29068. }
  29069. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29070. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  29071. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  29072. var position = BABYLON.Vector3.Zero();
  29073. var normal = BABYLON.Vector3.Zero();
  29074. var uv = BABYLON.Vector2.Zero();
  29075. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  29076. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  29077. for (var index = 0; index < positions.length; index += 3) {
  29078. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  29079. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  29080. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  29081. // Compute height
  29082. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  29083. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  29084. var pos = (u + v * heightMapWidth) * 4;
  29085. var r = buffer[pos] / 255.0;
  29086. var g = buffer[pos + 1] / 255.0;
  29087. var b = buffer[pos + 2] / 255.0;
  29088. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  29089. normal.normalize();
  29090. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  29091. position = position.add(normal);
  29092. position.toArray(positions, index);
  29093. }
  29094. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  29095. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  29096. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  29097. return this;
  29098. };
  29099. /**
  29100. * Modify the mesh to get a flat shading rendering.
  29101. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  29102. * This method returns the Mesh.
  29103. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  29104. */
  29105. Mesh.prototype.convertToFlatShadedMesh = function () {
  29106. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  29107. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  29108. var kinds = this.getVerticesDataKinds();
  29109. var vbs = {};
  29110. var data = {};
  29111. var newdata = {};
  29112. var updatableNormals = false;
  29113. var kindIndex;
  29114. var kind;
  29115. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29116. kind = kinds[kindIndex];
  29117. var vertexBuffer = this.getVertexBuffer(kind);
  29118. if (kind === BABYLON.VertexBuffer.NormalKind) {
  29119. updatableNormals = vertexBuffer.isUpdatable();
  29120. kinds.splice(kindIndex, 1);
  29121. kindIndex--;
  29122. continue;
  29123. }
  29124. vbs[kind] = vertexBuffer;
  29125. data[kind] = vbs[kind].getData();
  29126. newdata[kind] = [];
  29127. }
  29128. // Save previous submeshes
  29129. var previousSubmeshes = this.subMeshes.slice(0);
  29130. var indices = this.getIndices();
  29131. var totalIndices = this.getTotalIndices();
  29132. // Generating unique vertices per face
  29133. var index;
  29134. for (index = 0; index < totalIndices; index++) {
  29135. var vertexIndex = indices[index];
  29136. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29137. kind = kinds[kindIndex];
  29138. var stride = vbs[kind].getStrideSize();
  29139. for (var offset = 0; offset < stride; offset++) {
  29140. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  29141. }
  29142. }
  29143. }
  29144. // Updating faces & normal
  29145. var normals = [];
  29146. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  29147. for (index = 0; index < totalIndices; index += 3) {
  29148. indices[index] = index;
  29149. indices[index + 1] = index + 1;
  29150. indices[index + 2] = index + 2;
  29151. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  29152. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  29153. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  29154. var p1p2 = p1.subtract(p2);
  29155. var p3p2 = p3.subtract(p2);
  29156. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  29157. // Store same normals for every vertex
  29158. for (var localIndex = 0; localIndex < 3; localIndex++) {
  29159. normals.push(normal.x);
  29160. normals.push(normal.y);
  29161. normals.push(normal.z);
  29162. }
  29163. }
  29164. this.setIndices(indices);
  29165. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  29166. // Updating vertex buffers
  29167. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29168. kind = kinds[kindIndex];
  29169. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  29170. }
  29171. // Updating submeshes
  29172. this.releaseSubMeshes();
  29173. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  29174. var previousOne = previousSubmeshes[submeshIndex];
  29175. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  29176. }
  29177. this.synchronizeInstances();
  29178. return this;
  29179. };
  29180. /**
  29181. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  29182. * In other words, more vertices, no more indices and a single bigger VBO.
  29183. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  29184. * Returns the Mesh.
  29185. */
  29186. Mesh.prototype.convertToUnIndexedMesh = function () {
  29187. /// <summary>Remove indices by unfolding faces into buffers</summary>
  29188. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  29189. var kinds = this.getVerticesDataKinds();
  29190. var vbs = {};
  29191. var data = {};
  29192. var newdata = {};
  29193. var kindIndex;
  29194. var kind;
  29195. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29196. kind = kinds[kindIndex];
  29197. var vertexBuffer = this.getVertexBuffer(kind);
  29198. vbs[kind] = vertexBuffer;
  29199. data[kind] = vbs[kind].getData();
  29200. newdata[kind] = [];
  29201. }
  29202. // Save previous submeshes
  29203. var previousSubmeshes = this.subMeshes.slice(0);
  29204. var indices = this.getIndices();
  29205. var totalIndices = this.getTotalIndices();
  29206. // Generating unique vertices per face
  29207. var index;
  29208. for (index = 0; index < totalIndices; index++) {
  29209. var vertexIndex = indices[index];
  29210. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29211. kind = kinds[kindIndex];
  29212. var stride = vbs[kind].getStrideSize();
  29213. for (var offset = 0; offset < stride; offset++) {
  29214. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  29215. }
  29216. }
  29217. }
  29218. // Updating indices
  29219. for (index = 0; index < totalIndices; index += 3) {
  29220. indices[index] = index;
  29221. indices[index + 1] = index + 1;
  29222. indices[index + 2] = index + 2;
  29223. }
  29224. this.setIndices(indices);
  29225. // Updating vertex buffers
  29226. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29227. kind = kinds[kindIndex];
  29228. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  29229. }
  29230. // Updating submeshes
  29231. this.releaseSubMeshes();
  29232. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  29233. var previousOne = previousSubmeshes[submeshIndex];
  29234. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  29235. }
  29236. this._unIndexed = true;
  29237. this.synchronizeInstances();
  29238. return this;
  29239. };
  29240. /**
  29241. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  29242. * This method returns the Mesh.
  29243. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  29244. */
  29245. Mesh.prototype.flipFaces = function (flipNormals) {
  29246. if (flipNormals === void 0) { flipNormals = false; }
  29247. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  29248. var i;
  29249. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  29250. for (i = 0; i < vertex_data.normals.length; i++) {
  29251. vertex_data.normals[i] *= -1;
  29252. }
  29253. }
  29254. if (vertex_data.indices) {
  29255. var temp;
  29256. for (i = 0; i < vertex_data.indices.length; i += 3) {
  29257. // reassign indices
  29258. temp = vertex_data.indices[i + 1];
  29259. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  29260. vertex_data.indices[i + 2] = temp;
  29261. }
  29262. }
  29263. vertex_data.applyToMesh(this);
  29264. return this;
  29265. };
  29266. // Instances
  29267. /**
  29268. * Creates a new InstancedMesh object from the mesh model.
  29269. * An instance shares the same properties and the same material than its model.
  29270. * Only these properties of each instance can then be set individually :
  29271. * - position
  29272. * - rotation
  29273. * - rotationQuaternion
  29274. * - setPivotMatrix
  29275. * - scaling
  29276. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  29277. * Warning : this method is not supported for Line mesh and LineSystem
  29278. */
  29279. Mesh.prototype.createInstance = function (name) {
  29280. return new BABYLON.InstancedMesh(name, this);
  29281. };
  29282. /**
  29283. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  29284. * After this call, all the mesh instances have the same submeshes than the current mesh.
  29285. * This method returns the Mesh.
  29286. */
  29287. Mesh.prototype.synchronizeInstances = function () {
  29288. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  29289. var instance = this.instances[instanceIndex];
  29290. instance._syncSubMeshes();
  29291. }
  29292. return this;
  29293. };
  29294. /**
  29295. * Simplify the mesh according to the given array of settings.
  29296. * Function will return immediately and will simplify async. It returns the Mesh.
  29297. * @param settings a collection of simplification settings.
  29298. * @param parallelProcessing should all levels calculate parallel or one after the other.
  29299. * @param type the type of simplification to run.
  29300. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  29301. */
  29302. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  29303. if (parallelProcessing === void 0) { parallelProcessing = true; }
  29304. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  29305. this.getScene().simplificationQueue.addTask({
  29306. settings: settings,
  29307. parallelProcessing: parallelProcessing,
  29308. mesh: this,
  29309. simplificationType: simplificationType,
  29310. successCallback: successCallback
  29311. });
  29312. return this;
  29313. };
  29314. /**
  29315. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  29316. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  29317. * This should be used together with the simplification to avoid disappearing triangles.
  29318. * Returns the Mesh.
  29319. * @param successCallback an optional success callback to be called after the optimization finished.
  29320. */
  29321. Mesh.prototype.optimizeIndices = function (successCallback) {
  29322. var _this = this;
  29323. var indices = this.getIndices();
  29324. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29325. if (!positions || !indices) {
  29326. return this;
  29327. }
  29328. var vectorPositions = new Array();
  29329. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  29330. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  29331. }
  29332. var dupes = new Array();
  29333. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  29334. var realPos = vectorPositions.length - 1 - iteration;
  29335. var testedPosition = vectorPositions[realPos];
  29336. for (var j = 0; j < realPos; ++j) {
  29337. var againstPosition = vectorPositions[j];
  29338. if (testedPosition.equals(againstPosition)) {
  29339. dupes[realPos] = j;
  29340. break;
  29341. }
  29342. }
  29343. }, function () {
  29344. for (var i = 0; i < indices.length; ++i) {
  29345. indices[i] = dupes[indices[i]] || indices[i];
  29346. }
  29347. //indices are now reordered
  29348. var originalSubMeshes = _this.subMeshes.slice(0);
  29349. _this.setIndices(indices);
  29350. _this.subMeshes = originalSubMeshes;
  29351. if (successCallback) {
  29352. successCallback(_this);
  29353. }
  29354. });
  29355. return this;
  29356. };
  29357. Mesh.prototype.serialize = function (serializationObject) {
  29358. serializationObject.name = this.name;
  29359. serializationObject.id = this.id;
  29360. serializationObject.type = this.getClassName();
  29361. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  29362. serializationObject.tags = BABYLON.Tags.GetTags(this);
  29363. }
  29364. serializationObject.position = this.position.asArray();
  29365. if (this.rotationQuaternion) {
  29366. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  29367. }
  29368. else if (this.rotation) {
  29369. serializationObject.rotation = this.rotation.asArray();
  29370. }
  29371. serializationObject.scaling = this.scaling.asArray();
  29372. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  29373. serializationObject.isEnabled = this.isEnabled(false);
  29374. serializationObject.isVisible = this.isVisible;
  29375. serializationObject.infiniteDistance = this.infiniteDistance;
  29376. serializationObject.pickable = this.isPickable;
  29377. serializationObject.receiveShadows = this.receiveShadows;
  29378. serializationObject.billboardMode = this.billboardMode;
  29379. serializationObject.visibility = this.visibility;
  29380. serializationObject.checkCollisions = this.checkCollisions;
  29381. serializationObject.isBlocker = this.isBlocker;
  29382. // Parent
  29383. if (this.parent) {
  29384. serializationObject.parentId = this.parent.id;
  29385. }
  29386. // Geometry
  29387. serializationObject.isUnIndexed = this.isUnIndexed;
  29388. var geometry = this._geometry;
  29389. if (geometry) {
  29390. var geometryId = geometry.id;
  29391. serializationObject.geometryId = geometryId;
  29392. // SubMeshes
  29393. serializationObject.subMeshes = [];
  29394. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  29395. var subMesh = this.subMeshes[subIndex];
  29396. serializationObject.subMeshes.push({
  29397. materialIndex: subMesh.materialIndex,
  29398. verticesStart: subMesh.verticesStart,
  29399. verticesCount: subMesh.verticesCount,
  29400. indexStart: subMesh.indexStart,
  29401. indexCount: subMesh.indexCount
  29402. });
  29403. }
  29404. }
  29405. // Material
  29406. if (this.material) {
  29407. serializationObject.materialId = this.material.id;
  29408. }
  29409. else {
  29410. this.material = null;
  29411. }
  29412. // Morph targets
  29413. if (this.morphTargetManager) {
  29414. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  29415. }
  29416. // Skeleton
  29417. if (this.skeleton) {
  29418. serializationObject.skeletonId = this.skeleton.id;
  29419. }
  29420. // Physics
  29421. //TODO implement correct serialization for physics impostors.
  29422. var impostor = this.getPhysicsImpostor();
  29423. if (impostor) {
  29424. serializationObject.physicsMass = impostor.getParam("mass");
  29425. serializationObject.physicsFriction = impostor.getParam("friction");
  29426. serializationObject.physicsRestitution = impostor.getParam("mass");
  29427. serializationObject.physicsImpostor = impostor.type;
  29428. }
  29429. // Metadata
  29430. if (this.metadata) {
  29431. serializationObject.metadata = this.metadata;
  29432. }
  29433. // Instances
  29434. serializationObject.instances = [];
  29435. for (var index = 0; index < this.instances.length; index++) {
  29436. var instance = this.instances[index];
  29437. var serializationInstance = {
  29438. name: instance.name,
  29439. id: instance.id,
  29440. position: instance.position.asArray(),
  29441. scaling: instance.scaling.asArray()
  29442. };
  29443. if (instance.rotationQuaternion) {
  29444. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  29445. }
  29446. else if (instance.rotation) {
  29447. serializationInstance.rotation = instance.rotation.asArray();
  29448. }
  29449. serializationObject.instances.push(serializationInstance);
  29450. // Animations
  29451. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  29452. serializationInstance.ranges = instance.serializeAnimationRanges();
  29453. }
  29454. //
  29455. // Animations
  29456. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  29457. serializationObject.ranges = this.serializeAnimationRanges();
  29458. // Layer mask
  29459. serializationObject.layerMask = this.layerMask;
  29460. // Alpha
  29461. serializationObject.alphaIndex = this.alphaIndex;
  29462. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  29463. // Overlay
  29464. serializationObject.overlayAlpha = this.overlayAlpha;
  29465. serializationObject.overlayColor = this.overlayColor.asArray();
  29466. serializationObject.renderOverlay = this.renderOverlay;
  29467. // Fog
  29468. serializationObject.applyFog = this.applyFog;
  29469. // Action Manager
  29470. if (this.actionManager) {
  29471. serializationObject.actions = this.actionManager.serialize(this.name);
  29472. }
  29473. };
  29474. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  29475. if (!this.geometry) {
  29476. return;
  29477. }
  29478. this._markSubMeshesAsAttributesDirty();
  29479. var morphTargetManager = this._morphTargetManager;
  29480. if (morphTargetManager && morphTargetManager.vertexCount) {
  29481. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  29482. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  29483. this.morphTargetManager = null;
  29484. return;
  29485. }
  29486. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  29487. var morphTarget = morphTargetManager.getActiveTarget(index);
  29488. var positions = morphTarget.getPositions();
  29489. if (!positions) {
  29490. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  29491. return;
  29492. }
  29493. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  29494. var normals = morphTarget.getNormals();
  29495. if (normals) {
  29496. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  29497. }
  29498. var tangents = morphTarget.getTangents();
  29499. if (tangents) {
  29500. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  29501. }
  29502. }
  29503. }
  29504. else {
  29505. var index = 0;
  29506. // Positions
  29507. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  29508. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  29509. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  29510. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  29511. }
  29512. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  29513. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  29514. }
  29515. index++;
  29516. }
  29517. }
  29518. };
  29519. // Statics
  29520. /**
  29521. * Returns a new Mesh object parsed from the source provided.
  29522. * The parameter `parsedMesh` is the source.
  29523. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  29524. */
  29525. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  29526. var mesh;
  29527. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  29528. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  29529. }
  29530. else {
  29531. mesh = new Mesh(parsedMesh.name, scene);
  29532. }
  29533. mesh.id = parsedMesh.id;
  29534. if (BABYLON.Tags) {
  29535. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  29536. }
  29537. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  29538. if (parsedMesh.metadata !== undefined) {
  29539. mesh.metadata = parsedMesh.metadata;
  29540. }
  29541. if (parsedMesh.rotationQuaternion) {
  29542. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  29543. }
  29544. else if (parsedMesh.rotation) {
  29545. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  29546. }
  29547. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  29548. if (parsedMesh.localMatrix) {
  29549. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  29550. }
  29551. else if (parsedMesh.pivotMatrix) {
  29552. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  29553. }
  29554. mesh.setEnabled(parsedMesh.isEnabled);
  29555. mesh.isVisible = parsedMesh.isVisible;
  29556. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  29557. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  29558. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  29559. if (parsedMesh.applyFog !== undefined) {
  29560. mesh.applyFog = parsedMesh.applyFog;
  29561. }
  29562. if (parsedMesh.pickable !== undefined) {
  29563. mesh.isPickable = parsedMesh.pickable;
  29564. }
  29565. if (parsedMesh.alphaIndex !== undefined) {
  29566. mesh.alphaIndex = parsedMesh.alphaIndex;
  29567. }
  29568. mesh.receiveShadows = parsedMesh.receiveShadows;
  29569. mesh.billboardMode = parsedMesh.billboardMode;
  29570. if (parsedMesh.visibility !== undefined) {
  29571. mesh.visibility = parsedMesh.visibility;
  29572. }
  29573. mesh.checkCollisions = parsedMesh.checkCollisions;
  29574. if (parsedMesh.isBlocker !== undefined) {
  29575. mesh.isBlocker = parsedMesh.isBlocker;
  29576. }
  29577. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  29578. // freezeWorldMatrix
  29579. if (parsedMesh.freezeWorldMatrix) {
  29580. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  29581. }
  29582. // Parent
  29583. if (parsedMesh.parentId) {
  29584. mesh._waitingParentId = parsedMesh.parentId;
  29585. }
  29586. // Actions
  29587. if (parsedMesh.actions !== undefined) {
  29588. mesh._waitingActions = parsedMesh.actions;
  29589. }
  29590. // Overlay
  29591. if (parsedMesh.overlayAlpha !== undefined) {
  29592. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  29593. }
  29594. if (parsedMesh.overlayColor !== undefined) {
  29595. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  29596. }
  29597. if (parsedMesh.renderOverlay !== undefined) {
  29598. mesh.renderOverlay = parsedMesh.renderOverlay;
  29599. }
  29600. // Geometry
  29601. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  29602. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  29603. if (parsedMesh.delayLoadingFile) {
  29604. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  29605. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  29606. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  29607. if (parsedMesh._binaryInfo) {
  29608. mesh._binaryInfo = parsedMesh._binaryInfo;
  29609. }
  29610. mesh._delayInfo = [];
  29611. if (parsedMesh.hasUVs) {
  29612. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  29613. }
  29614. if (parsedMesh.hasUVs2) {
  29615. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  29616. }
  29617. if (parsedMesh.hasUVs3) {
  29618. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  29619. }
  29620. if (parsedMesh.hasUVs4) {
  29621. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  29622. }
  29623. if (parsedMesh.hasUVs5) {
  29624. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  29625. }
  29626. if (parsedMesh.hasUVs6) {
  29627. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  29628. }
  29629. if (parsedMesh.hasColors) {
  29630. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  29631. }
  29632. if (parsedMesh.hasMatricesIndices) {
  29633. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  29634. }
  29635. if (parsedMesh.hasMatricesWeights) {
  29636. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  29637. }
  29638. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  29639. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  29640. mesh._checkDelayState();
  29641. }
  29642. }
  29643. else {
  29644. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  29645. }
  29646. // Material
  29647. if (parsedMesh.materialId) {
  29648. mesh.setMaterialByID(parsedMesh.materialId);
  29649. }
  29650. else {
  29651. mesh.material = null;
  29652. }
  29653. // Morph targets
  29654. if (parsedMesh.morphTargetManagerId > -1) {
  29655. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  29656. }
  29657. // Skeleton
  29658. if (parsedMesh.skeletonId > -1) {
  29659. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  29660. if (parsedMesh.numBoneInfluencers) {
  29661. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  29662. }
  29663. }
  29664. // Animations
  29665. if (parsedMesh.animations) {
  29666. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  29667. var parsedAnimation = parsedMesh.animations[animationIndex];
  29668. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  29669. }
  29670. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  29671. }
  29672. if (parsedMesh.autoAnimate) {
  29673. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  29674. }
  29675. // Layer Mask
  29676. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  29677. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  29678. }
  29679. else {
  29680. mesh.layerMask = 0x0FFFFFFF;
  29681. }
  29682. // Physics
  29683. if (parsedMesh.physicsImpostor) {
  29684. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  29685. mass: parsedMesh.physicsMass,
  29686. friction: parsedMesh.physicsFriction,
  29687. restitution: parsedMesh.physicsRestitution
  29688. }, scene);
  29689. }
  29690. // Instances
  29691. if (parsedMesh.instances) {
  29692. for (var index = 0; index < parsedMesh.instances.length; index++) {
  29693. var parsedInstance = parsedMesh.instances[index];
  29694. var instance = mesh.createInstance(parsedInstance.name);
  29695. if (parsedInstance.id) {
  29696. instance.id = parsedInstance.id;
  29697. }
  29698. if (BABYLON.Tags) {
  29699. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  29700. }
  29701. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  29702. if (parsedInstance.parentId) {
  29703. instance._waitingParentId = parsedInstance.parentId;
  29704. }
  29705. if (parsedInstance.rotationQuaternion) {
  29706. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  29707. }
  29708. else if (parsedInstance.rotation) {
  29709. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  29710. }
  29711. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  29712. instance.checkCollisions = mesh.checkCollisions;
  29713. if (parsedMesh.animations) {
  29714. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  29715. parsedAnimation = parsedMesh.animations[animationIndex];
  29716. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  29717. }
  29718. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  29719. }
  29720. }
  29721. }
  29722. return mesh;
  29723. };
  29724. /**
  29725. * Creates a ribbon mesh.
  29726. * Please consider using the same method from the MeshBuilder class instead.
  29727. * The ribbon is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  29728. *
  29729. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  29730. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  29731. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  29732. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  29733. * The parameter `offset` (positive integer, default : rounded half size of the pathArray length), is taken in account only if the `pathArray` is containing a single path.
  29734. * It's the offset to join together the points from the same path. Ex : offset = 10 means the point 1 is joined to the point 11.
  29735. * The optional parameter `instance` is an instance of an existing Ribbon object to be updated with the passed `pathArray` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#ribbon
  29736. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29737. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29738. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29739. */
  29740. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  29741. if (closeArray === void 0) { closeArray = false; }
  29742. if (updatable === void 0) { updatable = false; }
  29743. return BABYLON.MeshBuilder.CreateRibbon(name, {
  29744. pathArray: pathArray,
  29745. closeArray: closeArray,
  29746. closePath: closePath,
  29747. offset: offset,
  29748. updatable: updatable,
  29749. sideOrientation: sideOrientation,
  29750. instance: instance
  29751. }, scene);
  29752. };
  29753. /**
  29754. * Creates a plane polygonal mesh. By default, this is a disc.
  29755. * Please consider using the same method from the MeshBuilder class instead.
  29756. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  29757. * The parameter `tessellation` sets the number of polygon sides (positive integer, default 64). So a tessellation valued to 3 will build a triangle, to 4 a square, etc.
  29758. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29759. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29760. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29761. */
  29762. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  29763. if (scene === void 0) { scene = null; }
  29764. var options = {
  29765. radius: radius,
  29766. tessellation: tessellation,
  29767. sideOrientation: sideOrientation,
  29768. updatable: updatable
  29769. };
  29770. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  29771. };
  29772. /**
  29773. * Creates a box mesh.
  29774. * Please consider using the same method from the MeshBuilder class instead.
  29775. * The parameter `size` sets the size (float) of each box side (default 1).
  29776. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29777. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29778. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29779. */
  29780. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  29781. if (scene === void 0) { scene = null; }
  29782. var options = {
  29783. size: size,
  29784. sideOrientation: sideOrientation,
  29785. updatable: updatable
  29786. };
  29787. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  29788. };
  29789. /**
  29790. * Creates a sphere mesh.
  29791. * Please consider using the same method from the MeshBuilder class instead.
  29792. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  29793. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  29794. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29795. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29796. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29797. */
  29798. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  29799. var options = {
  29800. segments: segments,
  29801. diameterX: diameter,
  29802. diameterY: diameter,
  29803. diameterZ: diameter,
  29804. sideOrientation: sideOrientation,
  29805. updatable: updatable
  29806. };
  29807. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  29808. };
  29809. /**
  29810. * Creates a cylinder or a cone mesh.
  29811. * Please consider using the same method from the MeshBuilder class instead.
  29812. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  29813. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  29814. * The parameters `diameterTop` and `diameterBottom` overwrite the parameter `diameter` and set respectively the top cap and bottom cap diameter (floats, default 1). The parameter "diameterBottom" can't be zero.
  29815. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  29816. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  29817. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29818. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29819. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29820. */
  29821. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  29822. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  29823. if (scene !== undefined) {
  29824. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  29825. updatable = scene;
  29826. }
  29827. scene = subdivisions;
  29828. subdivisions = 1;
  29829. }
  29830. var options = {
  29831. height: height,
  29832. diameterTop: diameterTop,
  29833. diameterBottom: diameterBottom,
  29834. tessellation: tessellation,
  29835. subdivisions: subdivisions,
  29836. sideOrientation: sideOrientation,
  29837. updatable: updatable
  29838. };
  29839. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  29840. };
  29841. // Torus (Code from SharpDX.org)
  29842. /**
  29843. * Creates a torus mesh.
  29844. * Please consider using the same method from the MeshBuilder class instead.
  29845. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  29846. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  29847. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  29848. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29849. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29850. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29851. */
  29852. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  29853. var options = {
  29854. diameter: diameter,
  29855. thickness: thickness,
  29856. tessellation: tessellation,
  29857. sideOrientation: sideOrientation,
  29858. updatable: updatable
  29859. };
  29860. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  29861. };
  29862. /**
  29863. * Creates a torus knot mesh.
  29864. * Please consider using the same method from the MeshBuilder class instead.
  29865. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  29866. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  29867. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  29868. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  29869. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29870. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29871. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29872. */
  29873. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  29874. var options = {
  29875. radius: radius,
  29876. tube: tube,
  29877. radialSegments: radialSegments,
  29878. tubularSegments: tubularSegments,
  29879. p: p,
  29880. q: q,
  29881. sideOrientation: sideOrientation,
  29882. updatable: updatable
  29883. };
  29884. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  29885. };
  29886. /**
  29887. * Creates a line mesh.
  29888. * Please consider using the same method from the MeshBuilder class instead.
  29889. * A line mesh is considered as a parametric shape since it has no predefined original shape. Its shape is determined by the passed array of points as an input parameter.
  29890. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  29891. * The parameter `points` is an array successive Vector3.
  29892. * The optional parameter `instance` is an instance of an existing LineMesh object to be updated with the passed `points` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#lines-and-dashedlines
  29893. * When updating an instance, remember that only point positions can change, not the number of points.
  29894. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29895. */
  29896. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  29897. if (scene === void 0) { scene = null; }
  29898. if (updatable === void 0) { updatable = false; }
  29899. if (instance === void 0) { instance = null; }
  29900. var options = {
  29901. points: points,
  29902. updatable: updatable,
  29903. instance: instance
  29904. };
  29905. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  29906. };
  29907. /**
  29908. * Creates a dashed line mesh.
  29909. * Please consider using the same method from the MeshBuilder class instead.
  29910. * A dashed line mesh is considered as a parametric shape since it has no predefined original shape. Its shape is determined by the passed array of points as an input parameter.
  29911. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  29912. * The parameter `points` is an array successive Vector3.
  29913. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  29914. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  29915. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  29916. * The optional parameter `instance` is an instance of an existing LineMesh object to be updated with the passed `points` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#lines-and-dashedlines
  29917. * When updating an instance, remember that only point positions can change, not the number of points.
  29918. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29919. */
  29920. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  29921. if (scene === void 0) { scene = null; }
  29922. var options = {
  29923. points: points,
  29924. dashSize: dashSize,
  29925. gapSize: gapSize,
  29926. dashNb: dashNb,
  29927. updatable: updatable,
  29928. instance: instance
  29929. };
  29930. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  29931. };
  29932. /**
  29933. * Creates a polygon mesh.
  29934. * Please consider using the same method from the MeshBuilder class instead.
  29935. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  29936. * The parameter `shape` is a required array of successive Vector3 representing the corners of the polygon in th XoZ plane, that is y = 0 for all vectors.
  29937. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29938. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29939. * Remember you can only change the shape positions, not their number when updating a polygon.
  29940. */
  29941. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  29942. var options = {
  29943. shape: shape,
  29944. holes: holes,
  29945. updatable: updatable,
  29946. sideOrientation: sideOrientation
  29947. };
  29948. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  29949. };
  29950. /**
  29951. * Creates an extruded polygon mesh, with depth in the Y direction.
  29952. * Please consider using the same method from the MeshBuilder class instead.
  29953. */
  29954. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  29955. var options = {
  29956. shape: shape,
  29957. holes: holes,
  29958. depth: depth,
  29959. updatable: updatable,
  29960. sideOrientation: sideOrientation
  29961. };
  29962. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  29963. };
  29964. /**
  29965. * Creates an extruded shape mesh.
  29966. * The extrusion is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  29967. * Please consider using the same method from the MeshBuilder class instead.
  29968. *
  29969. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  29970. * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be extruded in its local space : the shape must be designed in the xOy plane and will be
  29971. * extruded along the Z axis.
  29972. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  29973. * The parameter `rotation` (float, default 0 radians) is the angle value to rotate the shape each step (each path point), from the former step (so rotation added each step) along the curve.
  29974. * The parameter `scale` (float, default 1) is the value to scale the shape.
  29975. * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL
  29976. * The optional parameter `instance` is an instance of an existing ExtrudedShape object to be updated with the passed `shape`, `path`, `scale` or `rotation` parameters : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#extruded-shape
  29977. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  29978. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29979. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29980. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29981. */
  29982. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  29983. if (scene === void 0) { scene = null; }
  29984. var options = {
  29985. shape: shape,
  29986. path: path,
  29987. scale: scale,
  29988. rotation: rotation,
  29989. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  29990. sideOrientation: sideOrientation,
  29991. instance: instance,
  29992. updatable: updatable
  29993. };
  29994. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  29995. };
  29996. /**
  29997. * Creates an custom extruded shape mesh.
  29998. * The custom extrusion is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  29999. * Please consider using the same method from the MeshBuilder class instead.
  30000. *
  30001. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  30002. * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be extruded in its local space : the shape must be designed in the xOy plane and will be
  30003. * extruded along the Z axis.
  30004. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  30005. * The parameter `rotationFunction` (JS function) is a custom Javascript function called on each path point. This function is passed the position i of the point in the path
  30006. * and the distance of this point from the begining of the path :
  30007. * ```javascript
  30008. * var rotationFunction = function(i, distance) {
  30009. * // do things
  30010. * return rotationValue; }
  30011. * ```
  30012. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  30013. * The parameter `scaleFunction` (JS function) is a custom Javascript function called on each path point. This function is passed the position i of the point in the path
  30014. * and the distance of this point from the begining of the path :
  30015. * ```javascript
  30016. * var scaleFunction = function(i, distance) {
  30017. * // do things
  30018. * return scaleValue;}
  30019. * ```
  30020. * It must returns a float value that will be the scale value applied to the shape on each path point.
  30021. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  30022. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  30023. * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL
  30024. * The optional parameter `instance` is an instance of an existing ExtrudedShape object to be updated with the passed `shape`, `path`, `scale` or `rotation` parameters : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#extruded-shape
  30025. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  30026. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30027. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30028. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30029. */
  30030. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  30031. var options = {
  30032. shape: shape,
  30033. path: path,
  30034. scaleFunction: scaleFunction,
  30035. rotationFunction: rotationFunction,
  30036. ribbonCloseArray: ribbonCloseArray,
  30037. ribbonClosePath: ribbonClosePath,
  30038. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  30039. sideOrientation: sideOrientation,
  30040. instance: instance,
  30041. updatable: updatable
  30042. };
  30043. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  30044. };
  30045. /**
  30046. * Creates lathe mesh.
  30047. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  30048. * Please consider using the same method from the MeshBuilder class instead.
  30049. * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be rotated in its local space : the shape must be designed in the xOy plane and will be
  30050. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  30051. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  30052. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  30053. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30054. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30055. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30056. */
  30057. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  30058. var options = {
  30059. shape: shape,
  30060. radius: radius,
  30061. tessellation: tessellation,
  30062. sideOrientation: sideOrientation,
  30063. updatable: updatable
  30064. };
  30065. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  30066. };
  30067. /**
  30068. * Creates a plane mesh.
  30069. * Please consider using the same method from the MeshBuilder class instead.
  30070. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  30071. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30072. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30073. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30074. */
  30075. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  30076. var options = {
  30077. size: size,
  30078. width: size,
  30079. height: size,
  30080. sideOrientation: sideOrientation,
  30081. updatable: updatable
  30082. };
  30083. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  30084. };
  30085. /**
  30086. * Creates a ground mesh.
  30087. * Please consider using the same method from the MeshBuilder class instead.
  30088. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  30089. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  30090. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30091. */
  30092. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  30093. var options = {
  30094. width: width,
  30095. height: height,
  30096. subdivisions: subdivisions,
  30097. updatable: updatable
  30098. };
  30099. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  30100. };
  30101. /**
  30102. * Creates a tiled ground mesh.
  30103. * Please consider using the same method from the MeshBuilder class instead.
  30104. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  30105. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  30106. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  30107. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  30108. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  30109. * numbers of subdivisions on the ground width and height of each tile.
  30110. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30111. */
  30112. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  30113. var options = {
  30114. xmin: xmin,
  30115. zmin: zmin,
  30116. xmax: xmax,
  30117. zmax: zmax,
  30118. subdivisions: subdivisions,
  30119. precision: precision,
  30120. updatable: updatable
  30121. };
  30122. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  30123. };
  30124. /**
  30125. * Creates a ground mesh from a height map.
  30126. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  30127. * Please consider using the same method from the MeshBuilder class instead.
  30128. * The parameter `url` sets the URL of the height map image resource.
  30129. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  30130. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  30131. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  30132. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  30133. * The parameter `onReady` is a javascript callback function that will be called once the mesh is just built (the height map download can last some time).
  30134. * This function is passed the newly built mesh :
  30135. * ```javascript
  30136. * function(mesh) { // do things
  30137. * return; }
  30138. * ```
  30139. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30140. */
  30141. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  30142. var options = {
  30143. width: width,
  30144. height: height,
  30145. subdivisions: subdivisions,
  30146. minHeight: minHeight,
  30147. maxHeight: maxHeight,
  30148. updatable: updatable,
  30149. onReady: onReady
  30150. };
  30151. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  30152. };
  30153. /**
  30154. * Creates a tube mesh.
  30155. * The tube is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  30156. * Please consider using the same method from the MeshBuilder class instead.
  30157. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  30158. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  30159. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  30160. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  30161. * This function is called on each point of the tube path and is passed the index `i` of the i-th point and the distance of this point from the first point of the path.
  30162. * It must return a radius value (positive float) :
  30163. * ```javascript
  30164. * var radiusFunction = function(i, distance) {
  30165. * // do things
  30166. * return radius; }
  30167. * ```
  30168. * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL
  30169. * The optional parameter `instance` is an instance of an existing Tube object to be updated with the passed `pathArray` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#tube
  30170. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30171. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30172. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30173. */
  30174. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  30175. var options = {
  30176. path: path,
  30177. radius: radius,
  30178. tessellation: tessellation,
  30179. radiusFunction: radiusFunction,
  30180. arc: 1,
  30181. cap: cap,
  30182. updatable: updatable,
  30183. sideOrientation: sideOrientation,
  30184. instance: instance
  30185. };
  30186. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  30187. };
  30188. /**
  30189. * Creates a polyhedron mesh.
  30190. * Please consider using the same method from the MeshBuilder class instead.
  30191. * The parameter `type` (positive integer, max 14, default 0) sets the polyhedron type to build among the 15 embbeded types. Please refer to the type sheet in the tutorial
  30192. * to choose the wanted type.
  30193. * The parameter `size` (positive float, default 1) sets the polygon size.
  30194. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  30195. * You can build other polyhedron types than the 15 embbeded ones by setting the parameter `custom` (`polyhedronObject`, default null). If you set the parameter `custom`, this overwrittes the parameter `type`.
  30196. * A `polyhedronObject` is a formatted javascript object. You'll find a full file with pre-set polyhedra here : https://github.com/BabylonJS/Extensions/tree/master/Polyhedron
  30197. * You can set the color and the UV of each side of the polyhedron with the parameters `faceColors` (Color4, default `(1, 1, 1, 1)`) and faceUV (Vector4, default `(0, 0, 1, 1)`).
  30198. * To understand how to set `faceUV` or `faceColors`, please read this by considering the right number of faces of your polyhedron, instead of only 6 for the box : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  30199. * The parameter `flat` (boolean, default true). If set to false, it gives the polyhedron a single global face, so less vertices and shared normals. In this case, `faceColors` and `faceUV` are ignored.
  30200. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30201. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30202. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30203. */
  30204. Mesh.CreatePolyhedron = function (name, options, scene) {
  30205. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  30206. };
  30207. /**
  30208. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  30209. * Please consider using the same method from the MeshBuilder class instead.
  30210. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  30211. * You can set some different icosphere dimensions, for instance to build an ellipsoid, by using the parameters `radiusX`, `radiusY` and `radiusZ` (all by default have the same value than `radius`).
  30212. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  30213. * The parameter `flat` (boolean, default true) gives each side its own normals. Set it to false to get a smooth continuous light reflection on the surface.
  30214. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30215. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30216. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30217. */
  30218. Mesh.CreateIcoSphere = function (name, options, scene) {
  30219. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  30220. };
  30221. /**
  30222. * Creates a decal mesh.
  30223. * Please consider using the same method from the MeshBuilder class instead.
  30224. * A decal is a mesh usually applied as a model onto the surface of another mesh. So don't forget the parameter `sourceMesh` depicting the decal.
  30225. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  30226. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  30227. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  30228. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  30229. */
  30230. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  30231. var options = {
  30232. position: position,
  30233. normal: normal,
  30234. size: size,
  30235. angle: angle
  30236. };
  30237. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  30238. };
  30239. // Skeletons
  30240. /**
  30241. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  30242. */
  30243. Mesh.prototype.setPositionsForCPUSkinning = function () {
  30244. if (!this._sourcePositions) {
  30245. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30246. if (!source) {
  30247. return this._sourcePositions;
  30248. }
  30249. this._sourcePositions = new Float32Array(source);
  30250. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  30251. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  30252. }
  30253. }
  30254. return this._sourcePositions;
  30255. };
  30256. /**
  30257. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  30258. */
  30259. Mesh.prototype.setNormalsForCPUSkinning = function () {
  30260. if (!this._sourceNormals) {
  30261. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  30262. if (!source) {
  30263. return this._sourceNormals;
  30264. }
  30265. this._sourceNormals = new Float32Array(source);
  30266. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  30267. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  30268. }
  30269. }
  30270. return this._sourceNormals;
  30271. };
  30272. /**
  30273. * Updates the vertex buffer by applying transformation from the bones.
  30274. * Returns the Mesh.
  30275. *
  30276. * @param {skeleton} skeleton to apply
  30277. */
  30278. Mesh.prototype.applySkeleton = function (skeleton) {
  30279. if (!this.geometry) {
  30280. return this;
  30281. }
  30282. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  30283. return this;
  30284. }
  30285. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  30286. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  30287. return this;
  30288. }
  30289. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  30290. return this;
  30291. }
  30292. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  30293. return this;
  30294. }
  30295. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  30296. return this;
  30297. }
  30298. if (!this._sourcePositions) {
  30299. var submeshes = this.subMeshes.slice();
  30300. this.setPositionsForCPUSkinning();
  30301. this.subMeshes = submeshes;
  30302. }
  30303. if (!this._sourceNormals) {
  30304. this.setNormalsForCPUSkinning();
  30305. }
  30306. // positionsData checks for not being Float32Array will only pass at most once
  30307. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30308. if (!positionsData) {
  30309. return this;
  30310. }
  30311. if (!(positionsData instanceof Float32Array)) {
  30312. positionsData = new Float32Array(positionsData);
  30313. }
  30314. // normalsData checks for not being Float32Array will only pass at most once
  30315. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  30316. if (!normalsData) {
  30317. return this;
  30318. }
  30319. if (!(normalsData instanceof Float32Array)) {
  30320. normalsData = new Float32Array(normalsData);
  30321. }
  30322. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  30323. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  30324. if (!matricesWeightsData || !matricesIndicesData) {
  30325. return this;
  30326. }
  30327. var needExtras = this.numBoneInfluencers > 4;
  30328. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  30329. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  30330. var skeletonMatrices = skeleton.getTransformMatrices(this);
  30331. var tempVector3 = BABYLON.Vector3.Zero();
  30332. var finalMatrix = new BABYLON.Matrix();
  30333. var tempMatrix = new BABYLON.Matrix();
  30334. var matWeightIdx = 0;
  30335. var inf;
  30336. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  30337. var weight;
  30338. for (inf = 0; inf < 4; inf++) {
  30339. weight = matricesWeightsData[matWeightIdx + inf];
  30340. if (weight > 0) {
  30341. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  30342. finalMatrix.addToSelf(tempMatrix);
  30343. }
  30344. else
  30345. break;
  30346. }
  30347. if (needExtras) {
  30348. for (inf = 0; inf < 4; inf++) {
  30349. weight = matricesWeightsExtraData[matWeightIdx + inf];
  30350. if (weight > 0) {
  30351. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  30352. finalMatrix.addToSelf(tempMatrix);
  30353. }
  30354. else
  30355. break;
  30356. }
  30357. }
  30358. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  30359. tempVector3.toArray(positionsData, index);
  30360. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  30361. tempVector3.toArray(normalsData, index);
  30362. finalMatrix.reset();
  30363. }
  30364. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  30365. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  30366. return this;
  30367. };
  30368. // Tools
  30369. /**
  30370. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  30371. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  30372. */
  30373. Mesh.MinMax = function (meshes) {
  30374. var minVector = null;
  30375. var maxVector = null;
  30376. meshes.forEach(function (mesh, index, array) {
  30377. var boundingInfo = mesh.getBoundingInfo();
  30378. var boundingBox = boundingInfo.boundingBox;
  30379. if (!minVector || !maxVector) {
  30380. minVector = boundingBox.minimumWorld;
  30381. maxVector = boundingBox.maximumWorld;
  30382. }
  30383. else {
  30384. minVector.minimizeInPlace(boundingBox.minimumWorld);
  30385. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  30386. }
  30387. });
  30388. if (!minVector || !maxVector) {
  30389. return {
  30390. min: BABYLON.Vector3.Zero(),
  30391. max: BABYLON.Vector3.Zero()
  30392. };
  30393. }
  30394. return {
  30395. min: minVector,
  30396. max: maxVector
  30397. };
  30398. };
  30399. /**
  30400. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  30401. */
  30402. Mesh.Center = function (meshesOrMinMaxVector) {
  30403. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  30404. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  30405. };
  30406. /**
  30407. * Merge the array of meshes into a single mesh for performance reasons.
  30408. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  30409. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  30410. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  30411. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  30412. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  30413. */
  30414. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  30415. if (disposeSource === void 0) { disposeSource = true; }
  30416. var index;
  30417. if (!allow32BitsIndices) {
  30418. var totalVertices = 0;
  30419. // Counting vertices
  30420. for (index = 0; index < meshes.length; index++) {
  30421. if (meshes[index]) {
  30422. totalVertices += meshes[index].getTotalVertices();
  30423. if (totalVertices > 65536) {
  30424. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  30425. return null;
  30426. }
  30427. }
  30428. }
  30429. }
  30430. // Merge
  30431. var vertexData = null;
  30432. var otherVertexData;
  30433. var indiceArray = new Array();
  30434. var source = null;
  30435. for (index = 0; index < meshes.length; index++) {
  30436. if (meshes[index]) {
  30437. meshes[index].computeWorldMatrix(true);
  30438. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  30439. otherVertexData.transform(meshes[index].getWorldMatrix());
  30440. if (vertexData) {
  30441. vertexData.merge(otherVertexData);
  30442. }
  30443. else {
  30444. vertexData = otherVertexData;
  30445. source = meshes[index];
  30446. }
  30447. if (subdivideWithSubMeshes) {
  30448. indiceArray.push(meshes[index].getTotalIndices());
  30449. }
  30450. }
  30451. }
  30452. source = source;
  30453. if (!meshSubclass) {
  30454. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  30455. }
  30456. vertexData.applyToMesh(meshSubclass);
  30457. // Setting properties
  30458. meshSubclass.material = source.material;
  30459. meshSubclass.checkCollisions = source.checkCollisions;
  30460. // Cleaning
  30461. if (disposeSource) {
  30462. for (index = 0; index < meshes.length; index++) {
  30463. if (meshes[index]) {
  30464. meshes[index].dispose();
  30465. }
  30466. }
  30467. }
  30468. // Subdivide
  30469. if (subdivideWithSubMeshes) {
  30470. //-- Suppresions du submesh global
  30471. meshSubclass.releaseSubMeshes();
  30472. index = 0;
  30473. var offset = 0;
  30474. //-- aplique la subdivision en fonction du tableau d'indices
  30475. while (index < indiceArray.length) {
  30476. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  30477. offset += indiceArray[index];
  30478. index++;
  30479. }
  30480. }
  30481. return meshSubclass;
  30482. };
  30483. // Consts
  30484. Mesh._FRONTSIDE = 0;
  30485. Mesh._BACKSIDE = 1;
  30486. Mesh._DOUBLESIDE = 2;
  30487. Mesh._DEFAULTSIDE = 0;
  30488. Mesh._NO_CAP = 0;
  30489. Mesh._CAP_START = 1;
  30490. Mesh._CAP_END = 2;
  30491. Mesh._CAP_ALL = 3;
  30492. return Mesh;
  30493. }(BABYLON.AbstractMesh));
  30494. BABYLON.Mesh = Mesh;
  30495. })(BABYLON || (BABYLON = {}));
  30496. //# sourceMappingURL=babylon.mesh.js.map
  30497. var BABYLON;
  30498. (function (BABYLON) {
  30499. var BaseSubMesh = /** @class */ (function () {
  30500. function BaseSubMesh() {
  30501. }
  30502. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  30503. get: function () {
  30504. return this._materialEffect;
  30505. },
  30506. enumerable: true,
  30507. configurable: true
  30508. });
  30509. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  30510. if (defines === void 0) { defines = null; }
  30511. if (this._materialEffect === effect) {
  30512. if (!effect) {
  30513. this._materialDefines = null;
  30514. }
  30515. return;
  30516. }
  30517. this._materialDefines = defines;
  30518. this._materialEffect = effect;
  30519. };
  30520. return BaseSubMesh;
  30521. }());
  30522. BABYLON.BaseSubMesh = BaseSubMesh;
  30523. var SubMesh = /** @class */ (function (_super) {
  30524. __extends(SubMesh, _super);
  30525. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  30526. if (createBoundingBox === void 0) { createBoundingBox = true; }
  30527. var _this = _super.call(this) || this;
  30528. _this.materialIndex = materialIndex;
  30529. _this.verticesStart = verticesStart;
  30530. _this.verticesCount = verticesCount;
  30531. _this.indexStart = indexStart;
  30532. _this.indexCount = indexCount;
  30533. _this._renderId = 0;
  30534. _this._mesh = mesh;
  30535. _this._renderingMesh = renderingMesh || mesh;
  30536. mesh.subMeshes.push(_this);
  30537. _this._trianglePlanes = [];
  30538. _this._id = mesh.subMeshes.length - 1;
  30539. if (createBoundingBox) {
  30540. _this.refreshBoundingInfo();
  30541. mesh.computeWorldMatrix(true);
  30542. }
  30543. return _this;
  30544. }
  30545. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  30546. if (createBoundingBox === void 0) { createBoundingBox = true; }
  30547. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  30548. };
  30549. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  30550. get: function () {
  30551. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  30552. },
  30553. enumerable: true,
  30554. configurable: true
  30555. });
  30556. /**
  30557. * Returns the submesh BoudingInfo object.
  30558. */
  30559. SubMesh.prototype.getBoundingInfo = function () {
  30560. if (this.IsGlobal) {
  30561. return this._mesh.getBoundingInfo();
  30562. }
  30563. return this._boundingInfo;
  30564. };
  30565. /**
  30566. * Sets the submesh BoundingInfo.
  30567. * Return the SubMesh.
  30568. */
  30569. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  30570. this._boundingInfo = boundingInfo;
  30571. return this;
  30572. };
  30573. /**
  30574. * Returns the mesh of the current submesh.
  30575. */
  30576. SubMesh.prototype.getMesh = function () {
  30577. return this._mesh;
  30578. };
  30579. /**
  30580. * Returns the rendering mesh of the submesh.
  30581. */
  30582. SubMesh.prototype.getRenderingMesh = function () {
  30583. return this._renderingMesh;
  30584. };
  30585. /**
  30586. * Returns the submesh material.
  30587. */
  30588. SubMesh.prototype.getMaterial = function () {
  30589. var rootMaterial = this._renderingMesh.material;
  30590. if (rootMaterial === null || rootMaterial === undefined) {
  30591. return this._mesh.getScene().defaultMaterial;
  30592. }
  30593. else if (rootMaterial.getSubMaterial) {
  30594. var multiMaterial = rootMaterial;
  30595. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  30596. if (this._currentMaterial !== effectiveMaterial) {
  30597. this._currentMaterial = effectiveMaterial;
  30598. this._materialDefines = null;
  30599. }
  30600. return effectiveMaterial;
  30601. }
  30602. return rootMaterial;
  30603. };
  30604. // Methods
  30605. /**
  30606. * Sets a new updated BoundingInfo object to the submesh.
  30607. * Returns the SubMesh.
  30608. */
  30609. SubMesh.prototype.refreshBoundingInfo = function () {
  30610. this._lastColliderWorldVertices = null;
  30611. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  30612. return this;
  30613. }
  30614. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30615. if (!data) {
  30616. this._boundingInfo = this._mesh.getBoundingInfo();
  30617. return this;
  30618. }
  30619. var indices = this._renderingMesh.getIndices();
  30620. var extend;
  30621. //is this the only submesh?
  30622. if (this.indexStart === 0 && this.indexCount === indices.length) {
  30623. var boundingInfo = this._renderingMesh.getBoundingInfo();
  30624. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  30625. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  30626. }
  30627. else {
  30628. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  30629. }
  30630. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  30631. return this;
  30632. };
  30633. SubMesh.prototype._checkCollision = function (collider) {
  30634. var boundingInfo = this._renderingMesh.getBoundingInfo();
  30635. return boundingInfo._checkCollision(collider);
  30636. };
  30637. /**
  30638. * Updates the submesh BoundingInfo.
  30639. * Returns the Submesh.
  30640. */
  30641. SubMesh.prototype.updateBoundingInfo = function (world) {
  30642. var boundingInfo = this.getBoundingInfo();
  30643. if (!boundingInfo) {
  30644. this.refreshBoundingInfo();
  30645. boundingInfo = this.getBoundingInfo();
  30646. }
  30647. boundingInfo.update(world);
  30648. return this;
  30649. };
  30650. /**
  30651. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  30652. * Boolean returned.
  30653. */
  30654. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  30655. var boundingInfo = this.getBoundingInfo();
  30656. if (!boundingInfo) {
  30657. return false;
  30658. }
  30659. return boundingInfo.isInFrustum(frustumPlanes);
  30660. };
  30661. /**
  30662. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  30663. * Boolean returned.
  30664. */
  30665. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  30666. var boundingInfo = this.getBoundingInfo();
  30667. if (!boundingInfo) {
  30668. return false;
  30669. }
  30670. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  30671. };
  30672. /**
  30673. * Renders the submesh.
  30674. * Returns it.
  30675. */
  30676. SubMesh.prototype.render = function (enableAlphaMode) {
  30677. this._renderingMesh.render(this, enableAlphaMode);
  30678. return this;
  30679. };
  30680. /**
  30681. * Returns a new Index Buffer.
  30682. * Type returned : WebGLBuffer.
  30683. */
  30684. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  30685. if (!this._linesIndexBuffer) {
  30686. var linesIndices = [];
  30687. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  30688. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  30689. }
  30690. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  30691. this.linesIndexCount = linesIndices.length;
  30692. }
  30693. return this._linesIndexBuffer;
  30694. };
  30695. /**
  30696. * True is the passed Ray intersects the submesh bounding box.
  30697. * Boolean returned.
  30698. */
  30699. SubMesh.prototype.canIntersects = function (ray) {
  30700. var boundingInfo = this.getBoundingInfo();
  30701. if (!boundingInfo) {
  30702. return false;
  30703. }
  30704. return ray.intersectsBox(boundingInfo.boundingBox);
  30705. };
  30706. /**
  30707. * Returns an object IntersectionInfo.
  30708. */
  30709. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  30710. var intersectInfo = null;
  30711. // LineMesh first as it's also a Mesh...
  30712. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  30713. var lineMesh = this._mesh;
  30714. // Line test
  30715. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  30716. var p0 = positions[indices[index]];
  30717. var p1 = positions[indices[index + 1]];
  30718. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  30719. if (length < 0) {
  30720. continue;
  30721. }
  30722. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  30723. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  30724. if (fastCheck) {
  30725. break;
  30726. }
  30727. }
  30728. }
  30729. }
  30730. else {
  30731. // Triangles test
  30732. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  30733. var p0 = positions[indices[index]];
  30734. var p1 = positions[indices[index + 1]];
  30735. var p2 = positions[indices[index + 2]];
  30736. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  30737. if (currentIntersectInfo) {
  30738. if (currentIntersectInfo.distance < 0) {
  30739. continue;
  30740. }
  30741. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  30742. intersectInfo = currentIntersectInfo;
  30743. intersectInfo.faceId = index / 3;
  30744. if (fastCheck) {
  30745. break;
  30746. }
  30747. }
  30748. }
  30749. }
  30750. }
  30751. return intersectInfo;
  30752. };
  30753. SubMesh.prototype._rebuild = function () {
  30754. if (this._linesIndexBuffer) {
  30755. this._linesIndexBuffer = null;
  30756. }
  30757. };
  30758. // Clone
  30759. /**
  30760. * Creates a new Submesh from the passed Mesh.
  30761. */
  30762. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  30763. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  30764. if (!this.IsGlobal) {
  30765. var boundingInfo = this.getBoundingInfo();
  30766. if (!boundingInfo) {
  30767. return result;
  30768. }
  30769. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  30770. }
  30771. return result;
  30772. };
  30773. // Dispose
  30774. /**
  30775. * Disposes the Submesh.
  30776. * Returns nothing.
  30777. */
  30778. SubMesh.prototype.dispose = function () {
  30779. if (this._linesIndexBuffer) {
  30780. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  30781. this._linesIndexBuffer = null;
  30782. }
  30783. // Remove from mesh
  30784. var index = this._mesh.subMeshes.indexOf(this);
  30785. this._mesh.subMeshes.splice(index, 1);
  30786. };
  30787. // Statics
  30788. /**
  30789. * Creates a new Submesh from the passed parameters :
  30790. * - materialIndex (integer) : the index of the main mesh material.
  30791. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  30792. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  30793. * - mesh (Mesh) : the main mesh to create the submesh from.
  30794. * - renderingMesh (optional Mesh) : rendering mesh.
  30795. */
  30796. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  30797. var minVertexIndex = Number.MAX_VALUE;
  30798. var maxVertexIndex = -Number.MAX_VALUE;
  30799. renderingMesh = (renderingMesh || mesh);
  30800. var indices = renderingMesh.getIndices();
  30801. for (var index = startIndex; index < startIndex + indexCount; index++) {
  30802. var vertexIndex = indices[index];
  30803. if (vertexIndex < minVertexIndex)
  30804. minVertexIndex = vertexIndex;
  30805. if (vertexIndex > maxVertexIndex)
  30806. maxVertexIndex = vertexIndex;
  30807. }
  30808. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  30809. };
  30810. return SubMesh;
  30811. }(BaseSubMesh));
  30812. BABYLON.SubMesh = SubMesh;
  30813. })(BABYLON || (BABYLON = {}));
  30814. //# sourceMappingURL=babylon.subMesh.js.map
  30815. var __assign = (this && this.__assign) || Object.assign || function(t) {
  30816. for (var s, i = 1, n = arguments.length; i < n; i++) {
  30817. s = arguments[i];
  30818. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  30819. t[p] = s[p];
  30820. }
  30821. return t;
  30822. };
  30823. var BABYLON;
  30824. (function (BABYLON) {
  30825. /**
  30826. * Manages the defines for the Material.
  30827. */
  30828. var MaterialDefines = /** @class */ (function () {
  30829. function MaterialDefines() {
  30830. this._isDirty = true;
  30831. this._areLightsDirty = true;
  30832. this._areAttributesDirty = true;
  30833. this._areTexturesDirty = true;
  30834. this._areFresnelDirty = true;
  30835. this._areMiscDirty = true;
  30836. this._areImageProcessingDirty = true;
  30837. this._normals = false;
  30838. this._uvs = false;
  30839. this._needNormals = false;
  30840. this._needUVs = false;
  30841. }
  30842. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  30843. /**
  30844. * Specifies if the material needs to be re-calculated.
  30845. */
  30846. get: function () {
  30847. return this._isDirty;
  30848. },
  30849. enumerable: true,
  30850. configurable: true
  30851. });
  30852. /**
  30853. * Marks the material to indicate that it has been re-calculated.
  30854. */
  30855. MaterialDefines.prototype.markAsProcessed = function () {
  30856. this._isDirty = false;
  30857. this._areAttributesDirty = false;
  30858. this._areTexturesDirty = false;
  30859. this._areFresnelDirty = false;
  30860. this._areLightsDirty = false;
  30861. this._areMiscDirty = false;
  30862. this._areImageProcessingDirty = false;
  30863. };
  30864. /**
  30865. * Marks the material to indicate that it needs to be re-calculated.
  30866. */
  30867. MaterialDefines.prototype.markAsUnprocessed = function () {
  30868. this._isDirty = true;
  30869. };
  30870. /**
  30871. * Marks the material to indicate all of its defines need to be re-calculated.
  30872. */
  30873. MaterialDefines.prototype.markAllAsDirty = function () {
  30874. this._areTexturesDirty = true;
  30875. this._areAttributesDirty = true;
  30876. this._areLightsDirty = true;
  30877. this._areFresnelDirty = true;
  30878. this._areMiscDirty = true;
  30879. this._areImageProcessingDirty = true;
  30880. this._isDirty = true;
  30881. };
  30882. /**
  30883. * Marks the material to indicate that image processing needs to be re-calculated.
  30884. */
  30885. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  30886. this._areImageProcessingDirty = true;
  30887. this._isDirty = true;
  30888. };
  30889. /**
  30890. * Marks the material to indicate the lights need to be re-calculated.
  30891. */
  30892. MaterialDefines.prototype.markAsLightDirty = function () {
  30893. this._areLightsDirty = true;
  30894. this._isDirty = true;
  30895. };
  30896. /**
  30897. * Marks the attribute state as changed.
  30898. */
  30899. MaterialDefines.prototype.markAsAttributesDirty = function () {
  30900. this._areAttributesDirty = true;
  30901. this._isDirty = true;
  30902. };
  30903. /**
  30904. * Marks the texture state as changed.
  30905. */
  30906. MaterialDefines.prototype.markAsTexturesDirty = function () {
  30907. this._areTexturesDirty = true;
  30908. this._isDirty = true;
  30909. };
  30910. /**
  30911. * Marks the fresnel state as changed.
  30912. */
  30913. MaterialDefines.prototype.markAsFresnelDirty = function () {
  30914. this._areFresnelDirty = true;
  30915. this._isDirty = true;
  30916. };
  30917. /**
  30918. * Marks the misc state as changed.
  30919. */
  30920. MaterialDefines.prototype.markAsMiscDirty = function () {
  30921. this._areMiscDirty = true;
  30922. this._isDirty = true;
  30923. };
  30924. /**
  30925. * Rebuilds the material defines.
  30926. */
  30927. MaterialDefines.prototype.rebuild = function () {
  30928. if (this._keys) {
  30929. delete this._keys;
  30930. }
  30931. this._keys = [];
  30932. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  30933. var key = _a[_i];
  30934. if (key[0] === "_") {
  30935. continue;
  30936. }
  30937. this._keys.push(key);
  30938. }
  30939. };
  30940. /**
  30941. * Specifies if two material defines are equal.
  30942. * @param other - A material define instance to compare to.
  30943. * @returns - Boolean indicating if the material defines are equal (true) or not (false).
  30944. */
  30945. MaterialDefines.prototype.isEqual = function (other) {
  30946. if (this._keys.length !== other._keys.length) {
  30947. return false;
  30948. }
  30949. for (var index = 0; index < this._keys.length; index++) {
  30950. var prop = this._keys[index];
  30951. if (this[prop] !== other[prop]) {
  30952. return false;
  30953. }
  30954. }
  30955. return true;
  30956. };
  30957. /**
  30958. * Clones this instance's defines to another instance.
  30959. * @param other - material defines to clone values to.
  30960. */
  30961. MaterialDefines.prototype.cloneTo = function (other) {
  30962. if (this._keys.length !== other._keys.length) {
  30963. other._keys = this._keys.slice(0);
  30964. }
  30965. for (var index = 0; index < this._keys.length; index++) {
  30966. var prop = this._keys[index];
  30967. other[prop] = this[prop];
  30968. }
  30969. };
  30970. /**
  30971. * Resets the material define values.
  30972. */
  30973. MaterialDefines.prototype.reset = function () {
  30974. for (var index = 0; index < this._keys.length; index++) {
  30975. var prop = this._keys[index];
  30976. if (typeof (this[prop]) === "number") {
  30977. this[prop] = 0;
  30978. }
  30979. else {
  30980. this[prop] = false;
  30981. }
  30982. }
  30983. };
  30984. /**
  30985. * Converts the material define values to a string.
  30986. * @returns - String of material define information.
  30987. */
  30988. MaterialDefines.prototype.toString = function () {
  30989. var result = "";
  30990. for (var index = 0; index < this._keys.length; index++) {
  30991. var prop = this._keys[index];
  30992. var value = this[prop];
  30993. if (typeof (value) === "number") {
  30994. result += "#define " + prop + " " + this[prop] + "\n";
  30995. }
  30996. else if (value) {
  30997. result += "#define " + prop + "\n";
  30998. }
  30999. }
  31000. return result;
  31001. };
  31002. return MaterialDefines;
  31003. }());
  31004. BABYLON.MaterialDefines = MaterialDefines;
  31005. /**
  31006. * This offers the main features of a material in BJS.
  31007. */
  31008. var Material = /** @class */ (function () {
  31009. /**
  31010. * Creates a material instance.
  31011. * @param name - The name of the material.
  31012. * @param scene - The BJS scene to reference.
  31013. * @param doNotAdd - Specifies if the material should be added to the scene.
  31014. */
  31015. function Material(name, scene, doNotAdd) {
  31016. /**
  31017. * Specifies if the ready state should be checked on each call.
  31018. */
  31019. this.checkReadyOnEveryCall = false;
  31020. /**
  31021. * Specifies if the ready state should be checked once.
  31022. */
  31023. this.checkReadyOnlyOnce = false;
  31024. /**
  31025. * The state of the material.
  31026. */
  31027. this.state = "";
  31028. /**
  31029. * The alpha value of the material.
  31030. */
  31031. this._alpha = 1.0;
  31032. /**
  31033. * Specifies if back face culling is enabled.
  31034. */
  31035. this._backFaceCulling = true;
  31036. /**
  31037. * Specifies if the material should be serialized.
  31038. */
  31039. this.doNotSerialize = false;
  31040. /**
  31041. * Specifies if the effect should be stored on sub meshes.
  31042. */
  31043. this.storeEffectOnSubMeshes = false;
  31044. /**
  31045. * An event triggered when the material is disposed.
  31046. * @type {BABYLON.Observable}
  31047. */
  31048. this.onDisposeObservable = new BABYLON.Observable();
  31049. /**
  31050. * An event triggered when the material is bound.
  31051. * @type {BABYLON.Observable}
  31052. */
  31053. this.onBindObservable = new BABYLON.Observable();
  31054. /**
  31055. * An event triggered when the material is unbound.
  31056. * @type {BABYLON.Observable}
  31057. */
  31058. this.onUnBindObservable = new BABYLON.Observable();
  31059. /**
  31060. * Stores the value of the alpha mode.
  31061. */
  31062. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  31063. /**
  31064. * Stores the state of the need depth pre-pass value.
  31065. */
  31066. this._needDepthPrePass = false;
  31067. /**
  31068. * Specifies if depth writing should be disabled.
  31069. */
  31070. this.disableDepthWrite = false;
  31071. /**
  31072. * Specifies if depth writing should be forced.
  31073. */
  31074. this.forceDepthWrite = false;
  31075. /**
  31076. * Specifies if there should be a separate pass for culling.
  31077. */
  31078. this.separateCullingPass = false;
  31079. /**
  31080. * Stores the state specifing if fog should be enabled.
  31081. */
  31082. this._fogEnabled = true;
  31083. /**
  31084. * Stores the size of points.
  31085. */
  31086. this.pointSize = 1.0;
  31087. /**
  31088. * Stores the z offset value.
  31089. */
  31090. this.zOffset = 0;
  31091. /**
  31092. * Specifies if the material was previously ready.
  31093. */
  31094. this._wasPreviouslyReady = false;
  31095. /**
  31096. * Stores the fill mode state.
  31097. */
  31098. this._fillMode = Material.TriangleFillMode;
  31099. this.name = name;
  31100. this.id = name || BABYLON.Tools.RandomId();
  31101. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  31102. if (this._scene.useRightHandedSystem) {
  31103. this.sideOrientation = Material.ClockWiseSideOrientation;
  31104. }
  31105. else {
  31106. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  31107. }
  31108. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  31109. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  31110. if (!doNotAdd) {
  31111. this._scene.materials.push(this);
  31112. }
  31113. }
  31114. Object.defineProperty(Material, "TriangleFillMode", {
  31115. /**
  31116. * Returns the triangle fill mode.
  31117. */
  31118. get: function () {
  31119. return Material._TriangleFillMode;
  31120. },
  31121. enumerable: true,
  31122. configurable: true
  31123. });
  31124. Object.defineProperty(Material, "WireFrameFillMode", {
  31125. /**
  31126. * Returns the wireframe mode.
  31127. */
  31128. get: function () {
  31129. return Material._WireFrameFillMode;
  31130. },
  31131. enumerable: true,
  31132. configurable: true
  31133. });
  31134. Object.defineProperty(Material, "PointFillMode", {
  31135. /**
  31136. * Returns the point fill mode.
  31137. */
  31138. get: function () {
  31139. return Material._PointFillMode;
  31140. },
  31141. enumerable: true,
  31142. configurable: true
  31143. });
  31144. Object.defineProperty(Material, "PointListDrawMode", {
  31145. /**
  31146. * Returns the point list draw mode.
  31147. */
  31148. get: function () {
  31149. return Material._PointListDrawMode;
  31150. },
  31151. enumerable: true,
  31152. configurable: true
  31153. });
  31154. Object.defineProperty(Material, "LineListDrawMode", {
  31155. /**
  31156. * Returns the line list draw mode.
  31157. */
  31158. get: function () {
  31159. return Material._LineListDrawMode;
  31160. },
  31161. enumerable: true,
  31162. configurable: true
  31163. });
  31164. Object.defineProperty(Material, "LineLoopDrawMode", {
  31165. /**
  31166. * Returns the line loop draw mode.
  31167. */
  31168. get: function () {
  31169. return Material._LineLoopDrawMode;
  31170. },
  31171. enumerable: true,
  31172. configurable: true
  31173. });
  31174. Object.defineProperty(Material, "LineStripDrawMode", {
  31175. /**
  31176. * Returns the line strip draw mode.
  31177. */
  31178. get: function () {
  31179. return Material._LineStripDrawMode;
  31180. },
  31181. enumerable: true,
  31182. configurable: true
  31183. });
  31184. Object.defineProperty(Material, "TriangleStripDrawMode", {
  31185. /**
  31186. * Returns the triangle strip draw mode.
  31187. */
  31188. get: function () {
  31189. return Material._TriangleStripDrawMode;
  31190. },
  31191. enumerable: true,
  31192. configurable: true
  31193. });
  31194. Object.defineProperty(Material, "TriangleFanDrawMode", {
  31195. /**
  31196. * Returns the triangle fan draw mode.
  31197. */
  31198. get: function () {
  31199. return Material._TriangleFanDrawMode;
  31200. },
  31201. enumerable: true,
  31202. configurable: true
  31203. });
  31204. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  31205. /**
  31206. * Returns the clock-wise side orientation.
  31207. */
  31208. get: function () {
  31209. return Material._ClockWiseSideOrientation;
  31210. },
  31211. enumerable: true,
  31212. configurable: true
  31213. });
  31214. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  31215. /**
  31216. * Returns the counter clock-wise side orientation.
  31217. */
  31218. get: function () {
  31219. return Material._CounterClockWiseSideOrientation;
  31220. },
  31221. enumerable: true,
  31222. configurable: true
  31223. });
  31224. Object.defineProperty(Material, "TextureDirtyFlag", {
  31225. /**
  31226. * Returns the dirty texture flag value.
  31227. */
  31228. get: function () {
  31229. return Material._TextureDirtyFlag;
  31230. },
  31231. enumerable: true,
  31232. configurable: true
  31233. });
  31234. Object.defineProperty(Material, "LightDirtyFlag", {
  31235. /**
  31236. * Returns the dirty light flag value.
  31237. */
  31238. get: function () {
  31239. return Material._LightDirtyFlag;
  31240. },
  31241. enumerable: true,
  31242. configurable: true
  31243. });
  31244. Object.defineProperty(Material, "FresnelDirtyFlag", {
  31245. /**
  31246. * Returns the dirty fresnel flag value.
  31247. */
  31248. get: function () {
  31249. return Material._FresnelDirtyFlag;
  31250. },
  31251. enumerable: true,
  31252. configurable: true
  31253. });
  31254. Object.defineProperty(Material, "AttributesDirtyFlag", {
  31255. /**
  31256. * Returns the dirty attributes flag value.
  31257. */
  31258. get: function () {
  31259. return Material._AttributesDirtyFlag;
  31260. },
  31261. enumerable: true,
  31262. configurable: true
  31263. });
  31264. Object.defineProperty(Material, "MiscDirtyFlag", {
  31265. /**
  31266. * Returns the dirty misc flag value.
  31267. */
  31268. get: function () {
  31269. return Material._MiscDirtyFlag;
  31270. },
  31271. enumerable: true,
  31272. configurable: true
  31273. });
  31274. Object.defineProperty(Material.prototype, "alpha", {
  31275. /**
  31276. * Gets the alpha value of the material.
  31277. */
  31278. get: function () {
  31279. return this._alpha;
  31280. },
  31281. /**
  31282. * Sets the alpha value of the material.
  31283. */
  31284. set: function (value) {
  31285. if (this._alpha === value) {
  31286. return;
  31287. }
  31288. this._alpha = value;
  31289. this.markAsDirty(Material.MiscDirtyFlag);
  31290. },
  31291. enumerable: true,
  31292. configurable: true
  31293. });
  31294. Object.defineProperty(Material.prototype, "backFaceCulling", {
  31295. /**
  31296. * Gets the back-face culling state.
  31297. */
  31298. get: function () {
  31299. return this._backFaceCulling;
  31300. },
  31301. /**
  31302. * Sets the back-face culling state.
  31303. */
  31304. set: function (value) {
  31305. if (this._backFaceCulling === value) {
  31306. return;
  31307. }
  31308. this._backFaceCulling = value;
  31309. this.markAsDirty(Material.TextureDirtyFlag);
  31310. },
  31311. enumerable: true,
  31312. configurable: true
  31313. });
  31314. Object.defineProperty(Material.prototype, "onDispose", {
  31315. /**
  31316. * Called during a dispose event.
  31317. */
  31318. set: function (callback) {
  31319. if (this._onDisposeObserver) {
  31320. this.onDisposeObservable.remove(this._onDisposeObserver);
  31321. }
  31322. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  31323. },
  31324. enumerable: true,
  31325. configurable: true
  31326. });
  31327. Object.defineProperty(Material.prototype, "onBind", {
  31328. /**
  31329. * Called during a bind event.
  31330. */
  31331. set: function (callback) {
  31332. if (this._onBindObserver) {
  31333. this.onBindObservable.remove(this._onBindObserver);
  31334. }
  31335. this._onBindObserver = this.onBindObservable.add(callback);
  31336. },
  31337. enumerable: true,
  31338. configurable: true
  31339. });
  31340. Object.defineProperty(Material.prototype, "alphaMode", {
  31341. /**
  31342. * Gets the value of the alpha mode.
  31343. */
  31344. get: function () {
  31345. return this._alphaMode;
  31346. },
  31347. /**
  31348. * Sets the value of the alpha mode.
  31349. */
  31350. set: function (value) {
  31351. if (this._alphaMode === value) {
  31352. return;
  31353. }
  31354. this._alphaMode = value;
  31355. this.markAsDirty(Material.TextureDirtyFlag);
  31356. },
  31357. enumerable: true,
  31358. configurable: true
  31359. });
  31360. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  31361. /**
  31362. * Gets the depth pre-pass value.
  31363. */
  31364. get: function () {
  31365. return this._needDepthPrePass;
  31366. },
  31367. /**
  31368. * Sets the need depth pre-pass value.
  31369. */
  31370. set: function (value) {
  31371. if (this._needDepthPrePass === value) {
  31372. return;
  31373. }
  31374. this._needDepthPrePass = value;
  31375. if (this._needDepthPrePass) {
  31376. this.checkReadyOnEveryCall = true;
  31377. }
  31378. },
  31379. enumerable: true,
  31380. configurable: true
  31381. });
  31382. Object.defineProperty(Material.prototype, "fogEnabled", {
  31383. /**
  31384. * Gets the value of the fog enabled state.
  31385. */
  31386. get: function () {
  31387. return this._fogEnabled;
  31388. },
  31389. /**
  31390. * Sets the state for enabling fog.
  31391. */
  31392. set: function (value) {
  31393. if (this._fogEnabled === value) {
  31394. return;
  31395. }
  31396. this._fogEnabled = value;
  31397. this.markAsDirty(Material.MiscDirtyFlag);
  31398. },
  31399. enumerable: true,
  31400. configurable: true
  31401. });
  31402. Object.defineProperty(Material.prototype, "wireframe", {
  31403. /**
  31404. * Gets a value specifying if wireframe mode is enabled.
  31405. */
  31406. get: function () {
  31407. return this._fillMode === Material.WireFrameFillMode;
  31408. },
  31409. /**
  31410. * Sets the state of wireframe mode.
  31411. */
  31412. set: function (value) {
  31413. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  31414. },
  31415. enumerable: true,
  31416. configurable: true
  31417. });
  31418. Object.defineProperty(Material.prototype, "pointsCloud", {
  31419. /**
  31420. * Gets the value specifying if point clouds are enabled.
  31421. */
  31422. get: function () {
  31423. return this._fillMode === Material.PointFillMode;
  31424. },
  31425. /**
  31426. * Sets the state of point cloud mode.
  31427. */
  31428. set: function (value) {
  31429. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  31430. },
  31431. enumerable: true,
  31432. configurable: true
  31433. });
  31434. Object.defineProperty(Material.prototype, "fillMode", {
  31435. /**
  31436. * Gets the material fill mode.
  31437. */
  31438. get: function () {
  31439. return this._fillMode;
  31440. },
  31441. /**
  31442. * Sets the material fill mode.
  31443. */
  31444. set: function (value) {
  31445. if (this._fillMode === value) {
  31446. return;
  31447. }
  31448. this._fillMode = value;
  31449. this.markAsDirty(Material.MiscDirtyFlag);
  31450. },
  31451. enumerable: true,
  31452. configurable: true
  31453. });
  31454. /**
  31455. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  31456. * subclasses should override adding information pertainent to themselves.
  31457. * @returns - String with material information.
  31458. */
  31459. Material.prototype.toString = function (fullDetails) {
  31460. var ret = "Name: " + this.name;
  31461. if (fullDetails) {
  31462. }
  31463. return ret;
  31464. };
  31465. /**
  31466. * Gets the class name of the material.
  31467. * @returns - String with the class name of the material.
  31468. */
  31469. Material.prototype.getClassName = function () {
  31470. return "Material";
  31471. };
  31472. Object.defineProperty(Material.prototype, "isFrozen", {
  31473. /**
  31474. * Specifies if updates for the material been locked.
  31475. */
  31476. get: function () {
  31477. return this.checkReadyOnlyOnce;
  31478. },
  31479. enumerable: true,
  31480. configurable: true
  31481. });
  31482. /**
  31483. * Locks updates for the material.
  31484. */
  31485. Material.prototype.freeze = function () {
  31486. this.checkReadyOnlyOnce = true;
  31487. };
  31488. /**
  31489. * Unlocks updates for the material.
  31490. */
  31491. Material.prototype.unfreeze = function () {
  31492. this.checkReadyOnlyOnce = false;
  31493. };
  31494. /**
  31495. * Specifies if the material is ready to be used.
  31496. * @param mesh - BJS mesh.
  31497. * @param useInstances - Specifies if instances should be used.
  31498. * @returns - Boolean indicating if the material is ready to be used.
  31499. */
  31500. Material.prototype.isReady = function (mesh, useInstances) {
  31501. return true;
  31502. };
  31503. /**
  31504. * Specifies that the submesh is ready to be used.
  31505. * @param mesh - BJS mesh.
  31506. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  31507. * @param useInstances - Specifies that instances should be used.
  31508. * @returns - boolean indicating that the submesh is ready or not.
  31509. */
  31510. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  31511. return false;
  31512. };
  31513. /**
  31514. * Returns the material effect.
  31515. * @returns - Nullable material effect.
  31516. */
  31517. Material.prototype.getEffect = function () {
  31518. return this._effect;
  31519. };
  31520. /**
  31521. * Returns the BJS scene.
  31522. * @returns - BJS Scene.
  31523. */
  31524. Material.prototype.getScene = function () {
  31525. return this._scene;
  31526. };
  31527. /**
  31528. * Specifies if the material will require alpha blending
  31529. * @returns - Boolean specifying if alpha blending is needed.
  31530. */
  31531. Material.prototype.needAlphaBlending = function () {
  31532. return (this.alpha < 1.0);
  31533. };
  31534. /**
  31535. * Specifies if the mesh will require alpha blending.
  31536. * @param mesh - BJS mesh.
  31537. * @returns - Boolean specifying if alpha blending is needed for the mesh.
  31538. */
  31539. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  31540. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  31541. };
  31542. /**
  31543. * Specifies if this material should be rendered in alpha test mode.
  31544. * @returns - Boolean specifying if an alpha test is needed.
  31545. */
  31546. Material.prototype.needAlphaTesting = function () {
  31547. return false;
  31548. };
  31549. /**
  31550. * Gets the texture used for the alpha test.
  31551. * @returns - Nullable alpha test texture.
  31552. */
  31553. Material.prototype.getAlphaTestTexture = function () {
  31554. return null;
  31555. };
  31556. /**
  31557. * Marks the material to indicate that it needs to be re-calculated.
  31558. */
  31559. Material.prototype.markDirty = function () {
  31560. this._wasPreviouslyReady = false;
  31561. };
  31562. Material.prototype._preBind = function (effect, overrideOrientation) {
  31563. if (overrideOrientation === void 0) { overrideOrientation = null; }
  31564. var engine = this._scene.getEngine();
  31565. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  31566. var reverse = orientation === Material.ClockWiseSideOrientation;
  31567. engine.enableEffect(effect ? effect : this._effect);
  31568. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  31569. return reverse;
  31570. };
  31571. /**
  31572. * Binds the material to the mesh.
  31573. * @param world - World transformation matrix.
  31574. * @param mesh - Mesh to bind the material to.
  31575. */
  31576. Material.prototype.bind = function (world, mesh) {
  31577. };
  31578. /**
  31579. * Binds the submesh to the material.
  31580. * @param world - World transformation matrix.
  31581. * @param mesh - Mesh containing the submesh.
  31582. * @param subMesh - Submesh to bind the material to.
  31583. */
  31584. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  31585. };
  31586. /**
  31587. * Binds the world matrix to the material.
  31588. * @param world - World transformation matrix.
  31589. */
  31590. Material.prototype.bindOnlyWorldMatrix = function (world) {
  31591. };
  31592. /**
  31593. * Binds the scene's uniform buffer to the effect.
  31594. * @param effect - Effect to bind to the scene uniform buffer.
  31595. * @param sceneUbo - Scene uniform buffer.
  31596. */
  31597. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  31598. sceneUbo.bindToEffect(effect, "Scene");
  31599. };
  31600. /**
  31601. * Binds the view matrix to the effect.
  31602. * @param effect - Effect to bind the view matrix to.
  31603. */
  31604. Material.prototype.bindView = function (effect) {
  31605. if (!this._useUBO) {
  31606. effect.setMatrix("view", this.getScene().getViewMatrix());
  31607. }
  31608. else {
  31609. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  31610. }
  31611. };
  31612. /**
  31613. * Binds the view projection matrix to the effect.
  31614. * @param effect - Effect to bind the view projection matrix to.
  31615. */
  31616. Material.prototype.bindViewProjection = function (effect) {
  31617. if (!this._useUBO) {
  31618. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  31619. }
  31620. else {
  31621. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  31622. }
  31623. };
  31624. /**
  31625. * Specifies if material alpha testing should be turned on for the mesh.
  31626. * @param mesh - BJS mesh.
  31627. */
  31628. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  31629. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  31630. };
  31631. /**
  31632. * Processes to execute after binding the material to a mesh.
  31633. * @param mesh - BJS mesh.
  31634. */
  31635. Material.prototype._afterBind = function (mesh) {
  31636. this._scene._cachedMaterial = this;
  31637. if (mesh) {
  31638. this._scene._cachedVisibility = mesh.visibility;
  31639. }
  31640. else {
  31641. this._scene._cachedVisibility = 1;
  31642. }
  31643. if (mesh) {
  31644. this.onBindObservable.notifyObservers(mesh);
  31645. }
  31646. if (this.disableDepthWrite) {
  31647. var engine = this._scene.getEngine();
  31648. this._cachedDepthWriteState = engine.getDepthWrite();
  31649. engine.setDepthWrite(false);
  31650. }
  31651. };
  31652. /**
  31653. * Unbinds the material from the mesh.
  31654. */
  31655. Material.prototype.unbind = function () {
  31656. this.onUnBindObservable.notifyObservers(this);
  31657. if (this.disableDepthWrite) {
  31658. var engine = this._scene.getEngine();
  31659. engine.setDepthWrite(this._cachedDepthWriteState);
  31660. }
  31661. };
  31662. /**
  31663. * Gets the active textures from the material.
  31664. * @returns - Array of textures.
  31665. */
  31666. Material.prototype.getActiveTextures = function () {
  31667. return [];
  31668. };
  31669. /**
  31670. * Specifies if the material uses a texture.
  31671. * @param texture - Texture to check against the material.
  31672. * @returns - Boolean specifying if the material uses the texture.
  31673. */
  31674. Material.prototype.hasTexture = function (texture) {
  31675. return false;
  31676. };
  31677. /**
  31678. * Makes a duplicate of the material, and gives it a new name.
  31679. * @param name - Name to call the duplicated material.
  31680. * @returns - Nullable cloned material
  31681. */
  31682. Material.prototype.clone = function (name) {
  31683. return null;
  31684. };
  31685. /**
  31686. * Gets the meshes bound to the material.
  31687. * @returns - Array of meshes bound to the material.
  31688. */
  31689. Material.prototype.getBindedMeshes = function () {
  31690. var result = new Array();
  31691. for (var index = 0; index < this._scene.meshes.length; index++) {
  31692. var mesh = this._scene.meshes[index];
  31693. if (mesh.material === this) {
  31694. result.push(mesh);
  31695. }
  31696. }
  31697. return result;
  31698. };
  31699. /**
  31700. * Force shader compilation
  31701. * @param mesh - BJS mesh.
  31702. * @param onCompiled - function to execute once the material is compiled.
  31703. * @param options - options to pass to this function.
  31704. */
  31705. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  31706. var _this = this;
  31707. var localOptions = __assign({ clipPlane: false }, options);
  31708. var subMesh = new BABYLON.BaseSubMesh();
  31709. var scene = this.getScene();
  31710. var checkReady = function () {
  31711. if (!_this._scene || !_this._scene.getEngine()) {
  31712. return;
  31713. }
  31714. if (subMesh._materialDefines) {
  31715. subMesh._materialDefines._renderId = -1;
  31716. }
  31717. var clipPlaneState = scene.clipPlane;
  31718. if (localOptions.clipPlane) {
  31719. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  31720. }
  31721. if (_this.storeEffectOnSubMeshes) {
  31722. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  31723. if (onCompiled) {
  31724. onCompiled(_this);
  31725. }
  31726. }
  31727. else {
  31728. setTimeout(checkReady, 16);
  31729. }
  31730. }
  31731. else {
  31732. if (_this.isReady(mesh)) {
  31733. if (onCompiled) {
  31734. onCompiled(_this);
  31735. }
  31736. }
  31737. else {
  31738. setTimeout(checkReady, 16);
  31739. }
  31740. }
  31741. if (localOptions.clipPlane) {
  31742. scene.clipPlane = clipPlaneState;
  31743. }
  31744. };
  31745. checkReady();
  31746. };
  31747. /**
  31748. * Force shader compilation.
  31749. * @param mesh The mesh that will use this material
  31750. * @param options Additional options for compiling the shaders
  31751. * @returns A promise that resolves when the compilation completes
  31752. */
  31753. Material.prototype.forceCompilationAsync = function (mesh, options) {
  31754. var _this = this;
  31755. return new Promise(function (resolve) {
  31756. _this.forceCompilation(mesh, function () {
  31757. resolve();
  31758. }, options);
  31759. });
  31760. };
  31761. /**
  31762. * Marks a define in the material to indicate that it needs to be re-computed.
  31763. * @param flag - Material define flag.
  31764. */
  31765. Material.prototype.markAsDirty = function (flag) {
  31766. if (flag & Material.TextureDirtyFlag) {
  31767. this._markAllSubMeshesAsTexturesDirty();
  31768. }
  31769. if (flag & Material.LightDirtyFlag) {
  31770. this._markAllSubMeshesAsLightsDirty();
  31771. }
  31772. if (flag & Material.FresnelDirtyFlag) {
  31773. this._markAllSubMeshesAsFresnelDirty();
  31774. }
  31775. if (flag & Material.AttributesDirtyFlag) {
  31776. this._markAllSubMeshesAsAttributesDirty();
  31777. }
  31778. if (flag & Material.MiscDirtyFlag) {
  31779. this._markAllSubMeshesAsMiscDirty();
  31780. }
  31781. this.getScene().resetCachedMaterial();
  31782. };
  31783. /**
  31784. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated.
  31785. * @param func - function which checks material defines against the submeshes.
  31786. */
  31787. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  31788. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  31789. var mesh = _a[_i];
  31790. if (!mesh.subMeshes) {
  31791. continue;
  31792. }
  31793. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  31794. var subMesh = _c[_b];
  31795. if (subMesh.getMaterial() !== this) {
  31796. continue;
  31797. }
  31798. if (!subMesh._materialDefines) {
  31799. continue;
  31800. }
  31801. func(subMesh._materialDefines);
  31802. }
  31803. }
  31804. };
  31805. /**
  31806. * Indicates that image processing needs to be re-calculated for all submeshes.
  31807. */
  31808. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  31809. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  31810. };
  31811. /**
  31812. * Indicates that textures need to be re-calculated for all submeshes.
  31813. */
  31814. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  31815. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  31816. };
  31817. /**
  31818. * Indicates that fresnel needs to be re-calculated for all submeshes.
  31819. */
  31820. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  31821. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  31822. };
  31823. /**
  31824. * Indicates that fresnel and misc need to be re-calculated for all submeshes.
  31825. */
  31826. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  31827. this._markAllSubMeshesAsDirty(function (defines) {
  31828. defines.markAsFresnelDirty();
  31829. defines.markAsMiscDirty();
  31830. });
  31831. };
  31832. /**
  31833. * Indicates that lights need to be re-calculated for all submeshes.
  31834. */
  31835. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  31836. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  31837. };
  31838. /**
  31839. * Indicates that attributes need to be re-calculated for all submeshes.
  31840. */
  31841. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  31842. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  31843. };
  31844. /**
  31845. * Indicates that misc needs to be re-calculated for all submeshes.
  31846. */
  31847. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  31848. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  31849. };
  31850. /**
  31851. * Indicates that textures and misc need to be re-calculated for all submeshes.
  31852. */
  31853. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  31854. this._markAllSubMeshesAsDirty(function (defines) {
  31855. defines.markAsTexturesDirty();
  31856. defines.markAsMiscDirty();
  31857. });
  31858. };
  31859. /**
  31860. * Disposes the material.
  31861. * @param forceDisposeEffect - Specifies if effects should be force disposed.
  31862. * @param forceDisposeTextures - Specifies if textures should be force disposed.
  31863. */
  31864. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  31865. // Animations
  31866. this.getScene().stopAnimation(this);
  31867. this.getScene().freeProcessedMaterials();
  31868. // Remove from scene
  31869. var index = this._scene.materials.indexOf(this);
  31870. if (index >= 0) {
  31871. this._scene.materials.splice(index, 1);
  31872. }
  31873. // Remove from meshes
  31874. for (index = 0; index < this._scene.meshes.length; index++) {
  31875. var mesh = this._scene.meshes[index];
  31876. if (mesh.material === this) {
  31877. mesh.material = null;
  31878. if (mesh.geometry) {
  31879. var geometry = (mesh.geometry);
  31880. if (this.storeEffectOnSubMeshes) {
  31881. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  31882. var subMesh = _a[_i];
  31883. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  31884. if (forceDisposeEffect && subMesh._materialEffect) {
  31885. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  31886. }
  31887. }
  31888. }
  31889. else {
  31890. geometry._releaseVertexArrayObject(this._effect);
  31891. }
  31892. }
  31893. }
  31894. }
  31895. this._uniformBuffer.dispose();
  31896. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  31897. if (forceDisposeEffect && this._effect) {
  31898. if (!this.storeEffectOnSubMeshes) {
  31899. this._scene.getEngine()._releaseEffect(this._effect);
  31900. }
  31901. this._effect = null;
  31902. }
  31903. // Callback
  31904. this.onDisposeObservable.notifyObservers(this);
  31905. this.onDisposeObservable.clear();
  31906. this.onBindObservable.clear();
  31907. this.onUnBindObservable.clear();
  31908. };
  31909. /**
  31910. * Serializes this material.
  31911. * @returns - serialized material object.
  31912. */
  31913. Material.prototype.serialize = function () {
  31914. return BABYLON.SerializationHelper.Serialize(this);
  31915. };
  31916. /**
  31917. * Creates a MultiMaterial from parse MultiMaterial data.
  31918. * @param parsedMultiMaterial - Parsed MultiMaterial data.
  31919. * @param scene - BJS scene.
  31920. * @returns - MultiMaterial.
  31921. */
  31922. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  31923. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  31924. multiMaterial.id = parsedMultiMaterial.id;
  31925. if (BABYLON.Tags) {
  31926. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  31927. }
  31928. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  31929. var subMatId = parsedMultiMaterial.materials[matIndex];
  31930. if (subMatId) {
  31931. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  31932. }
  31933. else {
  31934. multiMaterial.subMaterials.push(null);
  31935. }
  31936. }
  31937. return multiMaterial;
  31938. };
  31939. /**
  31940. * Creates a material from parsed material data.
  31941. * @param parsedMaterial - Parsed material data.
  31942. * @param scene - BJS scene.
  31943. * @param rootUrl - Root URL containing the material information.
  31944. * @returns - Parsed material.
  31945. */
  31946. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  31947. if (!parsedMaterial.customType) {
  31948. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  31949. }
  31950. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  31951. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  31952. if (!BABYLON.LegacyPBRMaterial) {
  31953. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  31954. return;
  31955. }
  31956. }
  31957. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  31958. return materialType.Parse(parsedMaterial, scene, rootUrl);
  31959. ;
  31960. };
  31961. // Triangle views
  31962. Material._TriangleFillMode = 0;
  31963. Material._WireFrameFillMode = 1;
  31964. Material._PointFillMode = 2;
  31965. // Draw modes
  31966. Material._PointListDrawMode = 3;
  31967. Material._LineListDrawMode = 4;
  31968. Material._LineLoopDrawMode = 5;
  31969. Material._LineStripDrawMode = 6;
  31970. Material._TriangleStripDrawMode = 7;
  31971. Material._TriangleFanDrawMode = 8;
  31972. /**
  31973. * Stores the clock-wise side orientation.
  31974. */
  31975. Material._ClockWiseSideOrientation = 0;
  31976. /**
  31977. * Stores the counter clock-wise side orientation.
  31978. */
  31979. Material._CounterClockWiseSideOrientation = 1;
  31980. /**
  31981. * The dirty texture flag value.
  31982. */
  31983. Material._TextureDirtyFlag = 1;
  31984. /**
  31985. * The dirty light flag value.
  31986. */
  31987. Material._LightDirtyFlag = 2;
  31988. /**
  31989. * The dirty fresnel flag value.
  31990. */
  31991. Material._FresnelDirtyFlag = 4;
  31992. /**
  31993. * The dirty attribute flag value.
  31994. */
  31995. Material._AttributesDirtyFlag = 8;
  31996. /**
  31997. * The dirty misc flag value.
  31998. */
  31999. Material._MiscDirtyFlag = 16;
  32000. __decorate([
  32001. BABYLON.serialize()
  32002. ], Material.prototype, "id", void 0);
  32003. __decorate([
  32004. BABYLON.serialize()
  32005. ], Material.prototype, "name", void 0);
  32006. __decorate([
  32007. BABYLON.serialize()
  32008. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  32009. __decorate([
  32010. BABYLON.serialize()
  32011. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  32012. __decorate([
  32013. BABYLON.serialize()
  32014. ], Material.prototype, "state", void 0);
  32015. __decorate([
  32016. BABYLON.serialize("alpha")
  32017. ], Material.prototype, "_alpha", void 0);
  32018. __decorate([
  32019. BABYLON.serialize("backFaceCulling")
  32020. ], Material.prototype, "_backFaceCulling", void 0);
  32021. __decorate([
  32022. BABYLON.serialize()
  32023. ], Material.prototype, "sideOrientation", void 0);
  32024. __decorate([
  32025. BABYLON.serialize("alphaMode")
  32026. ], Material.prototype, "_alphaMode", void 0);
  32027. __decorate([
  32028. BABYLON.serialize()
  32029. ], Material.prototype, "_needDepthPrePass", void 0);
  32030. __decorate([
  32031. BABYLON.serialize()
  32032. ], Material.prototype, "disableDepthWrite", void 0);
  32033. __decorate([
  32034. BABYLON.serialize()
  32035. ], Material.prototype, "forceDepthWrite", void 0);
  32036. __decorate([
  32037. BABYLON.serialize()
  32038. ], Material.prototype, "separateCullingPass", void 0);
  32039. __decorate([
  32040. BABYLON.serialize("fogEnabled")
  32041. ], Material.prototype, "_fogEnabled", void 0);
  32042. __decorate([
  32043. BABYLON.serialize()
  32044. ], Material.prototype, "pointSize", void 0);
  32045. __decorate([
  32046. BABYLON.serialize()
  32047. ], Material.prototype, "zOffset", void 0);
  32048. __decorate([
  32049. BABYLON.serialize()
  32050. ], Material.prototype, "wireframe", null);
  32051. __decorate([
  32052. BABYLON.serialize()
  32053. ], Material.prototype, "pointsCloud", null);
  32054. __decorate([
  32055. BABYLON.serialize()
  32056. ], Material.prototype, "fillMode", null);
  32057. return Material;
  32058. }());
  32059. BABYLON.Material = Material;
  32060. })(BABYLON || (BABYLON = {}));
  32061. //# sourceMappingURL=babylon.material.js.map
  32062. var BABYLON;
  32063. (function (BABYLON) {
  32064. var UniformBuffer = /** @class */ (function () {
  32065. /**
  32066. * Uniform buffer objects.
  32067. *
  32068. * Handles blocks of uniform on the GPU.
  32069. *
  32070. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  32071. *
  32072. * For more information, please refer to :
  32073. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  32074. */
  32075. function UniformBuffer(engine, data, dynamic) {
  32076. this._engine = engine;
  32077. this._noUBO = !engine.supportsUniformBuffers;
  32078. this._dynamic = dynamic;
  32079. this._data = data || [];
  32080. this._uniformLocations = {};
  32081. this._uniformSizes = {};
  32082. this._uniformLocationPointer = 0;
  32083. this._needSync = false;
  32084. if (this._noUBO) {
  32085. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  32086. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  32087. this.updateFloat = this._updateFloatForEffect;
  32088. this.updateFloat2 = this._updateFloat2ForEffect;
  32089. this.updateFloat3 = this._updateFloat3ForEffect;
  32090. this.updateFloat4 = this._updateFloat4ForEffect;
  32091. this.updateMatrix = this._updateMatrixForEffect;
  32092. this.updateVector3 = this._updateVector3ForEffect;
  32093. this.updateVector4 = this._updateVector4ForEffect;
  32094. this.updateColor3 = this._updateColor3ForEffect;
  32095. this.updateColor4 = this._updateColor4ForEffect;
  32096. }
  32097. else {
  32098. this._engine._uniformBuffers.push(this);
  32099. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  32100. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  32101. this.updateFloat = this._updateFloatForUniform;
  32102. this.updateFloat2 = this._updateFloat2ForUniform;
  32103. this.updateFloat3 = this._updateFloat3ForUniform;
  32104. this.updateFloat4 = this._updateFloat4ForUniform;
  32105. this.updateMatrix = this._updateMatrixForUniform;
  32106. this.updateVector3 = this._updateVector3ForUniform;
  32107. this.updateVector4 = this._updateVector4ForUniform;
  32108. this.updateColor3 = this._updateColor3ForUniform;
  32109. this.updateColor4 = this._updateColor4ForUniform;
  32110. }
  32111. }
  32112. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  32113. // Properties
  32114. /**
  32115. * Indicates if the buffer is using the WebGL2 UBO implementation,
  32116. * or just falling back on setUniformXXX calls.
  32117. */
  32118. get: function () {
  32119. return !this._noUBO;
  32120. },
  32121. enumerable: true,
  32122. configurable: true
  32123. });
  32124. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  32125. /**
  32126. * Indicates if the WebGL underlying uniform buffer is in sync
  32127. * with the javascript cache data.
  32128. */
  32129. get: function () {
  32130. return !this._needSync;
  32131. },
  32132. enumerable: true,
  32133. configurable: true
  32134. });
  32135. /**
  32136. * Indicates if the WebGL underlying uniform buffer is dynamic.
  32137. * Also, a dynamic UniformBuffer will disable cache verification and always
  32138. * update the underlying WebGL uniform buffer to the GPU.
  32139. */
  32140. UniformBuffer.prototype.isDynamic = function () {
  32141. return this._dynamic !== undefined;
  32142. };
  32143. /**
  32144. * The data cache on JS side.
  32145. */
  32146. UniformBuffer.prototype.getData = function () {
  32147. return this._bufferData;
  32148. };
  32149. /**
  32150. * The underlying WebGL Uniform buffer.
  32151. */
  32152. UniformBuffer.prototype.getBuffer = function () {
  32153. return this._buffer;
  32154. };
  32155. /**
  32156. * std140 layout specifies how to align data within an UBO structure.
  32157. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  32158. * for specs.
  32159. */
  32160. UniformBuffer.prototype._fillAlignment = function (size) {
  32161. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  32162. // and 4x4 matrices
  32163. // TODO : change if other types are used
  32164. var alignment;
  32165. if (size <= 2) {
  32166. alignment = size;
  32167. }
  32168. else {
  32169. alignment = 4;
  32170. }
  32171. if ((this._uniformLocationPointer % alignment) !== 0) {
  32172. var oldPointer = this._uniformLocationPointer;
  32173. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  32174. var diff = this._uniformLocationPointer - oldPointer;
  32175. for (var i = 0; i < diff; i++) {
  32176. this._data.push(0);
  32177. }
  32178. }
  32179. };
  32180. /**
  32181. * Adds an uniform in the buffer.
  32182. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  32183. * for the layout to be correct !
  32184. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32185. * @param {number|number[]} size Data size, or data directly.
  32186. */
  32187. UniformBuffer.prototype.addUniform = function (name, size) {
  32188. if (this._noUBO) {
  32189. return;
  32190. }
  32191. if (this._uniformLocations[name] !== undefined) {
  32192. // Already existing uniform
  32193. return;
  32194. }
  32195. // This function must be called in the order of the shader layout !
  32196. // size can be the size of the uniform, or data directly
  32197. var data;
  32198. if (size instanceof Array) {
  32199. data = size;
  32200. size = data.length;
  32201. }
  32202. else {
  32203. size = size;
  32204. data = [];
  32205. // Fill with zeros
  32206. for (var i = 0; i < size; i++) {
  32207. data.push(0);
  32208. }
  32209. }
  32210. this._fillAlignment(size);
  32211. this._uniformSizes[name] = size;
  32212. this._uniformLocations[name] = this._uniformLocationPointer;
  32213. this._uniformLocationPointer += size;
  32214. for (var i = 0; i < size; i++) {
  32215. this._data.push(data[i]);
  32216. }
  32217. this._needSync = true;
  32218. };
  32219. /**
  32220. * Wrapper for addUniform.
  32221. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32222. * @param {Matrix} mat A 4x4 matrix.
  32223. */
  32224. UniformBuffer.prototype.addMatrix = function (name, mat) {
  32225. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  32226. };
  32227. /**
  32228. * Wrapper for addUniform.
  32229. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32230. * @param {number} x
  32231. * @param {number} y
  32232. */
  32233. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  32234. var temp = [x, y];
  32235. this.addUniform(name, temp);
  32236. };
  32237. /**
  32238. * Wrapper for addUniform.
  32239. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32240. * @param {number} x
  32241. * @param {number} y
  32242. * @param {number} z
  32243. */
  32244. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  32245. var temp = [x, y, z];
  32246. this.addUniform(name, temp);
  32247. };
  32248. /**
  32249. * Wrapper for addUniform.
  32250. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32251. * @param {Color3} color
  32252. */
  32253. UniformBuffer.prototype.addColor3 = function (name, color) {
  32254. var temp = new Array();
  32255. color.toArray(temp);
  32256. this.addUniform(name, temp);
  32257. };
  32258. /**
  32259. * Wrapper for addUniform.
  32260. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32261. * @param {Color3} color
  32262. * @param {number} alpha
  32263. */
  32264. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  32265. var temp = new Array();
  32266. color.toArray(temp);
  32267. temp.push(alpha);
  32268. this.addUniform(name, temp);
  32269. };
  32270. /**
  32271. * Wrapper for addUniform.
  32272. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32273. * @param {Vector3} vector
  32274. */
  32275. UniformBuffer.prototype.addVector3 = function (name, vector) {
  32276. var temp = new Array();
  32277. vector.toArray(temp);
  32278. this.addUniform(name, temp);
  32279. };
  32280. /**
  32281. * Wrapper for addUniform.
  32282. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32283. */
  32284. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  32285. this.addUniform(name, 12);
  32286. };
  32287. /**
  32288. * Wrapper for addUniform.
  32289. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32290. */
  32291. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  32292. this.addUniform(name, 8);
  32293. };
  32294. /**
  32295. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  32296. */
  32297. UniformBuffer.prototype.create = function () {
  32298. if (this._noUBO) {
  32299. return;
  32300. }
  32301. if (this._buffer) {
  32302. return; // nothing to do
  32303. }
  32304. // See spec, alignment must be filled as a vec4
  32305. this._fillAlignment(4);
  32306. this._bufferData = new Float32Array(this._data);
  32307. this._rebuild();
  32308. this._needSync = true;
  32309. };
  32310. UniformBuffer.prototype._rebuild = function () {
  32311. if (this._noUBO) {
  32312. return;
  32313. }
  32314. if (this._dynamic) {
  32315. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  32316. }
  32317. else {
  32318. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  32319. }
  32320. };
  32321. /**
  32322. * Updates the WebGL Uniform Buffer on the GPU.
  32323. * If the `dynamic` flag is set to true, no cache comparison is done.
  32324. * Otherwise, the buffer will be updated only if the cache differs.
  32325. */
  32326. UniformBuffer.prototype.update = function () {
  32327. if (!this._buffer) {
  32328. this.create();
  32329. return;
  32330. }
  32331. if (!this._dynamic && !this._needSync) {
  32332. return;
  32333. }
  32334. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  32335. this._needSync = false;
  32336. };
  32337. /**
  32338. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  32339. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  32340. * @param {number[]|Float32Array} data Flattened data
  32341. * @param {number} size Size of the data.
  32342. */
  32343. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  32344. var location = this._uniformLocations[uniformName];
  32345. if (location === undefined) {
  32346. if (this._buffer) {
  32347. // Cannot add an uniform if the buffer is already created
  32348. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  32349. return;
  32350. }
  32351. this.addUniform(uniformName, size);
  32352. location = this._uniformLocations[uniformName];
  32353. }
  32354. if (!this._buffer) {
  32355. this.create();
  32356. }
  32357. if (!this._dynamic) {
  32358. // Cache for static uniform buffers
  32359. var changed = false;
  32360. for (var i = 0; i < size; i++) {
  32361. if (this._bufferData[location + i] !== data[i]) {
  32362. changed = true;
  32363. this._bufferData[location + i] = data[i];
  32364. }
  32365. }
  32366. this._needSync = this._needSync || changed;
  32367. }
  32368. else {
  32369. // No cache for dynamic
  32370. for (var i = 0; i < size; i++) {
  32371. this._bufferData[location + i] = data[i];
  32372. }
  32373. }
  32374. };
  32375. // Update methods
  32376. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  32377. // To match std140, matrix must be realigned
  32378. for (var i = 0; i < 3; i++) {
  32379. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  32380. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  32381. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  32382. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  32383. }
  32384. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  32385. };
  32386. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  32387. this._currentEffect.setMatrix3x3(name, matrix);
  32388. };
  32389. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  32390. this._currentEffect.setMatrix2x2(name, matrix);
  32391. };
  32392. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  32393. // To match std140, matrix must be realigned
  32394. for (var i = 0; i < 2; i++) {
  32395. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  32396. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  32397. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  32398. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  32399. }
  32400. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  32401. };
  32402. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  32403. this._currentEffect.setFloat(name, x);
  32404. };
  32405. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  32406. UniformBuffer._tempBuffer[0] = x;
  32407. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  32408. };
  32409. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  32410. if (suffix === void 0) { suffix = ""; }
  32411. this._currentEffect.setFloat2(name + suffix, x, y);
  32412. };
  32413. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  32414. if (suffix === void 0) { suffix = ""; }
  32415. UniformBuffer._tempBuffer[0] = x;
  32416. UniformBuffer._tempBuffer[1] = y;
  32417. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  32418. };
  32419. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  32420. if (suffix === void 0) { suffix = ""; }
  32421. this._currentEffect.setFloat3(name + suffix, x, y, z);
  32422. };
  32423. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  32424. if (suffix === void 0) { suffix = ""; }
  32425. UniformBuffer._tempBuffer[0] = x;
  32426. UniformBuffer._tempBuffer[1] = y;
  32427. UniformBuffer._tempBuffer[2] = z;
  32428. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  32429. };
  32430. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  32431. if (suffix === void 0) { suffix = ""; }
  32432. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  32433. };
  32434. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  32435. if (suffix === void 0) { suffix = ""; }
  32436. UniformBuffer._tempBuffer[0] = x;
  32437. UniformBuffer._tempBuffer[1] = y;
  32438. UniformBuffer._tempBuffer[2] = z;
  32439. UniformBuffer._tempBuffer[3] = w;
  32440. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  32441. };
  32442. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  32443. this._currentEffect.setMatrix(name, mat);
  32444. };
  32445. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  32446. this.updateUniform(name, mat.toArray(), 16);
  32447. };
  32448. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  32449. this._currentEffect.setVector3(name, vector);
  32450. };
  32451. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  32452. vector.toArray(UniformBuffer._tempBuffer);
  32453. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  32454. };
  32455. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  32456. this._currentEffect.setVector4(name, vector);
  32457. };
  32458. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  32459. vector.toArray(UniformBuffer._tempBuffer);
  32460. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  32461. };
  32462. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  32463. if (suffix === void 0) { suffix = ""; }
  32464. this._currentEffect.setColor3(name + suffix, color);
  32465. };
  32466. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  32467. if (suffix === void 0) { suffix = ""; }
  32468. color.toArray(UniformBuffer._tempBuffer);
  32469. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  32470. };
  32471. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  32472. if (suffix === void 0) { suffix = ""; }
  32473. this._currentEffect.setColor4(name + suffix, color, alpha);
  32474. };
  32475. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  32476. if (suffix === void 0) { suffix = ""; }
  32477. color.toArray(UniformBuffer._tempBuffer);
  32478. UniformBuffer._tempBuffer[3] = alpha;
  32479. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  32480. };
  32481. /**
  32482. * Sets a sampler uniform on the effect.
  32483. * @param {string} name Name of the sampler.
  32484. * @param {Texture} texture
  32485. */
  32486. UniformBuffer.prototype.setTexture = function (name, texture) {
  32487. this._currentEffect.setTexture(name, texture);
  32488. };
  32489. /**
  32490. * Directly updates the value of the uniform in the cache AND on the GPU.
  32491. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  32492. * @param {number[]|Float32Array} data Flattened data
  32493. */
  32494. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  32495. this.updateUniform(uniformName, data, data.length);
  32496. this.update();
  32497. };
  32498. /**
  32499. * Binds this uniform buffer to an effect.
  32500. * @param {Effect} effect
  32501. * @param {string} name Name of the uniform block in the shader.
  32502. */
  32503. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  32504. this._currentEffect = effect;
  32505. if (this._noUBO || !this._buffer) {
  32506. return;
  32507. }
  32508. effect.bindUniformBuffer(this._buffer, name);
  32509. };
  32510. /**
  32511. * Disposes the uniform buffer.
  32512. */
  32513. UniformBuffer.prototype.dispose = function () {
  32514. if (this._noUBO) {
  32515. return;
  32516. }
  32517. var index = this._engine._uniformBuffers.indexOf(this);
  32518. if (index !== -1) {
  32519. this._engine._uniformBuffers.splice(index, 1);
  32520. }
  32521. if (!this._buffer) {
  32522. return;
  32523. }
  32524. if (this._engine._releaseBuffer(this._buffer)) {
  32525. this._buffer = null;
  32526. }
  32527. };
  32528. // Pool for avoiding memory leaks
  32529. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  32530. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  32531. return UniformBuffer;
  32532. }());
  32533. BABYLON.UniformBuffer = UniformBuffer;
  32534. })(BABYLON || (BABYLON = {}));
  32535. //# sourceMappingURL=babylon.uniformBuffer.js.map
  32536. var BABYLON;
  32537. (function (BABYLON) {
  32538. var VertexData = /** @class */ (function () {
  32539. function VertexData() {
  32540. }
  32541. VertexData.prototype.set = function (data, kind) {
  32542. switch (kind) {
  32543. case BABYLON.VertexBuffer.PositionKind:
  32544. this.positions = data;
  32545. break;
  32546. case BABYLON.VertexBuffer.NormalKind:
  32547. this.normals = data;
  32548. break;
  32549. case BABYLON.VertexBuffer.TangentKind:
  32550. this.tangents = data;
  32551. break;
  32552. case BABYLON.VertexBuffer.UVKind:
  32553. this.uvs = data;
  32554. break;
  32555. case BABYLON.VertexBuffer.UV2Kind:
  32556. this.uvs2 = data;
  32557. break;
  32558. case BABYLON.VertexBuffer.UV3Kind:
  32559. this.uvs3 = data;
  32560. break;
  32561. case BABYLON.VertexBuffer.UV4Kind:
  32562. this.uvs4 = data;
  32563. break;
  32564. case BABYLON.VertexBuffer.UV5Kind:
  32565. this.uvs5 = data;
  32566. break;
  32567. case BABYLON.VertexBuffer.UV6Kind:
  32568. this.uvs6 = data;
  32569. break;
  32570. case BABYLON.VertexBuffer.ColorKind:
  32571. this.colors = data;
  32572. break;
  32573. case BABYLON.VertexBuffer.MatricesIndicesKind:
  32574. this.matricesIndices = data;
  32575. break;
  32576. case BABYLON.VertexBuffer.MatricesWeightsKind:
  32577. this.matricesWeights = data;
  32578. break;
  32579. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  32580. this.matricesIndicesExtra = data;
  32581. break;
  32582. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  32583. this.matricesWeightsExtra = data;
  32584. break;
  32585. }
  32586. };
  32587. /**
  32588. * Associates the vertexData to the passed Mesh.
  32589. * Sets it as updatable or not (default `false`).
  32590. * Returns the VertexData.
  32591. */
  32592. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  32593. this._applyTo(mesh, updatable);
  32594. return this;
  32595. };
  32596. /**
  32597. * Associates the vertexData to the passed Geometry.
  32598. * Sets it as updatable or not (default `false`).
  32599. * Returns the VertexData.
  32600. */
  32601. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  32602. this._applyTo(geometry, updatable);
  32603. return this;
  32604. };
  32605. /**
  32606. * Updates the associated mesh.
  32607. * Returns the VertexData.
  32608. */
  32609. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  32610. this._update(mesh);
  32611. return this;
  32612. };
  32613. /**
  32614. * Updates the associated geometry.
  32615. * Returns the VertexData.
  32616. */
  32617. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  32618. this._update(geometry);
  32619. return this;
  32620. };
  32621. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  32622. if (updatable === void 0) { updatable = false; }
  32623. if (this.positions) {
  32624. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  32625. }
  32626. if (this.normals) {
  32627. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  32628. }
  32629. if (this.tangents) {
  32630. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  32631. }
  32632. if (this.uvs) {
  32633. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  32634. }
  32635. if (this.uvs2) {
  32636. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  32637. }
  32638. if (this.uvs3) {
  32639. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  32640. }
  32641. if (this.uvs4) {
  32642. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  32643. }
  32644. if (this.uvs5) {
  32645. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  32646. }
  32647. if (this.uvs6) {
  32648. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  32649. }
  32650. if (this.colors) {
  32651. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  32652. }
  32653. if (this.matricesIndices) {
  32654. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  32655. }
  32656. if (this.matricesWeights) {
  32657. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  32658. }
  32659. if (this.matricesIndicesExtra) {
  32660. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  32661. }
  32662. if (this.matricesWeightsExtra) {
  32663. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  32664. }
  32665. if (this.indices) {
  32666. meshOrGeometry.setIndices(this.indices, null, updatable);
  32667. }
  32668. return this;
  32669. };
  32670. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  32671. if (this.positions) {
  32672. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  32673. }
  32674. if (this.normals) {
  32675. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  32676. }
  32677. if (this.tangents) {
  32678. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  32679. }
  32680. if (this.uvs) {
  32681. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  32682. }
  32683. if (this.uvs2) {
  32684. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  32685. }
  32686. if (this.uvs3) {
  32687. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  32688. }
  32689. if (this.uvs4) {
  32690. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  32691. }
  32692. if (this.uvs5) {
  32693. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  32694. }
  32695. if (this.uvs6) {
  32696. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  32697. }
  32698. if (this.colors) {
  32699. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  32700. }
  32701. if (this.matricesIndices) {
  32702. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  32703. }
  32704. if (this.matricesWeights) {
  32705. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  32706. }
  32707. if (this.matricesIndicesExtra) {
  32708. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  32709. }
  32710. if (this.matricesWeightsExtra) {
  32711. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  32712. }
  32713. if (this.indices) {
  32714. meshOrGeometry.setIndices(this.indices, null);
  32715. }
  32716. return this;
  32717. };
  32718. /**
  32719. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  32720. * Returns the VertexData.
  32721. */
  32722. VertexData.prototype.transform = function (matrix) {
  32723. var transformed = BABYLON.Vector3.Zero();
  32724. var index;
  32725. if (this.positions) {
  32726. var position = BABYLON.Vector3.Zero();
  32727. for (index = 0; index < this.positions.length; index += 3) {
  32728. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  32729. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  32730. this.positions[index] = transformed.x;
  32731. this.positions[index + 1] = transformed.y;
  32732. this.positions[index + 2] = transformed.z;
  32733. }
  32734. }
  32735. if (this.normals) {
  32736. var normal = BABYLON.Vector3.Zero();
  32737. for (index = 0; index < this.normals.length; index += 3) {
  32738. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  32739. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  32740. this.normals[index] = transformed.x;
  32741. this.normals[index + 1] = transformed.y;
  32742. this.normals[index + 2] = transformed.z;
  32743. }
  32744. }
  32745. if (this.tangents) {
  32746. var tangent = BABYLON.Vector4.Zero();
  32747. var tangentTransformed = BABYLON.Vector4.Zero();
  32748. for (index = 0; index < this.tangents.length; index += 4) {
  32749. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  32750. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  32751. this.tangents[index] = tangentTransformed.x;
  32752. this.tangents[index + 1] = tangentTransformed.y;
  32753. this.tangents[index + 2] = tangentTransformed.z;
  32754. this.tangents[index + 3] = tangentTransformed.w;
  32755. }
  32756. }
  32757. return this;
  32758. };
  32759. /**
  32760. * Merges the passed VertexData into the current one.
  32761. * Returns the modified VertexData.
  32762. */
  32763. VertexData.prototype.merge = function (other) {
  32764. this._validate();
  32765. other._validate();
  32766. if (!this.normals !== !other.normals ||
  32767. !this.tangents !== !other.tangents ||
  32768. !this.uvs !== !other.uvs ||
  32769. !this.uvs2 !== !other.uvs2 ||
  32770. !this.uvs3 !== !other.uvs3 ||
  32771. !this.uvs4 !== !other.uvs4 ||
  32772. !this.uvs5 !== !other.uvs5 ||
  32773. !this.uvs6 !== !other.uvs6 ||
  32774. !this.colors !== !other.colors ||
  32775. !this.matricesIndices !== !other.matricesIndices ||
  32776. !this.matricesWeights !== !other.matricesWeights ||
  32777. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  32778. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  32779. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  32780. }
  32781. if (other.indices) {
  32782. if (!this.indices) {
  32783. this.indices = [];
  32784. }
  32785. var offset = this.positions ? this.positions.length / 3 : 0;
  32786. for (var index = 0; index < other.indices.length; index++) {
  32787. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  32788. this.indices.push(other.indices[index] + offset);
  32789. }
  32790. }
  32791. this.positions = this._mergeElement(this.positions, other.positions);
  32792. this.normals = this._mergeElement(this.normals, other.normals);
  32793. this.tangents = this._mergeElement(this.tangents, other.tangents);
  32794. this.uvs = this._mergeElement(this.uvs, other.uvs);
  32795. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  32796. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  32797. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  32798. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  32799. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  32800. this.colors = this._mergeElement(this.colors, other.colors);
  32801. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  32802. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  32803. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  32804. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  32805. return this;
  32806. };
  32807. VertexData.prototype._mergeElement = function (source, other) {
  32808. if (!source) {
  32809. return other;
  32810. }
  32811. if (!other) {
  32812. return source;
  32813. }
  32814. var len = other.length + source.length;
  32815. var isSrcTypedArray = source instanceof Float32Array;
  32816. var isOthTypedArray = other instanceof Float32Array;
  32817. // use non-loop method when the source is Float32Array
  32818. if (isSrcTypedArray) {
  32819. var ret32 = new Float32Array(len);
  32820. ret32.set(source);
  32821. ret32.set(other, source.length);
  32822. return ret32;
  32823. // source is number[], when other is also use concat
  32824. }
  32825. else if (!isOthTypedArray) {
  32826. return source.concat(other);
  32827. // source is a number[], but other is a Float32Array, loop required
  32828. }
  32829. else {
  32830. var ret = source.slice(0); // copy source to a separate array
  32831. for (var i = 0, len = other.length; i < len; i++) {
  32832. ret.push(other[i]);
  32833. }
  32834. return ret;
  32835. }
  32836. };
  32837. VertexData.prototype._validate = function () {
  32838. if (!this.positions) {
  32839. throw new Error("Positions are required");
  32840. }
  32841. var getElementCount = function (kind, values) {
  32842. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  32843. if ((values.length % stride) !== 0) {
  32844. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  32845. }
  32846. return values.length / stride;
  32847. };
  32848. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  32849. var validateElementCount = function (kind, values) {
  32850. var elementCount = getElementCount(kind, values);
  32851. if (elementCount !== positionsElementCount) {
  32852. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  32853. }
  32854. };
  32855. if (this.normals)
  32856. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  32857. if (this.tangents)
  32858. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  32859. if (this.uvs)
  32860. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  32861. if (this.uvs2)
  32862. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  32863. if (this.uvs3)
  32864. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  32865. if (this.uvs4)
  32866. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  32867. if (this.uvs5)
  32868. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  32869. if (this.uvs6)
  32870. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  32871. if (this.colors)
  32872. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  32873. if (this.matricesIndices)
  32874. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  32875. if (this.matricesWeights)
  32876. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  32877. if (this.matricesIndicesExtra)
  32878. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  32879. if (this.matricesWeightsExtra)
  32880. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  32881. };
  32882. /**
  32883. * Serializes the VertexData.
  32884. * Returns a serialized object.
  32885. */
  32886. VertexData.prototype.serialize = function () {
  32887. var serializationObject = this.serialize();
  32888. if (this.positions) {
  32889. serializationObject.positions = this.positions;
  32890. }
  32891. if (this.normals) {
  32892. serializationObject.normals = this.normals;
  32893. }
  32894. if (this.tangents) {
  32895. serializationObject.tangents = this.tangents;
  32896. }
  32897. if (this.uvs) {
  32898. serializationObject.uvs = this.uvs;
  32899. }
  32900. if (this.uvs2) {
  32901. serializationObject.uvs2 = this.uvs2;
  32902. }
  32903. if (this.uvs3) {
  32904. serializationObject.uvs3 = this.uvs3;
  32905. }
  32906. if (this.uvs4) {
  32907. serializationObject.uvs4 = this.uvs4;
  32908. }
  32909. if (this.uvs5) {
  32910. serializationObject.uvs5 = this.uvs5;
  32911. }
  32912. if (this.uvs6) {
  32913. serializationObject.uvs6 = this.uvs6;
  32914. }
  32915. if (this.colors) {
  32916. serializationObject.colors = this.colors;
  32917. }
  32918. if (this.matricesIndices) {
  32919. serializationObject.matricesIndices = this.matricesIndices;
  32920. serializationObject.matricesIndices._isExpanded = true;
  32921. }
  32922. if (this.matricesWeights) {
  32923. serializationObject.matricesWeights = this.matricesWeights;
  32924. }
  32925. if (this.matricesIndicesExtra) {
  32926. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  32927. serializationObject.matricesIndicesExtra._isExpanded = true;
  32928. }
  32929. if (this.matricesWeightsExtra) {
  32930. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  32931. }
  32932. serializationObject.indices = this.indices;
  32933. return serializationObject;
  32934. };
  32935. // Statics
  32936. /**
  32937. * Returns the object VertexData associated to the passed mesh.
  32938. */
  32939. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  32940. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  32941. };
  32942. /**
  32943. * Returns the object VertexData associated to the passed geometry.
  32944. */
  32945. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  32946. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  32947. };
  32948. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  32949. var result = new VertexData();
  32950. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  32951. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  32952. }
  32953. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  32954. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  32955. }
  32956. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  32957. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  32958. }
  32959. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32960. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  32961. }
  32962. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  32963. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  32964. }
  32965. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  32966. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  32967. }
  32968. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  32969. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  32970. }
  32971. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  32972. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  32973. }
  32974. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  32975. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  32976. }
  32977. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  32978. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  32979. }
  32980. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  32981. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  32982. }
  32983. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  32984. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  32985. }
  32986. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  32987. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  32988. }
  32989. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  32990. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  32991. }
  32992. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  32993. return result;
  32994. };
  32995. /**
  32996. * Creates the vertexData of the Ribbon.
  32997. */
  32998. VertexData.CreateRibbon = function (options) {
  32999. var pathArray = options.pathArray;
  33000. var closeArray = options.closeArray || false;
  33001. var closePath = options.closePath || false;
  33002. var invertUV = options.invertUV || false;
  33003. var defaultOffset = Math.floor(pathArray[0].length / 2);
  33004. var offset = options.offset || defaultOffset;
  33005. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  33006. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33007. var customUV = options.uvs;
  33008. var customColors = options.colors;
  33009. var positions = [];
  33010. var indices = [];
  33011. var normals = [];
  33012. var uvs = [];
  33013. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  33014. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  33015. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  33016. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  33017. var minlg; // minimal length among all paths from pathArray
  33018. var lg = []; // array of path lengths : nb of vertex per path
  33019. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  33020. var p; // path iterator
  33021. var i; // point iterator
  33022. var j; // point iterator
  33023. // if single path in pathArray
  33024. if (pathArray.length < 2) {
  33025. var ar1 = [];
  33026. var ar2 = [];
  33027. for (i = 0; i < pathArray[0].length - offset; i++) {
  33028. ar1.push(pathArray[0][i]);
  33029. ar2.push(pathArray[0][i + offset]);
  33030. }
  33031. pathArray = [ar1, ar2];
  33032. }
  33033. // positions and horizontal distances (u)
  33034. var idc = 0;
  33035. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  33036. var path;
  33037. var l;
  33038. minlg = pathArray[0].length;
  33039. var vectlg;
  33040. var dist;
  33041. for (p = 0; p < pathArray.length; p++) {
  33042. uTotalDistance[p] = 0;
  33043. us[p] = [0];
  33044. path = pathArray[p];
  33045. l = path.length;
  33046. minlg = (minlg < l) ? minlg : l;
  33047. j = 0;
  33048. while (j < l) {
  33049. positions.push(path[j].x, path[j].y, path[j].z);
  33050. if (j > 0) {
  33051. vectlg = path[j].subtract(path[j - 1]).length();
  33052. dist = vectlg + uTotalDistance[p];
  33053. us[p].push(dist);
  33054. uTotalDistance[p] = dist;
  33055. }
  33056. j++;
  33057. }
  33058. if (closePath) {
  33059. j--;
  33060. positions.push(path[0].x, path[0].y, path[0].z);
  33061. vectlg = path[j].subtract(path[0]).length();
  33062. dist = vectlg + uTotalDistance[p];
  33063. us[p].push(dist);
  33064. uTotalDistance[p] = dist;
  33065. }
  33066. lg[p] = l + closePathCorr;
  33067. idx[p] = idc;
  33068. idc += (l + closePathCorr);
  33069. }
  33070. // vertical distances (v)
  33071. var path1;
  33072. var path2;
  33073. var vertex1 = null;
  33074. var vertex2 = null;
  33075. for (i = 0; i < minlg + closePathCorr; i++) {
  33076. vTotalDistance[i] = 0;
  33077. vs[i] = [0];
  33078. for (p = 0; p < pathArray.length - 1; p++) {
  33079. path1 = pathArray[p];
  33080. path2 = pathArray[p + 1];
  33081. if (i === minlg) {
  33082. vertex1 = path1[0];
  33083. vertex2 = path2[0];
  33084. }
  33085. else {
  33086. vertex1 = path1[i];
  33087. vertex2 = path2[i];
  33088. }
  33089. vectlg = vertex2.subtract(vertex1).length();
  33090. dist = vectlg + vTotalDistance[i];
  33091. vs[i].push(dist);
  33092. vTotalDistance[i] = dist;
  33093. }
  33094. if (closeArray && vertex2 && vertex1) {
  33095. path1 = pathArray[p];
  33096. path2 = pathArray[0];
  33097. if (i === minlg) {
  33098. vertex2 = path2[0];
  33099. }
  33100. vectlg = vertex2.subtract(vertex1).length();
  33101. dist = vectlg + vTotalDistance[i];
  33102. vTotalDistance[i] = dist;
  33103. }
  33104. }
  33105. // uvs
  33106. var u;
  33107. var v;
  33108. if (customUV) {
  33109. for (p = 0; p < customUV.length; p++) {
  33110. uvs.push(customUV[p].x, customUV[p].y);
  33111. }
  33112. }
  33113. else {
  33114. for (p = 0; p < pathArray.length; p++) {
  33115. for (i = 0; i < minlg + closePathCorr; i++) {
  33116. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  33117. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  33118. if (invertUV) {
  33119. uvs.push(v, u);
  33120. }
  33121. else {
  33122. uvs.push(u, v);
  33123. }
  33124. }
  33125. }
  33126. }
  33127. // indices
  33128. p = 0; // path index
  33129. var pi = 0; // positions array index
  33130. var l1 = lg[p] - 1; // path1 length
  33131. var l2 = lg[p + 1] - 1; // path2 length
  33132. var min = (l1 < l2) ? l1 : l2; // current path stop index
  33133. var shft = idx[1] - idx[0]; // shift
  33134. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  33135. while (pi <= min && p < path1nb) {
  33136. // draw two triangles between path1 (p1) and path2 (p2) : (p1.pi, p2.pi, p1.pi+1) and (p2.pi+1, p1.pi+1, p2.pi) clockwise
  33137. indices.push(pi, pi + shft, pi + 1);
  33138. indices.push(pi + shft + 1, pi + 1, pi + shft);
  33139. pi += 1;
  33140. if (pi === min) {
  33141. p++;
  33142. if (p === lg.length - 1) {
  33143. shft = idx[0] - idx[p];
  33144. l1 = lg[p] - 1;
  33145. l2 = lg[0] - 1;
  33146. }
  33147. else {
  33148. shft = idx[p + 1] - idx[p];
  33149. l1 = lg[p] - 1;
  33150. l2 = lg[p + 1] - 1;
  33151. }
  33152. pi = idx[p];
  33153. min = (l1 < l2) ? l1 + pi : l2 + pi;
  33154. }
  33155. }
  33156. // normals
  33157. VertexData.ComputeNormals(positions, indices, normals);
  33158. if (closePath) {
  33159. var indexFirst = 0;
  33160. var indexLast = 0;
  33161. for (p = 0; p < pathArray.length; p++) {
  33162. indexFirst = idx[p] * 3;
  33163. if (p + 1 < pathArray.length) {
  33164. indexLast = (idx[p + 1] - 1) * 3;
  33165. }
  33166. else {
  33167. indexLast = normals.length - 3;
  33168. }
  33169. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  33170. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  33171. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  33172. normals[indexLast] = normals[indexFirst];
  33173. normals[indexLast + 1] = normals[indexFirst + 1];
  33174. normals[indexLast + 2] = normals[indexFirst + 2];
  33175. }
  33176. }
  33177. // sides
  33178. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33179. // Colors
  33180. var colors = null;
  33181. if (customColors) {
  33182. colors = new Float32Array(customColors.length * 4);
  33183. for (var c = 0; c < customColors.length; c++) {
  33184. colors[c * 4] = customColors[c].r;
  33185. colors[c * 4 + 1] = customColors[c].g;
  33186. colors[c * 4 + 2] = customColors[c].b;
  33187. colors[c * 4 + 3] = customColors[c].a;
  33188. }
  33189. }
  33190. // Result
  33191. var vertexData = new VertexData();
  33192. var positions32 = new Float32Array(positions);
  33193. var normals32 = new Float32Array(normals);
  33194. var uvs32 = new Float32Array(uvs);
  33195. vertexData.indices = indices;
  33196. vertexData.positions = positions32;
  33197. vertexData.normals = normals32;
  33198. vertexData.uvs = uvs32;
  33199. if (colors) {
  33200. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  33201. }
  33202. if (closePath) {
  33203. vertexData._idx = idx;
  33204. }
  33205. return vertexData;
  33206. };
  33207. /**
  33208. * Creates the VertexData of the Box.
  33209. */
  33210. VertexData.CreateBox = function (options) {
  33211. var normalsSource = [
  33212. new BABYLON.Vector3(0, 0, 1),
  33213. new BABYLON.Vector3(0, 0, -1),
  33214. new BABYLON.Vector3(1, 0, 0),
  33215. new BABYLON.Vector3(-1, 0, 0),
  33216. new BABYLON.Vector3(0, 1, 0),
  33217. new BABYLON.Vector3(0, -1, 0)
  33218. ];
  33219. var indices = [];
  33220. var positions = [];
  33221. var normals = [];
  33222. var uvs = [];
  33223. var width = options.width || options.size || 1;
  33224. var height = options.height || options.size || 1;
  33225. var depth = options.depth || options.size || 1;
  33226. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33227. var faceUV = options.faceUV || new Array(6);
  33228. var faceColors = options.faceColors;
  33229. var colors = [];
  33230. // default face colors and UV if undefined
  33231. for (var f = 0; f < 6; f++) {
  33232. if (faceUV[f] === undefined) {
  33233. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  33234. }
  33235. if (faceColors && faceColors[f] === undefined) {
  33236. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  33237. }
  33238. }
  33239. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  33240. // Create each face in turn.
  33241. for (var index = 0; index < normalsSource.length; index++) {
  33242. var normal = normalsSource[index];
  33243. // Get two vectors perpendicular to the face normal and to each other.
  33244. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  33245. var side2 = BABYLON.Vector3.Cross(normal, side1);
  33246. // Six indices (two triangles) per face.
  33247. var verticesLength = positions.length / 3;
  33248. indices.push(verticesLength);
  33249. indices.push(verticesLength + 1);
  33250. indices.push(verticesLength + 2);
  33251. indices.push(verticesLength);
  33252. indices.push(verticesLength + 2);
  33253. indices.push(verticesLength + 3);
  33254. // Four vertices per face.
  33255. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  33256. positions.push(vertex.x, vertex.y, vertex.z);
  33257. normals.push(normal.x, normal.y, normal.z);
  33258. uvs.push(faceUV[index].z, faceUV[index].w);
  33259. if (faceColors) {
  33260. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33261. }
  33262. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  33263. positions.push(vertex.x, vertex.y, vertex.z);
  33264. normals.push(normal.x, normal.y, normal.z);
  33265. uvs.push(faceUV[index].x, faceUV[index].w);
  33266. if (faceColors) {
  33267. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33268. }
  33269. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  33270. positions.push(vertex.x, vertex.y, vertex.z);
  33271. normals.push(normal.x, normal.y, normal.z);
  33272. uvs.push(faceUV[index].x, faceUV[index].y);
  33273. if (faceColors) {
  33274. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33275. }
  33276. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  33277. positions.push(vertex.x, vertex.y, vertex.z);
  33278. normals.push(normal.x, normal.y, normal.z);
  33279. uvs.push(faceUV[index].z, faceUV[index].y);
  33280. if (faceColors) {
  33281. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33282. }
  33283. }
  33284. // sides
  33285. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33286. // Result
  33287. var vertexData = new VertexData();
  33288. vertexData.indices = indices;
  33289. vertexData.positions = positions;
  33290. vertexData.normals = normals;
  33291. vertexData.uvs = uvs;
  33292. if (faceColors) {
  33293. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  33294. vertexData.colors = totalColors;
  33295. }
  33296. return vertexData;
  33297. };
  33298. /**
  33299. * Creates the VertexData of the Sphere.
  33300. */
  33301. VertexData.CreateSphere = function (options) {
  33302. var segments = options.segments || 32;
  33303. var diameterX = options.diameterX || options.diameter || 1;
  33304. var diameterY = options.diameterY || options.diameter || 1;
  33305. var diameterZ = options.diameterZ || options.diameter || 1;
  33306. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  33307. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  33308. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33309. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  33310. var totalZRotationSteps = 2 + segments;
  33311. var totalYRotationSteps = 2 * totalZRotationSteps;
  33312. var indices = [];
  33313. var positions = [];
  33314. var normals = [];
  33315. var uvs = [];
  33316. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  33317. var normalizedZ = zRotationStep / totalZRotationSteps;
  33318. var angleZ = normalizedZ * Math.PI * slice;
  33319. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  33320. var normalizedY = yRotationStep / totalYRotationSteps;
  33321. var angleY = normalizedY * Math.PI * 2 * arc;
  33322. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  33323. var rotationY = BABYLON.Matrix.RotationY(angleY);
  33324. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  33325. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  33326. var vertex = complete.multiply(radius);
  33327. var normal = complete.divide(radius).normalize();
  33328. positions.push(vertex.x, vertex.y, vertex.z);
  33329. normals.push(normal.x, normal.y, normal.z);
  33330. uvs.push(normalizedY, normalizedZ);
  33331. }
  33332. if (zRotationStep > 0) {
  33333. var verticesCount = positions.length / 3;
  33334. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  33335. indices.push((firstIndex));
  33336. indices.push((firstIndex + 1));
  33337. indices.push(firstIndex + totalYRotationSteps + 1);
  33338. indices.push((firstIndex + totalYRotationSteps + 1));
  33339. indices.push((firstIndex + 1));
  33340. indices.push((firstIndex + totalYRotationSteps + 2));
  33341. }
  33342. }
  33343. }
  33344. // Sides
  33345. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33346. // Result
  33347. var vertexData = new VertexData();
  33348. vertexData.indices = indices;
  33349. vertexData.positions = positions;
  33350. vertexData.normals = normals;
  33351. vertexData.uvs = uvs;
  33352. return vertexData;
  33353. };
  33354. /**
  33355. * Creates the VertexData of the Cylinder or Cone.
  33356. */
  33357. VertexData.CreateCylinder = function (options) {
  33358. var height = options.height || 2;
  33359. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  33360. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  33361. var tessellation = options.tessellation || 24;
  33362. var subdivisions = options.subdivisions || 1;
  33363. var hasRings = options.hasRings ? true : false;
  33364. var enclose = options.enclose ? true : false;
  33365. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  33366. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33367. var faceUV = options.faceUV || new Array(3);
  33368. var faceColors = options.faceColors;
  33369. // default face colors and UV if undefined
  33370. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  33371. var ringNb = (hasRings) ? subdivisions : 1;
  33372. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  33373. var f;
  33374. for (f = 0; f < surfaceNb; f++) {
  33375. if (faceColors && faceColors[f] === undefined) {
  33376. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  33377. }
  33378. }
  33379. for (f = 0; f < surfaceNb; f++) {
  33380. if (faceUV && faceUV[f] === undefined) {
  33381. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  33382. }
  33383. }
  33384. var indices = new Array();
  33385. var positions = new Array();
  33386. var normals = new Array();
  33387. var uvs = new Array();
  33388. var colors = new Array();
  33389. var angle_step = Math.PI * 2 * arc / tessellation;
  33390. var angle;
  33391. var h;
  33392. var radius;
  33393. var tan = (diameterBottom - diameterTop) / 2 / height;
  33394. var ringVertex = BABYLON.Vector3.Zero();
  33395. var ringNormal = BABYLON.Vector3.Zero();
  33396. var ringFirstVertex = BABYLON.Vector3.Zero();
  33397. var ringFirstNormal = BABYLON.Vector3.Zero();
  33398. var quadNormal = BABYLON.Vector3.Zero();
  33399. var Y = BABYLON.Axis.Y;
  33400. // positions, normals, uvs
  33401. var i;
  33402. var j;
  33403. var r;
  33404. var ringIdx = 1;
  33405. var s = 1; // surface index
  33406. var cs = 0;
  33407. var v = 0;
  33408. for (i = 0; i <= subdivisions; i++) {
  33409. h = i / subdivisions;
  33410. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  33411. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  33412. for (r = 0; r < ringIdx; r++) {
  33413. if (hasRings) {
  33414. s += r;
  33415. }
  33416. if (enclose) {
  33417. s += 2 * r;
  33418. }
  33419. for (j = 0; j <= tessellation; j++) {
  33420. angle = j * angle_step;
  33421. // position
  33422. ringVertex.x = Math.cos(-angle) * radius;
  33423. ringVertex.y = -height / 2 + h * height;
  33424. ringVertex.z = Math.sin(-angle) * radius;
  33425. // normal
  33426. if (diameterTop === 0 && i === subdivisions) {
  33427. // if no top cap, reuse former normals
  33428. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  33429. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  33430. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  33431. }
  33432. else {
  33433. ringNormal.x = ringVertex.x;
  33434. ringNormal.z = ringVertex.z;
  33435. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  33436. ringNormal.normalize();
  33437. }
  33438. // keep first ring vertex values for enclose
  33439. if (j === 0) {
  33440. ringFirstVertex.copyFrom(ringVertex);
  33441. ringFirstNormal.copyFrom(ringNormal);
  33442. }
  33443. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  33444. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  33445. if (hasRings) {
  33446. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  33447. }
  33448. else {
  33449. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  33450. }
  33451. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  33452. if (faceColors) {
  33453. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  33454. }
  33455. }
  33456. // if enclose, add four vertices and their dedicated normals
  33457. if (arc !== 1 && enclose) {
  33458. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  33459. positions.push(0, ringVertex.y, 0);
  33460. positions.push(0, ringVertex.y, 0);
  33461. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  33462. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  33463. quadNormal.normalize();
  33464. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  33465. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  33466. quadNormal.normalize();
  33467. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  33468. if (hasRings) {
  33469. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  33470. }
  33471. else {
  33472. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  33473. }
  33474. uvs.push(faceUV[s + 1].x, v);
  33475. uvs.push(faceUV[s + 1].z, v);
  33476. if (hasRings) {
  33477. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  33478. }
  33479. else {
  33480. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  33481. }
  33482. uvs.push(faceUV[s + 2].x, v);
  33483. uvs.push(faceUV[s + 2].z, v);
  33484. if (faceColors) {
  33485. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  33486. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  33487. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  33488. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  33489. }
  33490. }
  33491. if (cs !== s) {
  33492. cs = s;
  33493. }
  33494. }
  33495. }
  33496. // indices
  33497. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  33498. var s;
  33499. i = 0;
  33500. for (s = 0; s < subdivisions; s++) {
  33501. var i0 = 0;
  33502. var i1 = 0;
  33503. var i2 = 0;
  33504. var i3 = 0;
  33505. for (j = 0; j < tessellation; j++) {
  33506. i0 = i * (e + 1) + j;
  33507. i1 = (i + 1) * (e + 1) + j;
  33508. i2 = i * (e + 1) + (j + 1);
  33509. i3 = (i + 1) * (e + 1) + (j + 1);
  33510. indices.push(i0, i1, i2);
  33511. indices.push(i3, i2, i1);
  33512. }
  33513. if (arc !== 1 && enclose) {
  33514. indices.push(i0 + 2, i1 + 2, i2 + 2);
  33515. indices.push(i3 + 2, i2 + 2, i1 + 2);
  33516. indices.push(i0 + 4, i1 + 4, i2 + 4);
  33517. indices.push(i3 + 4, i2 + 4, i1 + 4);
  33518. }
  33519. i = (hasRings) ? (i + 2) : (i + 1);
  33520. }
  33521. // Caps
  33522. var createCylinderCap = function (isTop) {
  33523. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  33524. if (radius === 0) {
  33525. return;
  33526. }
  33527. // Cap positions, normals & uvs
  33528. var angle;
  33529. var circleVector;
  33530. var i;
  33531. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  33532. var c = null;
  33533. if (faceColors) {
  33534. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  33535. }
  33536. // cap center
  33537. var vbase = positions.length / 3;
  33538. var offset = isTop ? height / 2 : -height / 2;
  33539. var center = new BABYLON.Vector3(0, offset, 0);
  33540. positions.push(center.x, center.y, center.z);
  33541. normals.push(0, isTop ? 1 : -1, 0);
  33542. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  33543. if (c) {
  33544. colors.push(c.r, c.g, c.b, c.a);
  33545. }
  33546. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  33547. for (i = 0; i <= tessellation; i++) {
  33548. angle = Math.PI * 2 * i * arc / tessellation;
  33549. var cos = Math.cos(-angle);
  33550. var sin = Math.sin(-angle);
  33551. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  33552. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  33553. positions.push(circleVector.x, circleVector.y, circleVector.z);
  33554. normals.push(0, isTop ? 1 : -1, 0);
  33555. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  33556. if (c) {
  33557. colors.push(c.r, c.g, c.b, c.a);
  33558. }
  33559. }
  33560. // Cap indices
  33561. for (i = 0; i < tessellation; i++) {
  33562. if (!isTop) {
  33563. indices.push(vbase);
  33564. indices.push(vbase + (i + 1));
  33565. indices.push(vbase + (i + 2));
  33566. }
  33567. else {
  33568. indices.push(vbase);
  33569. indices.push(vbase + (i + 2));
  33570. indices.push(vbase + (i + 1));
  33571. }
  33572. }
  33573. };
  33574. // add caps to geometry
  33575. createCylinderCap(false);
  33576. createCylinderCap(true);
  33577. // Sides
  33578. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33579. var vertexData = new VertexData();
  33580. vertexData.indices = indices;
  33581. vertexData.positions = positions;
  33582. vertexData.normals = normals;
  33583. vertexData.uvs = uvs;
  33584. if (faceColors) {
  33585. vertexData.colors = colors;
  33586. }
  33587. return vertexData;
  33588. };
  33589. /**
  33590. * Creates the VertexData of the Torus.
  33591. */
  33592. VertexData.CreateTorus = function (options) {
  33593. var indices = [];
  33594. var positions = [];
  33595. var normals = [];
  33596. var uvs = [];
  33597. var diameter = options.diameter || 1;
  33598. var thickness = options.thickness || 0.5;
  33599. var tessellation = options.tessellation || 16;
  33600. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33601. var stride = tessellation + 1;
  33602. for (var i = 0; i <= tessellation; i++) {
  33603. var u = i / tessellation;
  33604. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  33605. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  33606. for (var j = 0; j <= tessellation; j++) {
  33607. var v = 1 - j / tessellation;
  33608. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  33609. var dx = Math.cos(innerAngle);
  33610. var dy = Math.sin(innerAngle);
  33611. // Create a vertex.
  33612. var normal = new BABYLON.Vector3(dx, dy, 0);
  33613. var position = normal.scale(thickness / 2);
  33614. var textureCoordinate = new BABYLON.Vector2(u, v);
  33615. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  33616. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  33617. positions.push(position.x, position.y, position.z);
  33618. normals.push(normal.x, normal.y, normal.z);
  33619. uvs.push(textureCoordinate.x, textureCoordinate.y);
  33620. // And create indices for two triangles.
  33621. var nextI = (i + 1) % stride;
  33622. var nextJ = (j + 1) % stride;
  33623. indices.push(i * stride + j);
  33624. indices.push(i * stride + nextJ);
  33625. indices.push(nextI * stride + j);
  33626. indices.push(i * stride + nextJ);
  33627. indices.push(nextI * stride + nextJ);
  33628. indices.push(nextI * stride + j);
  33629. }
  33630. }
  33631. // Sides
  33632. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33633. // Result
  33634. var vertexData = new VertexData();
  33635. vertexData.indices = indices;
  33636. vertexData.positions = positions;
  33637. vertexData.normals = normals;
  33638. vertexData.uvs = uvs;
  33639. return vertexData;
  33640. };
  33641. /**
  33642. * Creates the VertexData of the LineSystem.
  33643. */
  33644. VertexData.CreateLineSystem = function (options) {
  33645. var indices = [];
  33646. var positions = [];
  33647. var lines = options.lines;
  33648. var colors = options.colors;
  33649. var vertexColors = [];
  33650. var idx = 0;
  33651. for (var l = 0; l < lines.length; l++) {
  33652. var points = lines[l];
  33653. for (var index = 0; index < points.length; index++) {
  33654. positions.push(points[index].x, points[index].y, points[index].z);
  33655. if (colors) {
  33656. var color = colors[l];
  33657. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  33658. }
  33659. if (index > 0) {
  33660. indices.push(idx - 1);
  33661. indices.push(idx);
  33662. }
  33663. idx++;
  33664. }
  33665. }
  33666. var vertexData = new VertexData();
  33667. vertexData.indices = indices;
  33668. vertexData.positions = positions;
  33669. if (colors) {
  33670. vertexData.colors = vertexColors;
  33671. }
  33672. return vertexData;
  33673. };
  33674. /**
  33675. * Create the VertexData of the DashedLines.
  33676. */
  33677. VertexData.CreateDashedLines = function (options) {
  33678. var dashSize = options.dashSize || 3;
  33679. var gapSize = options.gapSize || 1;
  33680. var dashNb = options.dashNb || 200;
  33681. var points = options.points;
  33682. var positions = new Array();
  33683. var indices = new Array();
  33684. var curvect = BABYLON.Vector3.Zero();
  33685. var lg = 0;
  33686. var nb = 0;
  33687. var shft = 0;
  33688. var dashshft = 0;
  33689. var curshft = 0;
  33690. var idx = 0;
  33691. var i = 0;
  33692. for (i = 0; i < points.length - 1; i++) {
  33693. points[i + 1].subtractToRef(points[i], curvect);
  33694. lg += curvect.length();
  33695. }
  33696. shft = lg / dashNb;
  33697. dashshft = dashSize * shft / (dashSize + gapSize);
  33698. for (i = 0; i < points.length - 1; i++) {
  33699. points[i + 1].subtractToRef(points[i], curvect);
  33700. nb = Math.floor(curvect.length() / shft);
  33701. curvect.normalize();
  33702. for (var j = 0; j < nb; j++) {
  33703. curshft = shft * j;
  33704. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  33705. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  33706. indices.push(idx, idx + 1);
  33707. idx += 2;
  33708. }
  33709. }
  33710. // Result
  33711. var vertexData = new VertexData();
  33712. vertexData.positions = positions;
  33713. vertexData.indices = indices;
  33714. return vertexData;
  33715. };
  33716. /**
  33717. * Creates the VertexData of the Ground.
  33718. */
  33719. VertexData.CreateGround = function (options) {
  33720. var indices = [];
  33721. var positions = [];
  33722. var normals = [];
  33723. var uvs = [];
  33724. var row, col;
  33725. var width = options.width || 1;
  33726. var height = options.height || 1;
  33727. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  33728. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  33729. for (row = 0; row <= subdivisionsY; row++) {
  33730. for (col = 0; col <= subdivisionsX; col++) {
  33731. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  33732. var normal = new BABYLON.Vector3(0, 1.0, 0);
  33733. positions.push(position.x, position.y, position.z);
  33734. normals.push(normal.x, normal.y, normal.z);
  33735. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  33736. }
  33737. }
  33738. for (row = 0; row < subdivisionsY; row++) {
  33739. for (col = 0; col < subdivisionsX; col++) {
  33740. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  33741. indices.push(col + 1 + row * (subdivisionsX + 1));
  33742. indices.push(col + row * (subdivisionsX + 1));
  33743. indices.push(col + (row + 1) * (subdivisionsX + 1));
  33744. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  33745. indices.push(col + row * (subdivisionsX + 1));
  33746. }
  33747. }
  33748. // Result
  33749. var vertexData = new VertexData();
  33750. vertexData.indices = indices;
  33751. vertexData.positions = positions;
  33752. vertexData.normals = normals;
  33753. vertexData.uvs = uvs;
  33754. return vertexData;
  33755. };
  33756. /**
  33757. * Creates the VertexData of the TiledGround.
  33758. */
  33759. VertexData.CreateTiledGround = function (options) {
  33760. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  33761. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  33762. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  33763. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  33764. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  33765. var precision = options.precision || { w: 1, h: 1 };
  33766. var indices = new Array();
  33767. var positions = new Array();
  33768. var normals = new Array();
  33769. var uvs = new Array();
  33770. var row, col, tileRow, tileCol;
  33771. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  33772. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  33773. precision.w = (precision.w < 1) ? 1 : precision.w;
  33774. precision.h = (precision.h < 1) ? 1 : precision.h;
  33775. var tileSize = {
  33776. 'w': (xmax - xmin) / subdivisions.w,
  33777. 'h': (zmax - zmin) / subdivisions.h
  33778. };
  33779. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  33780. // Indices
  33781. var base = positions.length / 3;
  33782. var rowLength = precision.w + 1;
  33783. for (row = 0; row < precision.h; row++) {
  33784. for (col = 0; col < precision.w; col++) {
  33785. var square = [
  33786. base + col + row * rowLength,
  33787. base + (col + 1) + row * rowLength,
  33788. base + (col + 1) + (row + 1) * rowLength,
  33789. base + col + (row + 1) * rowLength
  33790. ];
  33791. indices.push(square[1]);
  33792. indices.push(square[2]);
  33793. indices.push(square[3]);
  33794. indices.push(square[0]);
  33795. indices.push(square[1]);
  33796. indices.push(square[3]);
  33797. }
  33798. }
  33799. // Position, normals and uvs
  33800. var position = BABYLON.Vector3.Zero();
  33801. var normal = new BABYLON.Vector3(0, 1.0, 0);
  33802. for (row = 0; row <= precision.h; row++) {
  33803. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  33804. for (col = 0; col <= precision.w; col++) {
  33805. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  33806. position.y = 0;
  33807. positions.push(position.x, position.y, position.z);
  33808. normals.push(normal.x, normal.y, normal.z);
  33809. uvs.push(col / precision.w, row / precision.h);
  33810. }
  33811. }
  33812. }
  33813. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  33814. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  33815. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  33816. }
  33817. }
  33818. // Result
  33819. var vertexData = new VertexData();
  33820. vertexData.indices = indices;
  33821. vertexData.positions = positions;
  33822. vertexData.normals = normals;
  33823. vertexData.uvs = uvs;
  33824. return vertexData;
  33825. };
  33826. /**
  33827. * Creates the VertexData of the Ground designed from a heightmap.
  33828. */
  33829. VertexData.CreateGroundFromHeightMap = function (options) {
  33830. var indices = [];
  33831. var positions = [];
  33832. var normals = [];
  33833. var uvs = [];
  33834. var row, col;
  33835. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  33836. // Vertices
  33837. for (row = 0; row <= options.subdivisions; row++) {
  33838. for (col = 0; col <= options.subdivisions; col++) {
  33839. var position = new BABYLON.Vector3((col * options.width) / options.subdivisions - (options.width / 2.0), 0, ((options.subdivisions - row) * options.height) / options.subdivisions - (options.height / 2.0));
  33840. // Compute height
  33841. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  33842. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  33843. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  33844. var r = options.buffer[pos] / 255.0;
  33845. var g = options.buffer[pos + 1] / 255.0;
  33846. var b = options.buffer[pos + 2] / 255.0;
  33847. var gradient = r * filter.r + g * filter.g + b * filter.b;
  33848. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  33849. // Add vertex
  33850. positions.push(position.x, position.y, position.z);
  33851. normals.push(0, 0, 0);
  33852. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  33853. }
  33854. }
  33855. // Indices
  33856. for (row = 0; row < options.subdivisions; row++) {
  33857. for (col = 0; col < options.subdivisions; col++) {
  33858. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  33859. indices.push(col + 1 + row * (options.subdivisions + 1));
  33860. indices.push(col + row * (options.subdivisions + 1));
  33861. indices.push(col + (row + 1) * (options.subdivisions + 1));
  33862. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  33863. indices.push(col + row * (options.subdivisions + 1));
  33864. }
  33865. }
  33866. // Normals
  33867. VertexData.ComputeNormals(positions, indices, normals);
  33868. // Result
  33869. var vertexData = new VertexData();
  33870. vertexData.indices = indices;
  33871. vertexData.positions = positions;
  33872. vertexData.normals = normals;
  33873. vertexData.uvs = uvs;
  33874. return vertexData;
  33875. };
  33876. /**
  33877. * Creates the VertexData of the Plane.
  33878. */
  33879. VertexData.CreatePlane = function (options) {
  33880. var indices = [];
  33881. var positions = [];
  33882. var normals = [];
  33883. var uvs = [];
  33884. var width = options.width || options.size || 1;
  33885. var height = options.height || options.size || 1;
  33886. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33887. // Vertices
  33888. var halfWidth = width / 2.0;
  33889. var halfHeight = height / 2.0;
  33890. positions.push(-halfWidth, -halfHeight, 0);
  33891. normals.push(0, 0, -1.0);
  33892. uvs.push(0.0, 0.0);
  33893. positions.push(halfWidth, -halfHeight, 0);
  33894. normals.push(0, 0, -1.0);
  33895. uvs.push(1.0, 0.0);
  33896. positions.push(halfWidth, halfHeight, 0);
  33897. normals.push(0, 0, -1.0);
  33898. uvs.push(1.0, 1.0);
  33899. positions.push(-halfWidth, halfHeight, 0);
  33900. normals.push(0, 0, -1.0);
  33901. uvs.push(0.0, 1.0);
  33902. // Indices
  33903. indices.push(0);
  33904. indices.push(1);
  33905. indices.push(2);
  33906. indices.push(0);
  33907. indices.push(2);
  33908. indices.push(3);
  33909. // Sides
  33910. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33911. // Result
  33912. var vertexData = new VertexData();
  33913. vertexData.indices = indices;
  33914. vertexData.positions = positions;
  33915. vertexData.normals = normals;
  33916. vertexData.uvs = uvs;
  33917. return vertexData;
  33918. };
  33919. /**
  33920. * Creates the VertexData of the Disc or regular Polygon.
  33921. */
  33922. VertexData.CreateDisc = function (options) {
  33923. var positions = new Array();
  33924. var indices = new Array();
  33925. var normals = new Array();
  33926. var uvs = new Array();
  33927. var radius = options.radius || 0.5;
  33928. var tessellation = options.tessellation || 64;
  33929. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  33930. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33931. // positions and uvs
  33932. positions.push(0, 0, 0); // disc center first
  33933. uvs.push(0.5, 0.5);
  33934. var theta = Math.PI * 2 * arc;
  33935. var step = theta / tessellation;
  33936. for (var a = 0; a < theta; a += step) {
  33937. var x = Math.cos(a);
  33938. var y = Math.sin(a);
  33939. var u = (x + 1) / 2;
  33940. var v = (1 - y) / 2;
  33941. positions.push(radius * x, radius * y, 0);
  33942. uvs.push(u, v);
  33943. }
  33944. if (arc === 1) {
  33945. positions.push(positions[3], positions[4], positions[5]); // close the circle
  33946. uvs.push(uvs[2], uvs[3]);
  33947. }
  33948. //indices
  33949. var vertexNb = positions.length / 3;
  33950. for (var i = 1; i < vertexNb - 1; i++) {
  33951. indices.push(i + 1, 0, i);
  33952. }
  33953. // result
  33954. VertexData.ComputeNormals(positions, indices, normals);
  33955. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33956. var vertexData = new VertexData();
  33957. vertexData.indices = indices;
  33958. vertexData.positions = positions;
  33959. vertexData.normals = normals;
  33960. vertexData.uvs = uvs;
  33961. return vertexData;
  33962. };
  33963. /**
  33964. * Re-creates the VertexData of the Polygon for sideOrientation.
  33965. */
  33966. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  33967. var faceUV = fUV || new Array(3);
  33968. var faceColors = fColors;
  33969. var colors = [];
  33970. // default face colors and UV if undefined
  33971. for (var f = 0; f < 3; f++) {
  33972. if (faceUV[f] === undefined) {
  33973. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  33974. }
  33975. if (faceColors && faceColors[f] === undefined) {
  33976. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  33977. }
  33978. }
  33979. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33980. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33981. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  33982. var indices = polygon.getIndices();
  33983. // set face colours and textures
  33984. var idx = 0;
  33985. var face = 0;
  33986. for (var index = 0; index < normals.length; index += 3) {
  33987. //Edge Face no. 1
  33988. if (Math.abs(normals[index + 1]) < 0.001) {
  33989. face = 1;
  33990. }
  33991. //Top Face no. 0
  33992. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  33993. face = 0;
  33994. }
  33995. //Bottom Face no. 2
  33996. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  33997. face = 2;
  33998. }
  33999. idx = index / 3;
  34000. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  34001. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  34002. if (faceColors) {
  34003. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  34004. }
  34005. }
  34006. // sides
  34007. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  34008. // Result
  34009. var vertexData = new VertexData();
  34010. vertexData.indices = indices;
  34011. vertexData.positions = positions;
  34012. vertexData.normals = normals;
  34013. vertexData.uvs = uvs;
  34014. if (faceColors) {
  34015. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  34016. vertexData.colors = totalColors;
  34017. }
  34018. return vertexData;
  34019. };
  34020. /**
  34021. * Creates the VertexData of the IcoSphere.
  34022. */
  34023. VertexData.CreateIcoSphere = function (options) {
  34024. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34025. var radius = options.radius || 1;
  34026. var flat = (options.flat === undefined) ? true : options.flat;
  34027. var subdivisions = options.subdivisions || 4;
  34028. var radiusX = options.radiusX || radius;
  34029. var radiusY = options.radiusY || radius;
  34030. var radiusZ = options.radiusZ || radius;
  34031. var t = (1 + Math.sqrt(5)) / 2;
  34032. // 12 vertex x,y,z
  34033. var ico_vertices = [
  34034. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  34035. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  34036. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  34037. ];
  34038. // index of 3 vertex makes a face of icopshere
  34039. var ico_indices = [
  34040. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  34041. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  34042. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  34043. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  34044. ];
  34045. // vertex for uv have aliased position, not for UV
  34046. var vertices_unalias_id = [
  34047. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  34048. // vertex alias
  34049. 0,
  34050. 2,
  34051. 3,
  34052. 3,
  34053. 3,
  34054. 4,
  34055. 7,
  34056. 8,
  34057. 9,
  34058. 9,
  34059. 10,
  34060. 11 // 23: B + 12
  34061. ];
  34062. // uv as integer step (not pixels !)
  34063. var ico_vertexuv = [
  34064. 5, 1, 3, 1, 6, 4, 0, 0,
  34065. 5, 3, 4, 2, 2, 2, 4, 0,
  34066. 2, 0, 1, 1, 6, 0, 6, 2,
  34067. // vertex alias (for same vertex on different faces)
  34068. 0, 4,
  34069. 3, 3,
  34070. 4, 4,
  34071. 3, 1,
  34072. 4, 2,
  34073. 4, 4,
  34074. 0, 2,
  34075. 1, 1,
  34076. 2, 2,
  34077. 3, 3,
  34078. 1, 3,
  34079. 2, 4 // 23: B + 12
  34080. ];
  34081. // Vertices[0, 1, ...9, A, B] : position on UV plane
  34082. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  34083. // First island of uv mapping
  34084. // v = 4h 3+ 2
  34085. // v = 3h 9+ 4
  34086. // v = 2h 9+ 5 B
  34087. // v = 1h 9 1 0
  34088. // v = 0h 3 8 7 A
  34089. // u = 0 1 2 3 4 5 6 *a
  34090. // Second island of uv mapping
  34091. // v = 4h 0+ B+ 4+
  34092. // v = 3h A+ 2+
  34093. // v = 2h 7+ 6 3+
  34094. // v = 1h 8+ 3+
  34095. // v = 0h
  34096. // u = 0 1 2 3 4 5 6 *a
  34097. // Face layout on texture UV mapping
  34098. // ============
  34099. // \ 4 /\ 16 / ======
  34100. // \ / \ / /\ 11 /
  34101. // \/ 7 \/ / \ /
  34102. // ======= / 10 \/
  34103. // /\ 17 /\ =======
  34104. // / \ / \ \ 15 /\
  34105. // / 8 \/ 12 \ \ / \
  34106. // ============ \/ 6 \
  34107. // \ 18 /\ ============
  34108. // \ / \ \ 5 /\ 0 /
  34109. // \/ 13 \ \ / \ /
  34110. // ======= \/ 1 \/
  34111. // =============
  34112. // /\ 19 /\ 2 /\
  34113. // / \ / \ / \
  34114. // / 14 \/ 9 \/ 3 \
  34115. // ===================
  34116. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  34117. var ustep = 138 / 1024;
  34118. var vstep = 239 / 1024;
  34119. var uoffset = 60 / 1024;
  34120. var voffset = 26 / 1024;
  34121. // Second island should have margin, not to touch the first island
  34122. // avoid any borderline artefact in pixel rounding
  34123. var island_u_offset = -40 / 1024;
  34124. var island_v_offset = +20 / 1024;
  34125. // face is either island 0 or 1 :
  34126. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  34127. var island = [
  34128. 0, 0, 0, 0, 1,
  34129. 0, 0, 1, 1, 0,
  34130. 0, 0, 1, 1, 0,
  34131. 0, 1, 1, 1, 0 // 15 - 19
  34132. ];
  34133. var indices = new Array();
  34134. var positions = new Array();
  34135. var normals = new Array();
  34136. var uvs = new Array();
  34137. var current_indice = 0;
  34138. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  34139. var face_vertex_pos = new Array(3);
  34140. var face_vertex_uv = new Array(3);
  34141. var v012;
  34142. for (v012 = 0; v012 < 3; v012++) {
  34143. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  34144. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  34145. }
  34146. // create all with normals
  34147. for (var face = 0; face < 20; face++) {
  34148. // 3 vertex per face
  34149. for (v012 = 0; v012 < 3; v012++) {
  34150. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  34151. var v_id = ico_indices[3 * face + v012];
  34152. // vertex have 3D position (x,y,z)
  34153. face_vertex_pos[v012].copyFromFloats(ico_vertices[3 * vertices_unalias_id[v_id]], ico_vertices[3 * vertices_unalias_id[v_id] + 1], ico_vertices[3 * vertices_unalias_id[v_id] + 2]);
  34154. // Normalize to get normal, then scale to radius
  34155. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  34156. // uv Coordinates from vertex ID
  34157. face_vertex_uv[v012].copyFromFloats(ico_vertexuv[2 * v_id] * ustep + uoffset + island[face] * island_u_offset, ico_vertexuv[2 * v_id + 1] * vstep + voffset + island[face] * island_v_offset);
  34158. }
  34159. // Subdivide the face (interpolate pos, norm, uv)
  34160. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  34161. // - norm is linear interpolation of vertex corner normal
  34162. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  34163. // - uv is linear interpolation
  34164. //
  34165. // Topology is as below for sub-divide by 2
  34166. // vertex shown as v0,v1,v2
  34167. // interp index is i1 to progress in range [v0,v1[
  34168. // interp index is i2 to progress in range [v0,v2[
  34169. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  34170. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  34171. //
  34172. //
  34173. // i2 v2
  34174. // ^ ^
  34175. // / / \
  34176. // / / \
  34177. // / / \
  34178. // / / (0,1) \
  34179. // / #---------\
  34180. // / / \ (0,0)'/ \
  34181. // / / \ / \
  34182. // / / \ / \
  34183. // / / (0,0) \ / (1,0) \
  34184. // / #---------#---------\
  34185. // v0 v1
  34186. //
  34187. // --------------------> i1
  34188. //
  34189. // interp of (i1,i2):
  34190. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  34191. // along i1 : lerp(x0,x1, i1/(S-i2))
  34192. //
  34193. // centroid of triangle is needed to get help normal computation
  34194. // (c1,c2) are used for centroid location
  34195. var interp_vertex = function (i1, i2, c1, c2) {
  34196. // vertex is interpolated from
  34197. // - face_vertex_pos[0..2]
  34198. // - face_vertex_uv[0..2]
  34199. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  34200. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  34201. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  34202. pos_interp.normalize();
  34203. var vertex_normal;
  34204. if (flat) {
  34205. // in flat mode, recalculate normal as face centroid normal
  34206. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  34207. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  34208. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  34209. }
  34210. else {
  34211. // in smooth mode, recalculate normal from each single vertex position
  34212. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  34213. }
  34214. // Vertex normal need correction due to X,Y,Z radius scaling
  34215. vertex_normal.x /= radiusX;
  34216. vertex_normal.y /= radiusY;
  34217. vertex_normal.z /= radiusZ;
  34218. vertex_normal.normalize();
  34219. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  34220. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  34221. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  34222. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  34223. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  34224. uvs.push(uv_interp.x, uv_interp.y);
  34225. // push each vertex has member of a face
  34226. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  34227. indices.push(current_indice);
  34228. current_indice++;
  34229. };
  34230. for (var i2 = 0; i2 < subdivisions; i2++) {
  34231. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  34232. // face : (i1,i2) for /\ :
  34233. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  34234. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  34235. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  34236. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  34237. if (i1 + i2 + 1 < subdivisions) {
  34238. // face : (i1,i2)' for \/ :
  34239. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  34240. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  34241. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  34242. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  34243. }
  34244. }
  34245. }
  34246. }
  34247. // Sides
  34248. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34249. // Result
  34250. var vertexData = new VertexData();
  34251. vertexData.indices = indices;
  34252. vertexData.positions = positions;
  34253. vertexData.normals = normals;
  34254. vertexData.uvs = uvs;
  34255. return vertexData;
  34256. };
  34257. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  34258. /**
  34259. * Creates the VertexData of the Polyhedron.
  34260. */
  34261. VertexData.CreatePolyhedron = function (options) {
  34262. // provided polyhedron types :
  34263. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  34264. // 9 : Pentagonal Pyramid (J2), 10 : Triangular Dipyramid (J12), 11 : Pentagonal Dipyramid (J13), 12 : Elongated Square Dipyramid (J15), 13 : Elongated Pentagonal Dipyramid (J16), 14 : Elongated Pentagonal Cupola (J20)
  34265. var polyhedra = [];
  34266. polyhedra[0] = { vertex: [[0, 0, 1.732051], [1.632993, 0, -0.5773503], [-0.8164966, 1.414214, -0.5773503], [-0.8164966, -1.414214, -0.5773503]], face: [[0, 1, 2], [0, 2, 3], [0, 3, 1], [1, 3, 2]] };
  34267. polyhedra[1] = { vertex: [[0, 0, 1.414214], [1.414214, 0, 0], [0, 1.414214, 0], [-1.414214, 0, 0], [0, -1.414214, 0], [0, 0, -1.414214]], face: [[0, 1, 2], [0, 2, 3], [0, 3, 4], [0, 4, 1], [1, 4, 5], [1, 5, 2], [2, 5, 3], [3, 5, 4]] };
  34268. polyhedra[2] = {
  34269. vertex: [[0, 0, 1.070466], [0.7136442, 0, 0.7978784], [-0.3568221, 0.618034, 0.7978784], [-0.3568221, -0.618034, 0.7978784], [0.7978784, 0.618034, 0.3568221], [0.7978784, -0.618034, 0.3568221], [-0.9341724, 0.381966, 0.3568221], [0.1362939, 1, 0.3568221], [0.1362939, -1, 0.3568221], [-0.9341724, -0.381966, 0.3568221], [0.9341724, 0.381966, -0.3568221], [0.9341724, -0.381966, -0.3568221], [-0.7978784, 0.618034, -0.3568221], [-0.1362939, 1, -0.3568221], [-0.1362939, -1, -0.3568221], [-0.7978784, -0.618034, -0.3568221], [0.3568221, 0.618034, -0.7978784], [0.3568221, -0.618034, -0.7978784], [-0.7136442, 0, -0.7978784], [0, 0, -1.070466]],
  34270. face: [[0, 1, 4, 7, 2], [0, 2, 6, 9, 3], [0, 3, 8, 5, 1], [1, 5, 11, 10, 4], [2, 7, 13, 12, 6], [3, 9, 15, 14, 8], [4, 10, 16, 13, 7], [5, 8, 14, 17, 11], [6, 12, 18, 15, 9], [10, 11, 17, 19, 16], [12, 13, 16, 19, 18], [14, 15, 18, 19, 17]]
  34271. };
  34272. polyhedra[3] = {
  34273. vertex: [[0, 0, 1.175571], [1.051462, 0, 0.5257311], [0.3249197, 1, 0.5257311], [-0.8506508, 0.618034, 0.5257311], [-0.8506508, -0.618034, 0.5257311], [0.3249197, -1, 0.5257311], [0.8506508, 0.618034, -0.5257311], [0.8506508, -0.618034, -0.5257311], [-0.3249197, 1, -0.5257311], [-1.051462, 0, -0.5257311], [-0.3249197, -1, -0.5257311], [0, 0, -1.175571]],
  34274. face: [[0, 1, 2], [0, 2, 3], [0, 3, 4], [0, 4, 5], [0, 5, 1], [1, 5, 7], [1, 7, 6], [1, 6, 2], [2, 6, 8], [2, 8, 3], [3, 8, 9], [3, 9, 4], [4, 9, 10], [4, 10, 5], [5, 10, 7], [6, 7, 11], [6, 11, 8], [7, 10, 11], [8, 11, 9], [9, 11, 10]]
  34275. };
  34276. polyhedra[4] = {
  34277. vertex: [[0, 0, 1.070722], [0.7148135, 0, 0.7971752], [-0.104682, 0.7071068, 0.7971752], [-0.6841528, 0.2071068, 0.7971752], [-0.104682, -0.7071068, 0.7971752], [0.6101315, 0.7071068, 0.5236279], [1.04156, 0.2071068, 0.1367736], [0.6101315, -0.7071068, 0.5236279], [-0.3574067, 1, 0.1367736], [-0.7888348, -0.5, 0.5236279], [-0.9368776, 0.5, 0.1367736], [-0.3574067, -1, 0.1367736], [0.3574067, 1, -0.1367736], [0.9368776, -0.5, -0.1367736], [0.7888348, 0.5, -0.5236279], [0.3574067, -1, -0.1367736], [-0.6101315, 0.7071068, -0.5236279], [-1.04156, -0.2071068, -0.1367736], [-0.6101315, -0.7071068, -0.5236279], [0.104682, 0.7071068, -0.7971752], [0.6841528, -0.2071068, -0.7971752], [0.104682, -0.7071068, -0.7971752], [-0.7148135, 0, -0.7971752], [0, 0, -1.070722]],
  34278. face: [[0, 2, 3], [1, 6, 5], [4, 9, 11], [7, 15, 13], [8, 16, 10], [12, 14, 19], [17, 22, 18], [20, 21, 23], [0, 1, 5, 2], [0, 3, 9, 4], [0, 4, 7, 1], [1, 7, 13, 6], [2, 5, 12, 8], [2, 8, 10, 3], [3, 10, 17, 9], [4, 11, 15, 7], [5, 6, 14, 12], [6, 13, 20, 14], [8, 12, 19, 16], [9, 17, 18, 11], [10, 16, 22, 17], [11, 18, 21, 15], [13, 15, 21, 20], [14, 20, 23, 19], [16, 19, 23, 22], [18, 22, 23, 21]]
  34279. };
  34280. polyhedra[5] = { vertex: [[0, 0, 1.322876], [1.309307, 0, 0.1889822], [-0.9819805, 0.8660254, 0.1889822], [0.1636634, -1.299038, 0.1889822], [0.3273268, 0.8660254, -0.9449112], [-0.8183171, -0.4330127, -0.9449112]], face: [[0, 3, 1], [2, 4, 5], [0, 1, 4, 2], [0, 2, 5, 3], [1, 3, 5, 4]] };
  34281. polyhedra[6] = { vertex: [[0, 0, 1.159953], [1.013464, 0, 0.5642542], [-0.3501431, 0.9510565, 0.5642542], [-0.7715208, -0.6571639, 0.5642542], [0.6633206, 0.9510565, -0.03144481], [0.8682979, -0.6571639, -0.3996071], [-1.121664, 0.2938926, -0.03144481], [-0.2348831, -1.063314, -0.3996071], [0.5181548, 0.2938926, -0.9953061], [-0.5850262, -0.112257, -0.9953061]], face: [[0, 1, 4, 2], [0, 2, 6, 3], [1, 5, 8, 4], [3, 6, 9, 7], [5, 7, 9, 8], [0, 3, 7, 5, 1], [2, 4, 8, 9, 6]] };
  34282. polyhedra[7] = { vertex: [[0, 0, 1.118034], [0.8944272, 0, 0.6708204], [-0.2236068, 0.8660254, 0.6708204], [-0.7826238, -0.4330127, 0.6708204], [0.6708204, 0.8660254, 0.2236068], [1.006231, -0.4330127, -0.2236068], [-1.006231, 0.4330127, 0.2236068], [-0.6708204, -0.8660254, -0.2236068], [0.7826238, 0.4330127, -0.6708204], [0.2236068, -0.8660254, -0.6708204], [-0.8944272, 0, -0.6708204], [0, 0, -1.118034]], face: [[0, 1, 4, 2], [0, 2, 6, 3], [1, 5, 8, 4], [3, 6, 10, 7], [5, 9, 11, 8], [7, 10, 11, 9], [0, 3, 7, 9, 5, 1], [2, 4, 8, 11, 10, 6]] };
  34283. polyhedra[8] = { vertex: [[-0.729665, 0.670121, 0.319155], [-0.655235, -0.29213, -0.754096], [-0.093922, -0.607123, 0.537818], [0.702196, 0.595691, 0.485187], [0.776626, -0.36656, -0.588064]], face: [[1, 4, 2], [0, 1, 2], [3, 0, 2], [4, 3, 2], [4, 1, 0, 3]] };
  34284. polyhedra[9] = { vertex: [[-0.868849, -0.100041, 0.61257], [-0.329458, 0.976099, 0.28078], [-0.26629, -0.013796, -0.477654], [-0.13392, -1.034115, 0.229829], [0.738834, 0.707117, -0.307018], [0.859683, -0.535264, -0.338508]], face: [[3, 0, 2], [5, 3, 2], [4, 5, 2], [1, 4, 2], [0, 1, 2], [0, 3, 5, 4, 1]] };
  34285. polyhedra[10] = { vertex: [[-0.610389, 0.243975, 0.531213], [-0.187812, -0.48795, -0.664016], [-0.187812, 0.9759, -0.664016], [0.187812, -0.9759, 0.664016], [0.798201, 0.243975, 0.132803]], face: [[1, 3, 0], [3, 4, 0], [3, 1, 4], [0, 2, 1], [0, 4, 2], [2, 4, 1]] };
  34286. polyhedra[11] = { vertex: [[-1.028778, 0.392027, -0.048786], [-0.640503, -0.646161, 0.621837], [-0.125162, -0.395663, -0.540059], [0.004683, 0.888447, -0.651988], [0.125161, 0.395663, 0.540059], [0.632925, -0.791376, 0.433102], [1.031672, 0.157063, -0.354165]], face: [[3, 2, 0], [2, 1, 0], [2, 5, 1], [0, 4, 3], [0, 1, 4], [4, 1, 5], [2, 3, 6], [3, 4, 6], [5, 2, 6], [4, 5, 6]] };
  34287. polyhedra[12] = { vertex: [[-0.669867, 0.334933, -0.529576], [-0.669867, 0.334933, 0.529577], [-0.4043, 1.212901, 0], [-0.334933, -0.669867, -0.529576], [-0.334933, -0.669867, 0.529577], [0.334933, 0.669867, -0.529576], [0.334933, 0.669867, 0.529577], [0.4043, -1.212901, 0], [0.669867, -0.334933, -0.529576], [0.669867, -0.334933, 0.529577]], face: [[8, 9, 7], [6, 5, 2], [3, 8, 7], [5, 0, 2], [4, 3, 7], [0, 1, 2], [9, 4, 7], [1, 6, 2], [9, 8, 5, 6], [8, 3, 0, 5], [3, 4, 1, 0], [4, 9, 6, 1]] };
  34288. polyhedra[13] = { vertex: [[-0.931836, 0.219976, -0.264632], [-0.636706, 0.318353, 0.692816], [-0.613483, -0.735083, -0.264632], [-0.326545, 0.979634, 0], [-0.318353, -0.636706, 0.692816], [-0.159176, 0.477529, -0.856368], [0.159176, -0.477529, -0.856368], [0.318353, 0.636706, 0.692816], [0.326545, -0.979634, 0], [0.613482, 0.735082, -0.264632], [0.636706, -0.318353, 0.692816], [0.931835, -0.219977, -0.264632]], face: [[11, 10, 8], [7, 9, 3], [6, 11, 8], [9, 5, 3], [2, 6, 8], [5, 0, 3], [4, 2, 8], [0, 1, 3], [10, 4, 8], [1, 7, 3], [10, 11, 9, 7], [11, 6, 5, 9], [6, 2, 0, 5], [2, 4, 1, 0], [4, 10, 7, 1]] };
  34289. polyhedra[14] = {
  34290. vertex: [[-0.93465, 0.300459, -0.271185], [-0.838689, -0.260219, -0.516017], [-0.711319, 0.717591, 0.128359], [-0.710334, -0.156922, 0.080946], [-0.599799, 0.556003, -0.725148], [-0.503838, -0.004675, -0.969981], [-0.487004, 0.26021, 0.48049], [-0.460089, -0.750282, -0.512622], [-0.376468, 0.973135, -0.325605], [-0.331735, -0.646985, 0.084342], [-0.254001, 0.831847, 0.530001], [-0.125239, -0.494738, -0.966586], [0.029622, 0.027949, 0.730817], [0.056536, -0.982543, -0.262295], [0.08085, 1.087391, 0.076037], [0.125583, -0.532729, 0.485984], [0.262625, 0.599586, 0.780328], [0.391387, -0.726999, -0.716259], [0.513854, -0.868287, 0.139347], [0.597475, 0.85513, 0.326364], [0.641224, 0.109523, 0.783723], [0.737185, -0.451155, 0.538891], [0.848705, -0.612742, -0.314616], [0.976075, 0.365067, 0.32976], [1.072036, -0.19561, 0.084927]],
  34291. face: [[15, 18, 21], [12, 20, 16], [6, 10, 2], [3, 0, 1], [9, 7, 13], [2, 8, 4, 0], [0, 4, 5, 1], [1, 5, 11, 7], [7, 11, 17, 13], [13, 17, 22, 18], [18, 22, 24, 21], [21, 24, 23, 20], [20, 23, 19, 16], [16, 19, 14, 10], [10, 14, 8, 2], [15, 9, 13, 18], [12, 15, 21, 20], [6, 12, 16, 10], [3, 6, 2, 0], [9, 3, 1, 7], [9, 15, 12, 6, 3], [22, 17, 11, 5, 4, 8, 14, 19, 23, 24]]
  34292. };
  34293. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  34294. var size = options.size;
  34295. var sizeX = options.sizeX || size || 1;
  34296. var sizeY = options.sizeY || size || 1;
  34297. var sizeZ = options.sizeZ || size || 1;
  34298. var data = options.custom || polyhedra[type];
  34299. var nbfaces = data.face.length;
  34300. var faceUV = options.faceUV || new Array(nbfaces);
  34301. var faceColors = options.faceColors;
  34302. var flat = (options.flat === undefined) ? true : options.flat;
  34303. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34304. var positions = new Array();
  34305. var indices = new Array();
  34306. var normals = new Array();
  34307. var uvs = new Array();
  34308. var colors = new Array();
  34309. var index = 0;
  34310. var faceIdx = 0; // face cursor in the array "indexes"
  34311. var indexes = new Array();
  34312. var i = 0;
  34313. var f = 0;
  34314. var u, v, ang, x, y, tmp;
  34315. // default face colors and UV if undefined
  34316. if (flat) {
  34317. for (f = 0; f < nbfaces; f++) {
  34318. if (faceColors && faceColors[f] === undefined) {
  34319. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  34320. }
  34321. if (faceUV && faceUV[f] === undefined) {
  34322. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  34323. }
  34324. }
  34325. }
  34326. if (!flat) {
  34327. for (i = 0; i < data.vertex.length; i++) {
  34328. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  34329. uvs.push(0, 0);
  34330. }
  34331. for (f = 0; f < nbfaces; f++) {
  34332. for (i = 0; i < data.face[f].length - 2; i++) {
  34333. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  34334. }
  34335. }
  34336. }
  34337. else {
  34338. for (f = 0; f < nbfaces; f++) {
  34339. var fl = data.face[f].length; // number of vertices of the current face
  34340. ang = 2 * Math.PI / fl;
  34341. x = 0.5 * Math.tan(ang / 2);
  34342. y = 0.5;
  34343. // positions, uvs, colors
  34344. for (i = 0; i < fl; i++) {
  34345. // positions
  34346. positions.push(data.vertex[data.face[f][i]][0] * sizeX, data.vertex[data.face[f][i]][1] * sizeY, data.vertex[data.face[f][i]][2] * sizeZ);
  34347. indexes.push(index);
  34348. index++;
  34349. // uvs
  34350. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  34351. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  34352. uvs.push(u, v);
  34353. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  34354. y = x * Math.sin(ang) + y * Math.cos(ang);
  34355. x = tmp;
  34356. // colors
  34357. if (faceColors) {
  34358. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  34359. }
  34360. }
  34361. // indices from indexes
  34362. for (i = 0; i < fl - 2; i++) {
  34363. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  34364. }
  34365. faceIdx += fl;
  34366. }
  34367. }
  34368. VertexData.ComputeNormals(positions, indices, normals);
  34369. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34370. var vertexData = new VertexData();
  34371. vertexData.positions = positions;
  34372. vertexData.indices = indices;
  34373. vertexData.normals = normals;
  34374. vertexData.uvs = uvs;
  34375. if (faceColors && flat) {
  34376. vertexData.colors = colors;
  34377. }
  34378. return vertexData;
  34379. };
  34380. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  34381. /**
  34382. * Creates the VertexData of the Torus Knot.
  34383. */
  34384. VertexData.CreateTorusKnot = function (options) {
  34385. var indices = new Array();
  34386. var positions = new Array();
  34387. var normals = new Array();
  34388. var uvs = new Array();
  34389. var radius = options.radius || 2;
  34390. var tube = options.tube || 0.5;
  34391. var radialSegments = options.radialSegments || 32;
  34392. var tubularSegments = options.tubularSegments || 32;
  34393. var p = options.p || 2;
  34394. var q = options.q || 3;
  34395. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34396. // Helper
  34397. var getPos = function (angle) {
  34398. var cu = Math.cos(angle);
  34399. var su = Math.sin(angle);
  34400. var quOverP = q / p * angle;
  34401. var cs = Math.cos(quOverP);
  34402. var tx = radius * (2 + cs) * 0.5 * cu;
  34403. var ty = radius * (2 + cs) * su * 0.5;
  34404. var tz = radius * Math.sin(quOverP) * 0.5;
  34405. return new BABYLON.Vector3(tx, ty, tz);
  34406. };
  34407. // Vertices
  34408. var i;
  34409. var j;
  34410. for (i = 0; i <= radialSegments; i++) {
  34411. var modI = i % radialSegments;
  34412. var u = modI / radialSegments * 2 * p * Math.PI;
  34413. var p1 = getPos(u);
  34414. var p2 = getPos(u + 0.01);
  34415. var tang = p2.subtract(p1);
  34416. var n = p2.add(p1);
  34417. var bitan = BABYLON.Vector3.Cross(tang, n);
  34418. n = BABYLON.Vector3.Cross(bitan, tang);
  34419. bitan.normalize();
  34420. n.normalize();
  34421. for (j = 0; j < tubularSegments; j++) {
  34422. var modJ = j % tubularSegments;
  34423. var v = modJ / tubularSegments * 2 * Math.PI;
  34424. var cx = -tube * Math.cos(v);
  34425. var cy = tube * Math.sin(v);
  34426. positions.push(p1.x + cx * n.x + cy * bitan.x);
  34427. positions.push(p1.y + cx * n.y + cy * bitan.y);
  34428. positions.push(p1.z + cx * n.z + cy * bitan.z);
  34429. uvs.push(i / radialSegments);
  34430. uvs.push(j / tubularSegments);
  34431. }
  34432. }
  34433. for (i = 0; i < radialSegments; i++) {
  34434. for (j = 0; j < tubularSegments; j++) {
  34435. var jNext = (j + 1) % tubularSegments;
  34436. var a = i * tubularSegments + j;
  34437. var b = (i + 1) * tubularSegments + j;
  34438. var c = (i + 1) * tubularSegments + jNext;
  34439. var d = i * tubularSegments + jNext;
  34440. indices.push(d);
  34441. indices.push(b);
  34442. indices.push(a);
  34443. indices.push(d);
  34444. indices.push(c);
  34445. indices.push(b);
  34446. }
  34447. }
  34448. // Normals
  34449. VertexData.ComputeNormals(positions, indices, normals);
  34450. // Sides
  34451. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34452. // Result
  34453. var vertexData = new VertexData();
  34454. vertexData.indices = indices;
  34455. vertexData.positions = positions;
  34456. vertexData.normals = normals;
  34457. vertexData.uvs = uvs;
  34458. return vertexData;
  34459. };
  34460. // Tools
  34461. /**
  34462. * @param {any} - positions (number[] or Float32Array)
  34463. * @param {any} - indices (number[] or Uint16Array)
  34464. * @param {any} - normals (number[] or Float32Array)
  34465. * options (optional) :
  34466. * facetPositions : optional array of facet positions (vector3)
  34467. * facetNormals : optional array of facet normals (vector3)
  34468. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  34469. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  34470. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  34471. * bbSize : optional bounding box size data, required for facetPartitioning computation
  34472. * bInfo : optional bounding info, required for facetPartitioning computation
  34473. * useRightHandedSystem: optional boolean to for right handed system computation
  34474. * depthSort : optional boolean to enable the facet depth sort computation
  34475. * distanceTo : optional Vector3 to compute the facet depth from this location
  34476. * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  34477. */
  34478. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  34479. // temporary scalar variables
  34480. var index = 0; // facet index
  34481. var p1p2x = 0.0; // p1p2 vector x coordinate
  34482. var p1p2y = 0.0; // p1p2 vector y coordinate
  34483. var p1p2z = 0.0; // p1p2 vector z coordinate
  34484. var p3p2x = 0.0; // p3p2 vector x coordinate
  34485. var p3p2y = 0.0; // p3p2 vector y coordinate
  34486. var p3p2z = 0.0; // p3p2 vector z coordinate
  34487. var faceNormalx = 0.0; // facet normal x coordinate
  34488. var faceNormaly = 0.0; // facet normal y coordinate
  34489. var faceNormalz = 0.0; // facet normal z coordinate
  34490. var length = 0.0; // facet normal length before normalization
  34491. var v1x = 0; // vector1 x index in the positions array
  34492. var v1y = 0; // vector1 y index in the positions array
  34493. var v1z = 0; // vector1 z index in the positions array
  34494. var v2x = 0; // vector2 x index in the positions array
  34495. var v2y = 0; // vector2 y index in the positions array
  34496. var v2z = 0; // vector2 z index in the positions array
  34497. var v3x = 0; // vector3 x index in the positions array
  34498. var v3y = 0; // vector3 y index in the positions array
  34499. var v3z = 0; // vector3 z index in the positions array
  34500. var computeFacetNormals = false;
  34501. var computeFacetPositions = false;
  34502. var computeFacetPartitioning = false;
  34503. var computeDepthSort = false;
  34504. var faceNormalSign = 1;
  34505. var ratio = 0;
  34506. var distanceTo = null;
  34507. if (options) {
  34508. computeFacetNormals = (options.facetNormals) ? true : false;
  34509. computeFacetPositions = (options.facetPositions) ? true : false;
  34510. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  34511. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  34512. ratio = options.ratio || 0;
  34513. computeDepthSort = (options.depthSort) ? true : false;
  34514. distanceTo = (options.distanceTo);
  34515. if (computeDepthSort) {
  34516. if (distanceTo === undefined) {
  34517. distanceTo = BABYLON.Vector3.Zero();
  34518. }
  34519. var depthSortedFacets = options.depthSortedFacets;
  34520. }
  34521. }
  34522. // facetPartitioning reinit if needed
  34523. var xSubRatio = 0;
  34524. var ySubRatio = 0;
  34525. var zSubRatio = 0;
  34526. var subSq = 0;
  34527. if (computeFacetPartitioning && options && options.bbSize) {
  34528. var ox = 0; // X partitioning index for facet position
  34529. var oy = 0; // Y partinioning index for facet position
  34530. var oz = 0; // Z partinioning index for facet position
  34531. var b1x = 0; // X partitioning index for facet v1 vertex
  34532. var b1y = 0; // Y partitioning index for facet v1 vertex
  34533. var b1z = 0; // z partitioning index for facet v1 vertex
  34534. var b2x = 0; // X partitioning index for facet v2 vertex
  34535. var b2y = 0; // Y partitioning index for facet v2 vertex
  34536. var b2z = 0; // Z partitioning index for facet v2 vertex
  34537. var b3x = 0; // X partitioning index for facet v3 vertex
  34538. var b3y = 0; // Y partitioning index for facet v3 vertex
  34539. var b3z = 0; // Z partitioning index for facet v3 vertex
  34540. var block_idx_o = 0; // facet barycenter block index
  34541. var block_idx_v1 = 0; // v1 vertex block index
  34542. var block_idx_v2 = 0; // v2 vertex block index
  34543. var block_idx_v3 = 0; // v3 vertex block index
  34544. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  34545. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  34546. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  34547. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  34548. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  34549. subSq = options.subDiv.max * options.subDiv.max;
  34550. options.facetPartitioning.length = 0;
  34551. }
  34552. // reset the normals
  34553. for (index = 0; index < positions.length; index++) {
  34554. normals[index] = 0.0;
  34555. }
  34556. // Loop : 1 indice triplet = 1 facet
  34557. var nbFaces = (indices.length / 3) | 0;
  34558. for (index = 0; index < nbFaces; index++) {
  34559. // get the indexes of the coordinates of each vertex of the facet
  34560. v1x = indices[index * 3] * 3;
  34561. v1y = v1x + 1;
  34562. v1z = v1x + 2;
  34563. v2x = indices[index * 3 + 1] * 3;
  34564. v2y = v2x + 1;
  34565. v2z = v2x + 2;
  34566. v3x = indices[index * 3 + 2] * 3;
  34567. v3y = v3x + 1;
  34568. v3z = v3x + 2;
  34569. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  34570. p1p2y = positions[v1y] - positions[v2y];
  34571. p1p2z = positions[v1z] - positions[v2z];
  34572. p3p2x = positions[v3x] - positions[v2x];
  34573. p3p2y = positions[v3y] - positions[v2y];
  34574. p3p2z = positions[v3z] - positions[v2z];
  34575. // compute the face normal with the cross product
  34576. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  34577. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  34578. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  34579. // normalize this normal and store it in the array facetData
  34580. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  34581. length = (length === 0) ? 1.0 : length;
  34582. faceNormalx /= length;
  34583. faceNormaly /= length;
  34584. faceNormalz /= length;
  34585. if (computeFacetNormals && options) {
  34586. options.facetNormals[index].x = faceNormalx;
  34587. options.facetNormals[index].y = faceNormaly;
  34588. options.facetNormals[index].z = faceNormalz;
  34589. }
  34590. if (computeFacetPositions && options) {
  34591. // compute and the facet barycenter coordinates in the array facetPositions
  34592. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  34593. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  34594. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  34595. }
  34596. if (computeFacetPartitioning && options) {
  34597. // store the facet indexes in arrays in the main facetPartitioning array :
  34598. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  34599. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  34600. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  34601. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  34602. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  34603. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  34604. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  34605. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  34606. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  34607. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  34608. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  34609. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  34610. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  34611. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  34612. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  34613. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  34614. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  34615. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  34616. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  34617. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  34618. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  34619. // push each facet index in each block containing the vertex
  34620. options.facetPartitioning[block_idx_v1].push(index);
  34621. if (block_idx_v2 != block_idx_v1) {
  34622. options.facetPartitioning[block_idx_v2].push(index);
  34623. }
  34624. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  34625. options.facetPartitioning[block_idx_v3].push(index);
  34626. }
  34627. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  34628. options.facetPartitioning[block_idx_o].push(index);
  34629. }
  34630. }
  34631. if (computeDepthSort && options && options.facetPositions) {
  34632. var dsf = depthSortedFacets[index];
  34633. dsf.ind = index * 3;
  34634. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  34635. }
  34636. // compute the normals anyway
  34637. normals[v1x] += faceNormalx; // accumulate all the normals per face
  34638. normals[v1y] += faceNormaly;
  34639. normals[v1z] += faceNormalz;
  34640. normals[v2x] += faceNormalx;
  34641. normals[v2y] += faceNormaly;
  34642. normals[v2z] += faceNormalz;
  34643. normals[v3x] += faceNormalx;
  34644. normals[v3y] += faceNormaly;
  34645. normals[v3z] += faceNormalz;
  34646. }
  34647. // last normalization of each normal
  34648. for (index = 0; index < normals.length / 3; index++) {
  34649. faceNormalx = normals[index * 3];
  34650. faceNormaly = normals[index * 3 + 1];
  34651. faceNormalz = normals[index * 3 + 2];
  34652. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  34653. length = (length === 0) ? 1.0 : length;
  34654. faceNormalx /= length;
  34655. faceNormaly /= length;
  34656. faceNormalz /= length;
  34657. normals[index * 3] = faceNormalx;
  34658. normals[index * 3 + 1] = faceNormaly;
  34659. normals[index * 3 + 2] = faceNormalz;
  34660. }
  34661. };
  34662. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  34663. var li = indices.length;
  34664. var ln = normals.length;
  34665. var i;
  34666. var n;
  34667. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34668. switch (sideOrientation) {
  34669. case BABYLON.Mesh.FRONTSIDE:
  34670. // nothing changed
  34671. break;
  34672. case BABYLON.Mesh.BACKSIDE:
  34673. var tmp;
  34674. // indices
  34675. for (i = 0; i < li; i += 3) {
  34676. tmp = indices[i];
  34677. indices[i] = indices[i + 2];
  34678. indices[i + 2] = tmp;
  34679. }
  34680. // normals
  34681. for (n = 0; n < ln; n++) {
  34682. normals[n] = -normals[n];
  34683. }
  34684. break;
  34685. case BABYLON.Mesh.DOUBLESIDE:
  34686. // positions
  34687. var lp = positions.length;
  34688. var l = lp / 3;
  34689. for (var p = 0; p < lp; p++) {
  34690. positions[lp + p] = positions[p];
  34691. }
  34692. // indices
  34693. for (i = 0; i < li; i += 3) {
  34694. indices[i + li] = indices[i + 2] + l;
  34695. indices[i + 1 + li] = indices[i + 1] + l;
  34696. indices[i + 2 + li] = indices[i] + l;
  34697. }
  34698. // normals
  34699. for (n = 0; n < ln; n++) {
  34700. normals[ln + n] = -normals[n];
  34701. }
  34702. // uvs
  34703. var lu = uvs.length;
  34704. var u = 0;
  34705. for (u = 0; u < lu; u++) {
  34706. uvs[u + lu] = uvs[u];
  34707. }
  34708. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  34709. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  34710. u = 0;
  34711. for (i = 0; i < lu / 2; i++) {
  34712. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  34713. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  34714. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  34715. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  34716. u += 2;
  34717. }
  34718. break;
  34719. }
  34720. };
  34721. /**
  34722. * Creates a new VertexData from the imported parameters.
  34723. */
  34724. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  34725. var vertexData = new VertexData();
  34726. // positions
  34727. var positions = parsedVertexData.positions;
  34728. if (positions) {
  34729. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  34730. }
  34731. // normals
  34732. var normals = parsedVertexData.normals;
  34733. if (normals) {
  34734. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  34735. }
  34736. // tangents
  34737. var tangents = parsedVertexData.tangents;
  34738. if (tangents) {
  34739. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  34740. }
  34741. // uvs
  34742. var uvs = parsedVertexData.uvs;
  34743. if (uvs) {
  34744. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  34745. }
  34746. // uv2s
  34747. var uv2s = parsedVertexData.uv2s;
  34748. if (uv2s) {
  34749. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  34750. }
  34751. // uv3s
  34752. var uv3s = parsedVertexData.uv3s;
  34753. if (uv3s) {
  34754. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  34755. }
  34756. // uv4s
  34757. var uv4s = parsedVertexData.uv4s;
  34758. if (uv4s) {
  34759. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  34760. }
  34761. // uv5s
  34762. var uv5s = parsedVertexData.uv5s;
  34763. if (uv5s) {
  34764. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  34765. }
  34766. // uv6s
  34767. var uv6s = parsedVertexData.uv6s;
  34768. if (uv6s) {
  34769. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  34770. }
  34771. // colors
  34772. var colors = parsedVertexData.colors;
  34773. if (colors) {
  34774. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  34775. }
  34776. // matricesIndices
  34777. var matricesIndices = parsedVertexData.matricesIndices;
  34778. if (matricesIndices) {
  34779. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  34780. }
  34781. // matricesWeights
  34782. var matricesWeights = parsedVertexData.matricesWeights;
  34783. if (matricesWeights) {
  34784. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  34785. }
  34786. // indices
  34787. var indices = parsedVertexData.indices;
  34788. if (indices) {
  34789. vertexData.indices = indices;
  34790. }
  34791. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  34792. };
  34793. return VertexData;
  34794. }());
  34795. BABYLON.VertexData = VertexData;
  34796. })(BABYLON || (BABYLON = {}));
  34797. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  34798. var BABYLON;
  34799. (function (BABYLON) {
  34800. /**
  34801. * Class used to store geometry data (vertex buffers + index buffer)
  34802. */
  34803. var Geometry = /** @class */ (function () {
  34804. /**
  34805. * Creates a new geometry
  34806. * @param id defines the unique ID
  34807. * @param scene defines the hosting scene
  34808. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  34809. * @param updatable defines if geometry must be updatable (false by default)
  34810. * @param mesh defines the mesh that will be associated with the geometry
  34811. */
  34812. function Geometry(id, scene, vertexData, updatable, mesh) {
  34813. if (updatable === void 0) { updatable = false; }
  34814. if (mesh === void 0) { mesh = null; }
  34815. /**
  34816. * Gets the delay loading state of the geometry (none by default which means not delayed)
  34817. */
  34818. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  34819. this._totalVertices = 0;
  34820. this._isDisposed = false;
  34821. this._indexBufferIsUpdatable = false;
  34822. this.id = id;
  34823. this._engine = scene.getEngine();
  34824. this._meshes = [];
  34825. this._scene = scene;
  34826. //Init vertex buffer cache
  34827. this._vertexBuffers = {};
  34828. this._indices = [];
  34829. this._updatable = updatable;
  34830. // vertexData
  34831. if (vertexData) {
  34832. this.setAllVerticesData(vertexData, updatable);
  34833. }
  34834. else {
  34835. this._totalVertices = 0;
  34836. this._indices = [];
  34837. }
  34838. if (this._engine.getCaps().vertexArrayObject) {
  34839. this._vertexArrayObjects = {};
  34840. }
  34841. // applyToMesh
  34842. if (mesh) {
  34843. if (mesh.getClassName() === "LinesMesh") {
  34844. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  34845. this.updateExtend();
  34846. }
  34847. this.applyToMesh(mesh);
  34848. mesh.computeWorldMatrix(true);
  34849. }
  34850. }
  34851. Object.defineProperty(Geometry.prototype, "boundingBias", {
  34852. /**
  34853. * Gets or sets the Bias Vector to apply on the bounding elements (box/sphere), the max extend is computed as v += v * bias.x + bias.y, the min is computed as v -= v * bias.x + bias.y
  34854. */
  34855. get: function () {
  34856. return this._boundingBias;
  34857. },
  34858. /**
  34859. * Gets or sets the Bias Vector to apply on the bounding elements (box/sphere), the max extend is computed as v += v * bias.x + bias.y, the min is computed as v -= v * bias.x + bias.y
  34860. */
  34861. set: function (value) {
  34862. if (this._boundingBias && this._boundingBias.equals(value)) {
  34863. return;
  34864. }
  34865. this._boundingBias = value.clone();
  34866. this.updateBoundingInfo(true, null);
  34867. },
  34868. enumerable: true,
  34869. configurable: true
  34870. });
  34871. /**
  34872. * Static function used to attach a new empty geometry to a mesh
  34873. * @param mesh defines the mesh to attach the geometry to
  34874. * @returns the new {BABYLON.Geometry}
  34875. */
  34876. Geometry.CreateGeometryForMesh = function (mesh) {
  34877. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  34878. geometry.applyToMesh(mesh);
  34879. return geometry;
  34880. };
  34881. Object.defineProperty(Geometry.prototype, "extend", {
  34882. /**
  34883. * Gets the current extend of the geometry
  34884. */
  34885. get: function () {
  34886. return this._extend;
  34887. },
  34888. enumerable: true,
  34889. configurable: true
  34890. });
  34891. /**
  34892. * Gets the hosting scene
  34893. * @returns the hosting {BABYLON.Scene}
  34894. */
  34895. Geometry.prototype.getScene = function () {
  34896. return this._scene;
  34897. };
  34898. /**
  34899. * Gets the hosting engine
  34900. * @returns the hosting {BABYLON.Engine}
  34901. */
  34902. Geometry.prototype.getEngine = function () {
  34903. return this._engine;
  34904. };
  34905. /**
  34906. * Defines if the geometry is ready to use
  34907. * @returns true if the geometry is ready to be used
  34908. */
  34909. Geometry.prototype.isReady = function () {
  34910. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  34911. };
  34912. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  34913. /**
  34914. * Gets a value indicating that the geometry should not be serialized
  34915. */
  34916. get: function () {
  34917. for (var index = 0; index < this._meshes.length; index++) {
  34918. if (!this._meshes[index].doNotSerialize) {
  34919. return false;
  34920. }
  34921. }
  34922. return true;
  34923. },
  34924. enumerable: true,
  34925. configurable: true
  34926. });
  34927. /** @ignore */
  34928. Geometry.prototype._rebuild = function () {
  34929. if (this._vertexArrayObjects) {
  34930. this._vertexArrayObjects = {};
  34931. }
  34932. // Index buffer
  34933. if (this._meshes.length !== 0 && this._indices) {
  34934. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  34935. }
  34936. // Vertex buffers
  34937. for (var key in this._vertexBuffers) {
  34938. var vertexBuffer = this._vertexBuffers[key];
  34939. vertexBuffer._rebuild();
  34940. }
  34941. };
  34942. /**
  34943. * Affects all gemetry data in one call
  34944. * @param vertexData defines the geometry data
  34945. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  34946. */
  34947. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  34948. vertexData.applyToGeometry(this, updatable);
  34949. this.notifyUpdate();
  34950. };
  34951. /**
  34952. * Set specific vertex data
  34953. * @param kind defines the data kind (Position, normal, etc...)
  34954. * @param data defines the vertex data to use
  34955. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  34956. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  34957. */
  34958. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  34959. if (updatable === void 0) { updatable = false; }
  34960. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  34961. this.setVerticesBuffer(buffer);
  34962. };
  34963. /**
  34964. * Removes a specific vertex data
  34965. * @param kind defines the data kind (Position, normal, etc...)
  34966. */
  34967. Geometry.prototype.removeVerticesData = function (kind) {
  34968. if (this._vertexBuffers[kind]) {
  34969. this._vertexBuffers[kind].dispose();
  34970. delete this._vertexBuffers[kind];
  34971. }
  34972. };
  34973. /**
  34974. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  34975. * @param buffer defines the vertex buffer to use
  34976. */
  34977. Geometry.prototype.setVerticesBuffer = function (buffer) {
  34978. var kind = buffer.getKind();
  34979. if (this._vertexBuffers[kind]) {
  34980. this._vertexBuffers[kind].dispose();
  34981. }
  34982. this._vertexBuffers[kind] = buffer;
  34983. if (kind === BABYLON.VertexBuffer.PositionKind) {
  34984. var data = buffer.getData();
  34985. var stride = buffer.getStrideSize();
  34986. this._totalVertices = data.length / stride;
  34987. this.updateExtend(data, stride);
  34988. this._resetPointsArrayCache();
  34989. var meshes = this._meshes;
  34990. var numOfMeshes = meshes.length;
  34991. for (var index = 0; index < numOfMeshes; index++) {
  34992. var mesh = meshes[index];
  34993. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  34994. mesh._createGlobalSubMesh(false);
  34995. mesh.computeWorldMatrix(true);
  34996. }
  34997. }
  34998. this.notifyUpdate(kind);
  34999. if (this._vertexArrayObjects) {
  35000. this._disposeVertexArrayObjects();
  35001. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  35002. }
  35003. };
  35004. /**
  35005. * Update a specific vertex buffer
  35006. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  35007. * It will do nothing if the buffer is not updatable
  35008. * @param kind defines the data kind (Position, normal, etc...)
  35009. * @param data defines the data to use
  35010. * @param offset defines the offset in the target buffer where to store the data
  35011. */
  35012. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  35013. var vertexBuffer = this.getVertexBuffer(kind);
  35014. if (!vertexBuffer) {
  35015. return;
  35016. }
  35017. vertexBuffer.updateDirectly(data, offset);
  35018. this.notifyUpdate(kind);
  35019. };
  35020. /**
  35021. * Update a specific vertex buffer
  35022. * This function will create a new buffer if the current one is not updatable
  35023. * @param kind defines the data kind (Position, normal, etc...)
  35024. * @param data defines the data to use
  35025. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  35026. */
  35027. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  35028. if (updateExtends === void 0) { updateExtends = false; }
  35029. var vertexBuffer = this.getVertexBuffer(kind);
  35030. if (!vertexBuffer) {
  35031. return;
  35032. }
  35033. vertexBuffer.update(data);
  35034. if (kind === BABYLON.VertexBuffer.PositionKind) {
  35035. var stride = vertexBuffer.getStrideSize();
  35036. this._totalVertices = data.length / stride;
  35037. this.updateBoundingInfo(updateExtends, data);
  35038. }
  35039. this.notifyUpdate(kind);
  35040. };
  35041. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  35042. if (updateExtends) {
  35043. this.updateExtend(data);
  35044. }
  35045. var meshes = this._meshes;
  35046. var numOfMeshes = meshes.length;
  35047. this._resetPointsArrayCache();
  35048. for (var index = 0; index < numOfMeshes; index++) {
  35049. var mesh = meshes[index];
  35050. if (updateExtends) {
  35051. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  35052. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  35053. var subMesh = mesh.subMeshes[subIndex];
  35054. subMesh.refreshBoundingInfo();
  35055. }
  35056. }
  35057. }
  35058. };
  35059. /** @ignore */
  35060. Geometry.prototype._bind = function (effect, indexToBind) {
  35061. if (!effect) {
  35062. return;
  35063. }
  35064. if (indexToBind === undefined) {
  35065. indexToBind = this._indexBuffer;
  35066. }
  35067. var vbs = this.getVertexBuffers();
  35068. if (!vbs) {
  35069. return;
  35070. }
  35071. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  35072. this._engine.bindBuffers(vbs, indexToBind, effect);
  35073. return;
  35074. }
  35075. // Using VAO
  35076. if (!this._vertexArrayObjects[effect.key]) {
  35077. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  35078. }
  35079. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  35080. };
  35081. /**
  35082. * Gets total number of vertices
  35083. * @returns the total number of vertices
  35084. */
  35085. Geometry.prototype.getTotalVertices = function () {
  35086. if (!this.isReady()) {
  35087. return 0;
  35088. }
  35089. return this._totalVertices;
  35090. };
  35091. /**
  35092. * Gets a specific vertex data attached to this geometry
  35093. * @param kind defines the data kind (Position, normal, etc...)
  35094. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  35095. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  35096. * @returns a float array containing vertex data
  35097. */
  35098. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  35099. var vertexBuffer = this.getVertexBuffer(kind);
  35100. if (!vertexBuffer) {
  35101. return null;
  35102. }
  35103. var orig = vertexBuffer.getData();
  35104. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  35105. return orig;
  35106. }
  35107. else {
  35108. var len = orig.length;
  35109. var copy = [];
  35110. for (var i = 0; i < len; i++) {
  35111. copy.push(orig[i]);
  35112. }
  35113. return copy;
  35114. }
  35115. };
  35116. /**
  35117. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  35118. * @param kind defines the data kind (Position, normal, etc...)
  35119. * @returns true if the vertex buffer with the specified kind is updatable
  35120. */
  35121. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  35122. var vb = this._vertexBuffers[kind];
  35123. if (!vb) {
  35124. return false;
  35125. }
  35126. return vb.isUpdatable();
  35127. };
  35128. /**
  35129. * Gets a specific vertex buffer
  35130. * @param kind defines the data kind (Position, normal, etc...)
  35131. * @returns a {BABYLON.VertexBuffer}
  35132. */
  35133. Geometry.prototype.getVertexBuffer = function (kind) {
  35134. if (!this.isReady()) {
  35135. return null;
  35136. }
  35137. return this._vertexBuffers[kind];
  35138. };
  35139. /**
  35140. * Returns all vertex buffers
  35141. * @return an object holding all vertex buffers indexed by kind
  35142. */
  35143. Geometry.prototype.getVertexBuffers = function () {
  35144. if (!this.isReady()) {
  35145. return null;
  35146. }
  35147. return this._vertexBuffers;
  35148. };
  35149. /**
  35150. * Gets a boolean indicating if specific vertex buffer is present
  35151. * @param kind defines the data kind (Position, normal, etc...)
  35152. * @returns true if data is present
  35153. */
  35154. Geometry.prototype.isVerticesDataPresent = function (kind) {
  35155. if (!this._vertexBuffers) {
  35156. if (this._delayInfo) {
  35157. return this._delayInfo.indexOf(kind) !== -1;
  35158. }
  35159. return false;
  35160. }
  35161. return this._vertexBuffers[kind] !== undefined;
  35162. };
  35163. /**
  35164. * Gets a list of all attached data kinds (Position, normal, etc...)
  35165. * @returns a list of string containing all kinds
  35166. */
  35167. Geometry.prototype.getVerticesDataKinds = function () {
  35168. var result = [];
  35169. var kind;
  35170. if (!this._vertexBuffers && this._delayInfo) {
  35171. for (kind in this._delayInfo) {
  35172. result.push(kind);
  35173. }
  35174. }
  35175. else {
  35176. for (kind in this._vertexBuffers) {
  35177. result.push(kind);
  35178. }
  35179. }
  35180. return result;
  35181. };
  35182. /**
  35183. * Update index buffer
  35184. * @param indices defines the indices to store in the index buffer
  35185. * @param offset defines the offset in the target buffer where to store the data
  35186. */
  35187. Geometry.prototype.updateIndices = function (indices, offset) {
  35188. if (!this._indexBuffer) {
  35189. return;
  35190. }
  35191. if (!this._indexBufferIsUpdatable) {
  35192. this.setIndices(indices, null, true);
  35193. }
  35194. else {
  35195. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  35196. }
  35197. };
  35198. /**
  35199. * Creates a new index buffer
  35200. * @param indices defines the indices to store in the index buffer
  35201. * @param totalVertices defines the total number of vertices (could be null)
  35202. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  35203. */
  35204. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  35205. if (totalVertices === void 0) { totalVertices = null; }
  35206. if (updatable === void 0) { updatable = false; }
  35207. if (this._indexBuffer) {
  35208. this._engine._releaseBuffer(this._indexBuffer);
  35209. }
  35210. this._disposeVertexArrayObjects();
  35211. this._indices = indices;
  35212. this._indexBufferIsUpdatable = updatable;
  35213. if (this._meshes.length !== 0 && this._indices) {
  35214. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  35215. }
  35216. if (totalVertices != undefined) {
  35217. this._totalVertices = totalVertices;
  35218. }
  35219. var meshes = this._meshes;
  35220. var numOfMeshes = meshes.length;
  35221. for (var index = 0; index < numOfMeshes; index++) {
  35222. meshes[index]._createGlobalSubMesh(true);
  35223. }
  35224. this.notifyUpdate();
  35225. };
  35226. /**
  35227. * Return the total number of indices
  35228. * @returns the total number of indices
  35229. */
  35230. Geometry.prototype.getTotalIndices = function () {
  35231. if (!this.isReady()) {
  35232. return 0;
  35233. }
  35234. return this._indices.length;
  35235. };
  35236. /**
  35237. * Gets the index buffer array
  35238. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  35239. * @returns the index buffer array
  35240. */
  35241. Geometry.prototype.getIndices = function (copyWhenShared) {
  35242. if (!this.isReady()) {
  35243. return null;
  35244. }
  35245. var orig = this._indices;
  35246. if (!copyWhenShared || this._meshes.length === 1) {
  35247. return orig;
  35248. }
  35249. else {
  35250. var len = orig.length;
  35251. var copy = [];
  35252. for (var i = 0; i < len; i++) {
  35253. copy.push(orig[i]);
  35254. }
  35255. return copy;
  35256. }
  35257. };
  35258. /**
  35259. * Gets the index buffer
  35260. * @return the index buffer
  35261. */
  35262. Geometry.prototype.getIndexBuffer = function () {
  35263. if (!this.isReady()) {
  35264. return null;
  35265. }
  35266. return this._indexBuffer;
  35267. };
  35268. /** @ignore */
  35269. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  35270. if (effect === void 0) { effect = null; }
  35271. if (!effect || !this._vertexArrayObjects) {
  35272. return;
  35273. }
  35274. if (this._vertexArrayObjects[effect.key]) {
  35275. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  35276. delete this._vertexArrayObjects[effect.key];
  35277. }
  35278. };
  35279. /**
  35280. * Release the associated resources for a specific mesh
  35281. * @param mesh defines the source mesh
  35282. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  35283. */
  35284. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  35285. var meshes = this._meshes;
  35286. var index = meshes.indexOf(mesh);
  35287. if (index === -1) {
  35288. return;
  35289. }
  35290. meshes.splice(index, 1);
  35291. mesh._geometry = null;
  35292. if (meshes.length === 0 && shouldDispose) {
  35293. this.dispose();
  35294. }
  35295. };
  35296. /**
  35297. * Apply current geometry to a given mesh
  35298. * @param mesh defines the mesh to apply geometry to
  35299. */
  35300. Geometry.prototype.applyToMesh = function (mesh) {
  35301. if (mesh._geometry === this) {
  35302. return;
  35303. }
  35304. var previousGeometry = mesh._geometry;
  35305. if (previousGeometry) {
  35306. previousGeometry.releaseForMesh(mesh);
  35307. }
  35308. var meshes = this._meshes;
  35309. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  35310. mesh._geometry = this;
  35311. this._scene.pushGeometry(this);
  35312. meshes.push(mesh);
  35313. if (this.isReady()) {
  35314. this._applyToMesh(mesh);
  35315. }
  35316. else {
  35317. mesh._boundingInfo = this._boundingInfo;
  35318. }
  35319. };
  35320. Geometry.prototype.updateExtend = function (data, stride) {
  35321. if (data === void 0) { data = null; }
  35322. if (!data) {
  35323. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  35324. }
  35325. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  35326. };
  35327. Geometry.prototype._applyToMesh = function (mesh) {
  35328. var numOfMeshes = this._meshes.length;
  35329. // vertexBuffers
  35330. for (var kind in this._vertexBuffers) {
  35331. if (numOfMeshes === 1) {
  35332. this._vertexBuffers[kind].create();
  35333. }
  35334. var buffer = this._vertexBuffers[kind].getBuffer();
  35335. if (buffer)
  35336. buffer.references = numOfMeshes;
  35337. if (kind === BABYLON.VertexBuffer.PositionKind) {
  35338. if (!this._extend) {
  35339. this.updateExtend(this._vertexBuffers[kind].getData());
  35340. }
  35341. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  35342. mesh._createGlobalSubMesh(false);
  35343. //bounding info was just created again, world matrix should be applied again.
  35344. mesh._updateBoundingInfo();
  35345. }
  35346. }
  35347. // indexBuffer
  35348. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  35349. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  35350. }
  35351. if (this._indexBuffer) {
  35352. this._indexBuffer.references = numOfMeshes;
  35353. }
  35354. };
  35355. Geometry.prototype.notifyUpdate = function (kind) {
  35356. if (this.onGeometryUpdated) {
  35357. this.onGeometryUpdated(this, kind);
  35358. }
  35359. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  35360. var mesh = _a[_i];
  35361. mesh._markSubMeshesAsAttributesDirty();
  35362. }
  35363. };
  35364. /**
  35365. * Load the geometry if it was flagged as delay loaded
  35366. * @param scene defines the hosting scene
  35367. * @param onLoaded defines a callback called when the geometry is loaded
  35368. */
  35369. Geometry.prototype.load = function (scene, onLoaded) {
  35370. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  35371. return;
  35372. }
  35373. if (this.isReady()) {
  35374. if (onLoaded) {
  35375. onLoaded();
  35376. }
  35377. return;
  35378. }
  35379. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  35380. this._queueLoad(scene, onLoaded);
  35381. };
  35382. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  35383. var _this = this;
  35384. if (!this.delayLoadingFile) {
  35385. return;
  35386. }
  35387. scene._addPendingData(this);
  35388. scene._loadFile(this.delayLoadingFile, function (data) {
  35389. if (!_this._delayLoadingFunction) {
  35390. return;
  35391. }
  35392. _this._delayLoadingFunction(JSON.parse(data), _this);
  35393. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  35394. _this._delayInfo = [];
  35395. scene._removePendingData(_this);
  35396. var meshes = _this._meshes;
  35397. var numOfMeshes = meshes.length;
  35398. for (var index = 0; index < numOfMeshes; index++) {
  35399. _this._applyToMesh(meshes[index]);
  35400. }
  35401. if (onLoaded) {
  35402. onLoaded();
  35403. }
  35404. }, undefined, true);
  35405. };
  35406. /**
  35407. * Invert the geometry to move from a right handed system to a left handed one.
  35408. */
  35409. Geometry.prototype.toLeftHanded = function () {
  35410. // Flip faces
  35411. var tIndices = this.getIndices(false);
  35412. if (tIndices != null && tIndices.length > 0) {
  35413. for (var i = 0; i < tIndices.length; i += 3) {
  35414. var tTemp = tIndices[i + 0];
  35415. tIndices[i + 0] = tIndices[i + 2];
  35416. tIndices[i + 2] = tTemp;
  35417. }
  35418. this.setIndices(tIndices);
  35419. }
  35420. // Negate position.z
  35421. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  35422. if (tPositions != null && tPositions.length > 0) {
  35423. for (var i = 0; i < tPositions.length; i += 3) {
  35424. tPositions[i + 2] = -tPositions[i + 2];
  35425. }
  35426. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  35427. }
  35428. // Negate normal.z
  35429. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  35430. if (tNormals != null && tNormals.length > 0) {
  35431. for (var i = 0; i < tNormals.length; i += 3) {
  35432. tNormals[i + 2] = -tNormals[i + 2];
  35433. }
  35434. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  35435. }
  35436. };
  35437. // Cache
  35438. /** @ignore */
  35439. Geometry.prototype._resetPointsArrayCache = function () {
  35440. this._positions = null;
  35441. };
  35442. /** @ignore */
  35443. Geometry.prototype._generatePointsArray = function () {
  35444. if (this._positions)
  35445. return true;
  35446. this._positions = [];
  35447. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  35448. if (!data) {
  35449. return false;
  35450. }
  35451. for (var index = 0; index < data.length; index += 3) {
  35452. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  35453. }
  35454. return true;
  35455. };
  35456. /**
  35457. * Gets a value indicating if the geometry is disposed
  35458. * @returns true if the geometry was disposed
  35459. */
  35460. Geometry.prototype.isDisposed = function () {
  35461. return this._isDisposed;
  35462. };
  35463. Geometry.prototype._disposeVertexArrayObjects = function () {
  35464. if (this._vertexArrayObjects) {
  35465. for (var kind in this._vertexArrayObjects) {
  35466. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  35467. }
  35468. this._vertexArrayObjects = {};
  35469. }
  35470. };
  35471. /**
  35472. * Free all associated resources
  35473. */
  35474. Geometry.prototype.dispose = function () {
  35475. var meshes = this._meshes;
  35476. var numOfMeshes = meshes.length;
  35477. var index;
  35478. for (index = 0; index < numOfMeshes; index++) {
  35479. this.releaseForMesh(meshes[index]);
  35480. }
  35481. this._meshes = [];
  35482. this._disposeVertexArrayObjects();
  35483. for (var kind in this._vertexBuffers) {
  35484. this._vertexBuffers[kind].dispose();
  35485. }
  35486. this._vertexBuffers = {};
  35487. this._totalVertices = 0;
  35488. if (this._indexBuffer) {
  35489. this._engine._releaseBuffer(this._indexBuffer);
  35490. }
  35491. this._indexBuffer = null;
  35492. this._indices = [];
  35493. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  35494. this.delayLoadingFile = null;
  35495. this._delayLoadingFunction = null;
  35496. this._delayInfo = [];
  35497. this._boundingInfo = null;
  35498. this._scene.removeGeometry(this);
  35499. this._isDisposed = true;
  35500. };
  35501. /**
  35502. * Clone the current geometry into a new geometry
  35503. * @param id defines the unique ID of the new geometry
  35504. * @returns a new geometry object
  35505. */
  35506. Geometry.prototype.copy = function (id) {
  35507. var vertexData = new BABYLON.VertexData();
  35508. vertexData.indices = [];
  35509. var indices = this.getIndices();
  35510. if (indices) {
  35511. for (var index = 0; index < indices.length; index++) {
  35512. vertexData.indices.push(indices[index]);
  35513. }
  35514. }
  35515. var updatable = false;
  35516. var stopChecking = false;
  35517. var kind;
  35518. for (kind in this._vertexBuffers) {
  35519. // using slice() to make a copy of the array and not just reference it
  35520. var data = this.getVerticesData(kind);
  35521. if (data instanceof Float32Array) {
  35522. vertexData.set(new Float32Array(data), kind);
  35523. }
  35524. else {
  35525. vertexData.set(data.slice(0), kind);
  35526. }
  35527. if (!stopChecking) {
  35528. var vb = this.getVertexBuffer(kind);
  35529. if (vb) {
  35530. updatable = vb.isUpdatable();
  35531. stopChecking = !updatable;
  35532. }
  35533. }
  35534. }
  35535. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  35536. geometry.delayLoadState = this.delayLoadState;
  35537. geometry.delayLoadingFile = this.delayLoadingFile;
  35538. geometry._delayLoadingFunction = this._delayLoadingFunction;
  35539. for (kind in this._delayInfo) {
  35540. geometry._delayInfo = geometry._delayInfo || [];
  35541. geometry._delayInfo.push(kind);
  35542. }
  35543. // Bounding info
  35544. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  35545. return geometry;
  35546. };
  35547. /**
  35548. * Serialize the current geometry info (and not the vertices data) into a JSON object
  35549. * @return a JSON representation of the current geometry data (without the vertices data)
  35550. */
  35551. Geometry.prototype.serialize = function () {
  35552. var serializationObject = {};
  35553. serializationObject.id = this.id;
  35554. serializationObject.updatable = this._updatable;
  35555. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  35556. serializationObject.tags = BABYLON.Tags.GetTags(this);
  35557. }
  35558. return serializationObject;
  35559. };
  35560. Geometry.prototype.toNumberArray = function (origin) {
  35561. if (Array.isArray(origin)) {
  35562. return origin;
  35563. }
  35564. else {
  35565. return Array.prototype.slice.call(origin);
  35566. }
  35567. };
  35568. /**
  35569. * Serialize all vertices data into a JSON oject
  35570. * @returns a JSON representation of the current geometry data
  35571. */
  35572. Geometry.prototype.serializeVerticeData = function () {
  35573. var serializationObject = this.serialize();
  35574. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  35575. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  35576. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  35577. serializationObject.positions._updatable = true;
  35578. }
  35579. }
  35580. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  35581. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  35582. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  35583. serializationObject.normals._updatable = true;
  35584. }
  35585. }
  35586. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  35587. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  35588. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  35589. serializationObject.tangets._updatable = true;
  35590. }
  35591. }
  35592. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  35593. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  35594. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  35595. serializationObject.uvs._updatable = true;
  35596. }
  35597. }
  35598. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  35599. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  35600. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  35601. serializationObject.uv2s._updatable = true;
  35602. }
  35603. }
  35604. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  35605. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  35606. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  35607. serializationObject.uv3s._updatable = true;
  35608. }
  35609. }
  35610. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  35611. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  35612. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  35613. serializationObject.uv4s._updatable = true;
  35614. }
  35615. }
  35616. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  35617. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  35618. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  35619. serializationObject.uv5s._updatable = true;
  35620. }
  35621. }
  35622. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  35623. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  35624. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  35625. serializationObject.uv6s._updatable = true;
  35626. }
  35627. }
  35628. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  35629. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  35630. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  35631. serializationObject.colors._updatable = true;
  35632. }
  35633. }
  35634. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  35635. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  35636. serializationObject.matricesIndices._isExpanded = true;
  35637. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  35638. serializationObject.matricesIndices._updatable = true;
  35639. }
  35640. }
  35641. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  35642. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  35643. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  35644. serializationObject.matricesWeights._updatable = true;
  35645. }
  35646. }
  35647. serializationObject.indices = this.toNumberArray(this.getIndices());
  35648. return serializationObject;
  35649. };
  35650. // Statics
  35651. /**
  35652. * Extracts a clone of a mesh geometry
  35653. * @param mesh defines the source mesh
  35654. * @param id defines the unique ID of the new geometry object
  35655. * @returns the new geometry object
  35656. */
  35657. Geometry.ExtractFromMesh = function (mesh, id) {
  35658. var geometry = mesh._geometry;
  35659. if (!geometry) {
  35660. return null;
  35661. }
  35662. return geometry.copy(id);
  35663. };
  35664. /**
  35665. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  35666. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  35667. * Be aware Math.random() could cause collisions, but:
  35668. * "All but 6 of the 128 bits of the ID are randomly generated, which means that for any two ids, there's a 1 in 2^^122 (or 5.3x10^^36) chance they'll collide"
  35669. * @returns a string containing a new GUID
  35670. */
  35671. Geometry.RandomId = function () {
  35672. return BABYLON.Tools.RandomId();
  35673. };
  35674. /** @ignore */
  35675. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  35676. var scene = mesh.getScene();
  35677. // Geometry
  35678. var geometryId = parsedGeometry.geometryId;
  35679. if (geometryId) {
  35680. var geometry = scene.getGeometryByID(geometryId);
  35681. if (geometry) {
  35682. geometry.applyToMesh(mesh);
  35683. }
  35684. }
  35685. else if (parsedGeometry instanceof ArrayBuffer) {
  35686. var binaryInfo = mesh._binaryInfo;
  35687. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  35688. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  35689. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  35690. }
  35691. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  35692. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  35693. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  35694. }
  35695. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  35696. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  35697. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  35698. }
  35699. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  35700. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  35701. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  35702. }
  35703. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  35704. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  35705. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  35706. }
  35707. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  35708. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  35709. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  35710. }
  35711. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  35712. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  35713. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  35714. }
  35715. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  35716. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  35717. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  35718. }
  35719. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  35720. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  35721. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  35722. }
  35723. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  35724. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  35725. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  35726. }
  35727. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  35728. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  35729. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  35730. }
  35731. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  35732. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  35733. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  35734. }
  35735. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  35736. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  35737. mesh.setIndices(indicesData, null);
  35738. }
  35739. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  35740. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  35741. mesh.subMeshes = [];
  35742. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  35743. var materialIndex = subMeshesData[(i * 5) + 0];
  35744. var verticesStart = subMeshesData[(i * 5) + 1];
  35745. var verticesCount = subMeshesData[(i * 5) + 2];
  35746. var indexStart = subMeshesData[(i * 5) + 3];
  35747. var indexCount = subMeshesData[(i * 5) + 4];
  35748. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  35749. }
  35750. }
  35751. }
  35752. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  35753. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  35754. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  35755. if (parsedGeometry.tangents) {
  35756. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  35757. }
  35758. if (parsedGeometry.uvs) {
  35759. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  35760. }
  35761. if (parsedGeometry.uvs2) {
  35762. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  35763. }
  35764. if (parsedGeometry.uvs3) {
  35765. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  35766. }
  35767. if (parsedGeometry.uvs4) {
  35768. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  35769. }
  35770. if (parsedGeometry.uvs5) {
  35771. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  35772. }
  35773. if (parsedGeometry.uvs6) {
  35774. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  35775. }
  35776. if (parsedGeometry.colors) {
  35777. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  35778. }
  35779. if (parsedGeometry.matricesIndices) {
  35780. if (!parsedGeometry.matricesIndices._isExpanded) {
  35781. var floatIndices = [];
  35782. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  35783. var matricesIndex = parsedGeometry.matricesIndices[i];
  35784. floatIndices.push(matricesIndex & 0x000000FF);
  35785. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  35786. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  35787. floatIndices.push(matricesIndex >> 24);
  35788. }
  35789. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  35790. }
  35791. else {
  35792. delete parsedGeometry.matricesIndices._isExpanded;
  35793. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  35794. }
  35795. }
  35796. if (parsedGeometry.matricesIndicesExtra) {
  35797. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  35798. var floatIndices = [];
  35799. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  35800. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  35801. floatIndices.push(matricesIndex & 0x000000FF);
  35802. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  35803. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  35804. floatIndices.push(matricesIndex >> 24);
  35805. }
  35806. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  35807. }
  35808. else {
  35809. delete parsedGeometry.matricesIndices._isExpanded;
  35810. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  35811. }
  35812. }
  35813. if (parsedGeometry.matricesWeights) {
  35814. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  35815. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  35816. }
  35817. if (parsedGeometry.matricesWeightsExtra) {
  35818. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  35819. }
  35820. mesh.setIndices(parsedGeometry.indices, null);
  35821. }
  35822. // SubMeshes
  35823. if (parsedGeometry.subMeshes) {
  35824. mesh.subMeshes = [];
  35825. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  35826. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  35827. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  35828. }
  35829. }
  35830. // Flat shading
  35831. if (mesh._shouldGenerateFlatShading) {
  35832. mesh.convertToFlatShadedMesh();
  35833. delete mesh._shouldGenerateFlatShading;
  35834. }
  35835. // Update
  35836. mesh.computeWorldMatrix(true);
  35837. // Octree
  35838. var sceneOctree = scene.selectionOctree;
  35839. if (sceneOctree !== undefined && sceneOctree !== null) {
  35840. sceneOctree.addMesh(mesh);
  35841. }
  35842. };
  35843. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  35844. var epsilon = 1e-3;
  35845. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  35846. return;
  35847. }
  35848. var noInfluenceBoneIndex = 0.0;
  35849. if (parsedGeometry.skeletonId > -1) {
  35850. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  35851. if (!skeleton) {
  35852. return;
  35853. }
  35854. noInfluenceBoneIndex = skeleton.bones.length;
  35855. }
  35856. else {
  35857. return;
  35858. }
  35859. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  35860. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  35861. var matricesWeights = parsedGeometry.matricesWeights;
  35862. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  35863. var influencers = parsedGeometry.numBoneInfluencer;
  35864. var size = matricesWeights.length;
  35865. for (var i = 0; i < size; i += 4) {
  35866. var weight = 0.0;
  35867. var firstZeroWeight = -1;
  35868. for (var j = 0; j < 4; j++) {
  35869. var w = matricesWeights[i + j];
  35870. weight += w;
  35871. if (w < epsilon && firstZeroWeight < 0) {
  35872. firstZeroWeight = j;
  35873. }
  35874. }
  35875. if (matricesWeightsExtra) {
  35876. for (var j = 0; j < 4; j++) {
  35877. var w = matricesWeightsExtra[i + j];
  35878. weight += w;
  35879. if (w < epsilon && firstZeroWeight < 0) {
  35880. firstZeroWeight = j + 4;
  35881. }
  35882. }
  35883. }
  35884. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  35885. firstZeroWeight = influencers - 1;
  35886. }
  35887. if (weight > epsilon) {
  35888. var mweight = 1.0 / weight;
  35889. for (var j = 0; j < 4; j++) {
  35890. matricesWeights[i + j] *= mweight;
  35891. }
  35892. if (matricesWeightsExtra) {
  35893. for (var j = 0; j < 4; j++) {
  35894. matricesWeightsExtra[i + j] *= mweight;
  35895. }
  35896. }
  35897. }
  35898. else {
  35899. if (firstZeroWeight >= 4) {
  35900. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  35901. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  35902. }
  35903. else {
  35904. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  35905. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  35906. }
  35907. }
  35908. }
  35909. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  35910. if (parsedGeometry.matricesWeightsExtra) {
  35911. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  35912. }
  35913. };
  35914. /**
  35915. * Create a new geometry from persisted data (Using .babylon file format)
  35916. * @param parsedVertexData defines the persisted data
  35917. * @param scene defines the hosting scene
  35918. * @param rootUrl defines the root url to use to load assets (like delayed data)
  35919. * @returns the new geometry object
  35920. */
  35921. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  35922. if (scene.getGeometryByID(parsedVertexData.id)) {
  35923. return null; // null since geometry could be something else than a box...
  35924. }
  35925. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  35926. if (BABYLON.Tags) {
  35927. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  35928. }
  35929. if (parsedVertexData.delayLoadingFile) {
  35930. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  35931. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  35932. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  35933. geometry._delayInfo = [];
  35934. if (parsedVertexData.hasUVs) {
  35935. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  35936. }
  35937. if (parsedVertexData.hasUVs2) {
  35938. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  35939. }
  35940. if (parsedVertexData.hasUVs3) {
  35941. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  35942. }
  35943. if (parsedVertexData.hasUVs4) {
  35944. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  35945. }
  35946. if (parsedVertexData.hasUVs5) {
  35947. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  35948. }
  35949. if (parsedVertexData.hasUVs6) {
  35950. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  35951. }
  35952. if (parsedVertexData.hasColors) {
  35953. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  35954. }
  35955. if (parsedVertexData.hasMatricesIndices) {
  35956. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  35957. }
  35958. if (parsedVertexData.hasMatricesWeights) {
  35959. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  35960. }
  35961. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  35962. }
  35963. else {
  35964. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  35965. }
  35966. scene.pushGeometry(geometry, true);
  35967. return geometry;
  35968. };
  35969. return Geometry;
  35970. }());
  35971. BABYLON.Geometry = Geometry;
  35972. // Primitives
  35973. /// Abstract class
  35974. /**
  35975. * Abstract class used to provide common services for all typed geometries
  35976. */
  35977. var _PrimitiveGeometry = /** @class */ (function (_super) {
  35978. __extends(_PrimitiveGeometry, _super);
  35979. /**
  35980. * Creates a new typed geometry
  35981. * @param id defines the unique ID of the geometry
  35982. * @param scene defines the hosting scene
  35983. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35984. * @param mesh defines the hosting mesh (can be null)
  35985. */
  35986. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  35987. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  35988. if (mesh === void 0) { mesh = null; }
  35989. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  35990. _this._canBeRegenerated = _canBeRegenerated;
  35991. _this._beingRegenerated = true;
  35992. _this.regenerate();
  35993. _this._beingRegenerated = false;
  35994. return _this;
  35995. }
  35996. /**
  35997. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  35998. * @returns true if the geometry can be regenerated
  35999. */
  36000. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  36001. return this._canBeRegenerated;
  36002. };
  36003. /**
  36004. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  36005. */
  36006. _PrimitiveGeometry.prototype.regenerate = function () {
  36007. if (!this._canBeRegenerated) {
  36008. return;
  36009. }
  36010. this._beingRegenerated = true;
  36011. this.setAllVerticesData(this._regenerateVertexData(), false);
  36012. this._beingRegenerated = false;
  36013. };
  36014. /**
  36015. * Clone the geometry
  36016. * @param id defines the unique ID of the new geometry
  36017. * @returns the new geometry
  36018. */
  36019. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  36020. return _super.prototype.copy.call(this, id);
  36021. };
  36022. // overrides
  36023. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  36024. if (!this._beingRegenerated) {
  36025. return;
  36026. }
  36027. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  36028. };
  36029. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  36030. if (!this._beingRegenerated) {
  36031. return;
  36032. }
  36033. _super.prototype.setVerticesData.call(this, kind, data, false);
  36034. };
  36035. // to override
  36036. /** @ignore */
  36037. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  36038. throw new Error("Abstract method");
  36039. };
  36040. _PrimitiveGeometry.prototype.copy = function (id) {
  36041. throw new Error("Must be overriden in sub-classes.");
  36042. };
  36043. _PrimitiveGeometry.prototype.serialize = function () {
  36044. var serializationObject = _super.prototype.serialize.call(this);
  36045. serializationObject.canBeRegenerated = this.canBeRegenerated();
  36046. return serializationObject;
  36047. };
  36048. return _PrimitiveGeometry;
  36049. }(Geometry));
  36050. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  36051. /**
  36052. * Creates a ribbon geometry
  36053. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  36054. */
  36055. var RibbonGeometry = /** @class */ (function (_super) {
  36056. __extends(RibbonGeometry, _super);
  36057. /**
  36058. * Creates a ribbon geometry
  36059. * @param id defines the unique ID of the geometry
  36060. * @param scene defines the hosting scene
  36061. * @param pathArray defines the array of paths to use
  36062. * @param closeArray defines if the last path and the first path must be joined
  36063. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  36064. * @param offset defines the offset between points
  36065. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36066. * @param mesh defines the hosting mesh (can be null)
  36067. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36068. */
  36069. function RibbonGeometry(id, scene,
  36070. /**
  36071. * Defines the array of paths to use
  36072. */
  36073. pathArray,
  36074. /**
  36075. * Defines if the last and first points of each path in your pathArray must be joined
  36076. */
  36077. closeArray,
  36078. /**
  36079. * Defines if the last and first points of each path in your pathArray must be joined
  36080. */
  36081. closePath,
  36082. /**
  36083. * Defines the offset between points
  36084. */
  36085. offset, canBeRegenerated, mesh,
  36086. /**
  36087. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36088. */
  36089. side) {
  36090. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36091. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36092. _this.pathArray = pathArray;
  36093. _this.closeArray = closeArray;
  36094. _this.closePath = closePath;
  36095. _this.offset = offset;
  36096. _this.side = side;
  36097. return _this;
  36098. }
  36099. /** @ignore */
  36100. RibbonGeometry.prototype._regenerateVertexData = function () {
  36101. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  36102. };
  36103. RibbonGeometry.prototype.copy = function (id) {
  36104. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  36105. };
  36106. return RibbonGeometry;
  36107. }(_PrimitiveGeometry));
  36108. BABYLON.RibbonGeometry = RibbonGeometry;
  36109. /**
  36110. * Creates a box geometry
  36111. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  36112. */
  36113. var BoxGeometry = /** @class */ (function (_super) {
  36114. __extends(BoxGeometry, _super);
  36115. /**
  36116. * Creates a box geometry
  36117. * @param id defines the unique ID of the geometry
  36118. * @param scene defines the hosting scene
  36119. * @param size defines the zise of the box (width, height and depth are the same)
  36120. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36121. * @param mesh defines the hosting mesh (can be null)
  36122. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36123. */
  36124. function BoxGeometry(id, scene,
  36125. /**
  36126. * Defines the zise of the box (width, height and depth are the same)
  36127. */
  36128. size, canBeRegenerated, mesh,
  36129. /**
  36130. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36131. */
  36132. side) {
  36133. if (mesh === void 0) { mesh = null; }
  36134. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36135. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36136. _this.size = size;
  36137. _this.side = side;
  36138. return _this;
  36139. }
  36140. BoxGeometry.prototype._regenerateVertexData = function () {
  36141. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  36142. };
  36143. BoxGeometry.prototype.copy = function (id) {
  36144. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  36145. };
  36146. BoxGeometry.prototype.serialize = function () {
  36147. var serializationObject = _super.prototype.serialize.call(this);
  36148. serializationObject.size = this.size;
  36149. return serializationObject;
  36150. };
  36151. BoxGeometry.Parse = function (parsedBox, scene) {
  36152. if (scene.getGeometryByID(parsedBox.id)) {
  36153. return null; // null since geometry could be something else than a box...
  36154. }
  36155. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  36156. if (BABYLON.Tags) {
  36157. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  36158. }
  36159. scene.pushGeometry(box, true);
  36160. return box;
  36161. };
  36162. return BoxGeometry;
  36163. }(_PrimitiveGeometry));
  36164. BABYLON.BoxGeometry = BoxGeometry;
  36165. /**
  36166. * Creates a sphere geometry
  36167. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  36168. */
  36169. var SphereGeometry = /** @class */ (function (_super) {
  36170. __extends(SphereGeometry, _super);
  36171. /**
  36172. * Create a new sphere geometry
  36173. * @param id defines the unique ID of the geometry
  36174. * @param scene defines the hosting scene
  36175. * @param segments defines the number of segments to use to create the sphere
  36176. * @param diameter defines the diameter of the sphere
  36177. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36178. * @param mesh defines the hosting mesh (can be null)
  36179. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36180. */
  36181. function SphereGeometry(id, scene,
  36182. /**
  36183. * Defines the number of segments to use to create the sphere
  36184. */
  36185. segments,
  36186. /**
  36187. * Defines the diameter of the sphere
  36188. */
  36189. diameter, canBeRegenerated, mesh,
  36190. /**
  36191. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36192. */
  36193. side) {
  36194. if (mesh === void 0) { mesh = null; }
  36195. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36196. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36197. _this.segments = segments;
  36198. _this.diameter = diameter;
  36199. _this.side = side;
  36200. return _this;
  36201. }
  36202. SphereGeometry.prototype._regenerateVertexData = function () {
  36203. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  36204. };
  36205. SphereGeometry.prototype.copy = function (id) {
  36206. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  36207. };
  36208. SphereGeometry.prototype.serialize = function () {
  36209. var serializationObject = _super.prototype.serialize.call(this);
  36210. serializationObject.segments = this.segments;
  36211. serializationObject.diameter = this.diameter;
  36212. return serializationObject;
  36213. };
  36214. SphereGeometry.Parse = function (parsedSphere, scene) {
  36215. if (scene.getGeometryByID(parsedSphere.id)) {
  36216. return null; // null since geometry could be something else than a sphere...
  36217. }
  36218. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  36219. if (BABYLON.Tags) {
  36220. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  36221. }
  36222. scene.pushGeometry(sphere, true);
  36223. return sphere;
  36224. };
  36225. return SphereGeometry;
  36226. }(_PrimitiveGeometry));
  36227. BABYLON.SphereGeometry = SphereGeometry;
  36228. /**
  36229. * Creates a disc geometry
  36230. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  36231. */
  36232. var DiscGeometry = /** @class */ (function (_super) {
  36233. __extends(DiscGeometry, _super);
  36234. /**
  36235. * Creates a new disc geometry
  36236. * @param id defines the unique ID of the geometry
  36237. * @param scene defines the hosting scene
  36238. * @param radius defines the radius of the disc
  36239. * @param tessellation defines the tesselation factor to apply to the disc
  36240. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36241. * @param mesh defines the hosting mesh (can be null)
  36242. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36243. */
  36244. function DiscGeometry(id, scene,
  36245. /**
  36246. * Defines the radius of the disc
  36247. */
  36248. radius,
  36249. /**
  36250. * Defines the tesselation factor to apply to the disc
  36251. */
  36252. tessellation, canBeRegenerated, mesh,
  36253. /**
  36254. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36255. */
  36256. side) {
  36257. if (mesh === void 0) { mesh = null; }
  36258. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36259. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36260. _this.radius = radius;
  36261. _this.tessellation = tessellation;
  36262. _this.side = side;
  36263. return _this;
  36264. }
  36265. DiscGeometry.prototype._regenerateVertexData = function () {
  36266. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  36267. };
  36268. DiscGeometry.prototype.copy = function (id) {
  36269. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  36270. };
  36271. return DiscGeometry;
  36272. }(_PrimitiveGeometry));
  36273. BABYLON.DiscGeometry = DiscGeometry;
  36274. /**
  36275. * Creates a new cylinder geometry
  36276. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  36277. */
  36278. var CylinderGeometry = /** @class */ (function (_super) {
  36279. __extends(CylinderGeometry, _super);
  36280. /**
  36281. * Creates a new cylinder geometry
  36282. * @param id defines the unique ID of the geometry
  36283. * @param scene defines the hosting scene
  36284. * @param height defines the height of the cylinder
  36285. * @param diameterTop defines the diameter of the cylinder's top cap
  36286. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  36287. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  36288. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  36289. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36290. * @param mesh defines the hosting mesh (can be null)
  36291. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36292. */
  36293. function CylinderGeometry(id, scene,
  36294. /**
  36295. * Defines the height of the cylinder
  36296. */
  36297. height,
  36298. /**
  36299. * Defines the diameter of the cylinder's top cap
  36300. */
  36301. diameterTop,
  36302. /**
  36303. * Defines the diameter of the cylinder's bottom cap
  36304. */
  36305. diameterBottom,
  36306. /**
  36307. * Defines the tessellation factor to apply to the cylinder
  36308. */
  36309. tessellation,
  36310. /**
  36311. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  36312. */
  36313. subdivisions, canBeRegenerated, mesh,
  36314. /**
  36315. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36316. */
  36317. side) {
  36318. if (subdivisions === void 0) { subdivisions = 1; }
  36319. if (mesh === void 0) { mesh = null; }
  36320. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36321. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36322. _this.height = height;
  36323. _this.diameterTop = diameterTop;
  36324. _this.diameterBottom = diameterBottom;
  36325. _this.tessellation = tessellation;
  36326. _this.subdivisions = subdivisions;
  36327. _this.side = side;
  36328. return _this;
  36329. }
  36330. CylinderGeometry.prototype._regenerateVertexData = function () {
  36331. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  36332. };
  36333. CylinderGeometry.prototype.copy = function (id) {
  36334. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  36335. };
  36336. CylinderGeometry.prototype.serialize = function () {
  36337. var serializationObject = _super.prototype.serialize.call(this);
  36338. serializationObject.height = this.height;
  36339. serializationObject.diameterTop = this.diameterTop;
  36340. serializationObject.diameterBottom = this.diameterBottom;
  36341. serializationObject.tessellation = this.tessellation;
  36342. return serializationObject;
  36343. };
  36344. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  36345. if (scene.getGeometryByID(parsedCylinder.id)) {
  36346. return null; // null since geometry could be something else than a cylinder...
  36347. }
  36348. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  36349. if (BABYLON.Tags) {
  36350. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  36351. }
  36352. scene.pushGeometry(cylinder, true);
  36353. return cylinder;
  36354. };
  36355. return CylinderGeometry;
  36356. }(_PrimitiveGeometry));
  36357. BABYLON.CylinderGeometry = CylinderGeometry;
  36358. /**
  36359. * Creates a new torus geometry
  36360. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  36361. */
  36362. var TorusGeometry = /** @class */ (function (_super) {
  36363. __extends(TorusGeometry, _super);
  36364. /**
  36365. * Creates a new torus geometry
  36366. * @param id defines the unique ID of the geometry
  36367. * @param scene defines the hosting scene
  36368. * @param diameter defines the diameter of the torus
  36369. * @param thickness defines the thickness of the torus (ie. internal diameter)
  36370. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  36371. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36372. * @param mesh defines the hosting mesh (can be null)
  36373. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36374. */
  36375. function TorusGeometry(id, scene,
  36376. /**
  36377. * Defines the diameter of the torus
  36378. */
  36379. diameter,
  36380. /**
  36381. * Defines the thickness of the torus (ie. internal diameter)
  36382. */
  36383. thickness,
  36384. /**
  36385. * Defines the tesselation factor to apply to the torus
  36386. */
  36387. tessellation, canBeRegenerated, mesh,
  36388. /**
  36389. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36390. */
  36391. side) {
  36392. if (mesh === void 0) { mesh = null; }
  36393. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36394. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36395. _this.diameter = diameter;
  36396. _this.thickness = thickness;
  36397. _this.tessellation = tessellation;
  36398. _this.side = side;
  36399. return _this;
  36400. }
  36401. TorusGeometry.prototype._regenerateVertexData = function () {
  36402. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  36403. };
  36404. TorusGeometry.prototype.copy = function (id) {
  36405. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  36406. };
  36407. TorusGeometry.prototype.serialize = function () {
  36408. var serializationObject = _super.prototype.serialize.call(this);
  36409. serializationObject.diameter = this.diameter;
  36410. serializationObject.thickness = this.thickness;
  36411. serializationObject.tessellation = this.tessellation;
  36412. return serializationObject;
  36413. };
  36414. TorusGeometry.Parse = function (parsedTorus, scene) {
  36415. if (scene.getGeometryByID(parsedTorus.id)) {
  36416. return null; // null since geometry could be something else than a torus...
  36417. }
  36418. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  36419. if (BABYLON.Tags) {
  36420. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  36421. }
  36422. scene.pushGeometry(torus, true);
  36423. return torus;
  36424. };
  36425. return TorusGeometry;
  36426. }(_PrimitiveGeometry));
  36427. BABYLON.TorusGeometry = TorusGeometry;
  36428. /**
  36429. * Creates a new ground geometry
  36430. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  36431. */
  36432. var GroundGeometry = /** @class */ (function (_super) {
  36433. __extends(GroundGeometry, _super);
  36434. /**
  36435. * Creates a new ground geometry
  36436. * @param id defines the unique ID of the geometry
  36437. * @param scene defines the hosting scene
  36438. * @param width defines the width of the ground
  36439. * @param height defines the height of the ground
  36440. * @param subdivisions defines the subdivisions to apply to the ground
  36441. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36442. * @param mesh defines the hosting mesh (can be null)
  36443. */
  36444. function GroundGeometry(id, scene,
  36445. /**
  36446. * Defines the width of the ground
  36447. */
  36448. width,
  36449. /**
  36450. * Defines the height of the ground
  36451. */
  36452. height,
  36453. /**
  36454. * Defines the subdivisions to apply to the ground
  36455. */
  36456. subdivisions, canBeRegenerated, mesh) {
  36457. if (mesh === void 0) { mesh = null; }
  36458. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36459. _this.width = width;
  36460. _this.height = height;
  36461. _this.subdivisions = subdivisions;
  36462. return _this;
  36463. }
  36464. GroundGeometry.prototype._regenerateVertexData = function () {
  36465. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  36466. };
  36467. GroundGeometry.prototype.copy = function (id) {
  36468. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  36469. };
  36470. GroundGeometry.prototype.serialize = function () {
  36471. var serializationObject = _super.prototype.serialize.call(this);
  36472. serializationObject.width = this.width;
  36473. serializationObject.height = this.height;
  36474. serializationObject.subdivisions = this.subdivisions;
  36475. return serializationObject;
  36476. };
  36477. GroundGeometry.Parse = function (parsedGround, scene) {
  36478. if (scene.getGeometryByID(parsedGround.id)) {
  36479. return null; // null since geometry could be something else than a ground...
  36480. }
  36481. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  36482. if (BABYLON.Tags) {
  36483. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  36484. }
  36485. scene.pushGeometry(ground, true);
  36486. return ground;
  36487. };
  36488. return GroundGeometry;
  36489. }(_PrimitiveGeometry));
  36490. BABYLON.GroundGeometry = GroundGeometry;
  36491. /**
  36492. * Creates a tiled ground geometry
  36493. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  36494. */
  36495. var TiledGroundGeometry = /** @class */ (function (_super) {
  36496. __extends(TiledGroundGeometry, _super);
  36497. /**
  36498. * Creates a tiled ground geometry
  36499. * @param id defines the unique ID of the geometry
  36500. * @param scene defines the hosting scene
  36501. * @param xmin defines the minimum value on X axis
  36502. * @param zmin defines the minimum value on Z axis
  36503. * @param xmax defines the maximum value on X axis
  36504. * @param zmax defines the maximum value on Z axis
  36505. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  36506. * @param precision defines the precision to use when computing the tiles
  36507. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36508. * @param mesh defines the hosting mesh (can be null)
  36509. */
  36510. function TiledGroundGeometry(id, scene,
  36511. /**
  36512. * Defines the minimum value on X axis
  36513. */
  36514. xmin,
  36515. /**
  36516. * Defines the minimum value on Z axis
  36517. */
  36518. zmin,
  36519. /**
  36520. * Defines the maximum value on X axis
  36521. */
  36522. xmax,
  36523. /**
  36524. * Defines the maximum value on Z axis
  36525. */
  36526. zmax,
  36527. /**
  36528. * Defines the subdivisions to apply to the ground
  36529. */
  36530. subdivisions,
  36531. /**
  36532. * Defines the precision to use when computing the tiles
  36533. */
  36534. precision, canBeRegenerated, mesh) {
  36535. if (mesh === void 0) { mesh = null; }
  36536. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36537. _this.xmin = xmin;
  36538. _this.zmin = zmin;
  36539. _this.xmax = xmax;
  36540. _this.zmax = zmax;
  36541. _this.subdivisions = subdivisions;
  36542. _this.precision = precision;
  36543. return _this;
  36544. }
  36545. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  36546. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  36547. };
  36548. TiledGroundGeometry.prototype.copy = function (id) {
  36549. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  36550. };
  36551. return TiledGroundGeometry;
  36552. }(_PrimitiveGeometry));
  36553. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  36554. /**
  36555. * Creates a plane geometry
  36556. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  36557. */
  36558. var PlaneGeometry = /** @class */ (function (_super) {
  36559. __extends(PlaneGeometry, _super);
  36560. /**
  36561. * Creates a plane geometry
  36562. * @param id defines the unique ID of the geometry
  36563. * @param scene defines the hosting scene
  36564. * @param size defines the size of the plane (width === height)
  36565. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36566. * @param mesh defines the hosting mesh (can be null)
  36567. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36568. */
  36569. function PlaneGeometry(id, scene,
  36570. /**
  36571. * Defines the size of the plane (width === height)
  36572. */
  36573. size, canBeRegenerated, mesh,
  36574. /**
  36575. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36576. */
  36577. side) {
  36578. if (mesh === void 0) { mesh = null; }
  36579. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36580. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36581. _this.size = size;
  36582. _this.side = side;
  36583. return _this;
  36584. }
  36585. PlaneGeometry.prototype._regenerateVertexData = function () {
  36586. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  36587. };
  36588. PlaneGeometry.prototype.copy = function (id) {
  36589. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  36590. };
  36591. PlaneGeometry.prototype.serialize = function () {
  36592. var serializationObject = _super.prototype.serialize.call(this);
  36593. serializationObject.size = this.size;
  36594. return serializationObject;
  36595. };
  36596. PlaneGeometry.Parse = function (parsedPlane, scene) {
  36597. if (scene.getGeometryByID(parsedPlane.id)) {
  36598. return null; // null since geometry could be something else than a ground...
  36599. }
  36600. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  36601. if (BABYLON.Tags) {
  36602. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  36603. }
  36604. scene.pushGeometry(plane, true);
  36605. return plane;
  36606. };
  36607. return PlaneGeometry;
  36608. }(_PrimitiveGeometry));
  36609. BABYLON.PlaneGeometry = PlaneGeometry;
  36610. /**
  36611. * Creates a torus knot geometry
  36612. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  36613. */
  36614. var TorusKnotGeometry = /** @class */ (function (_super) {
  36615. __extends(TorusKnotGeometry, _super);
  36616. /**
  36617. * Creates a torus knot geometry
  36618. * @param id defines the unique ID of the geometry
  36619. * @param scene defines the hosting scene
  36620. * @param radius defines the radius of the torus knot
  36621. * @param tube defines the thickness of the torus knot tube
  36622. * @param radialSegments defines the number of radial segments
  36623. * @param tubularSegments defines the number of tubular segments
  36624. * @param p defines the first number of windings
  36625. * @param q defines the second number of windings
  36626. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36627. * @param mesh defines the hosting mesh (can be null)
  36628. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36629. */
  36630. function TorusKnotGeometry(id, scene,
  36631. /**
  36632. * Defines the radius of the torus knot
  36633. */
  36634. radius,
  36635. /**
  36636. * Defines the thickness of the torus knot tube
  36637. */
  36638. tube,
  36639. /**
  36640. * Defines the number of radial segments
  36641. */
  36642. radialSegments,
  36643. /**
  36644. * Defines the number of tubular segments
  36645. */
  36646. tubularSegments,
  36647. /**
  36648. * Defines the first number of windings
  36649. */
  36650. p,
  36651. /**
  36652. * Defines the second number of windings
  36653. */
  36654. q, canBeRegenerated, mesh,
  36655. /**
  36656. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36657. */
  36658. side) {
  36659. if (mesh === void 0) { mesh = null; }
  36660. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36661. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36662. _this.radius = radius;
  36663. _this.tube = tube;
  36664. _this.radialSegments = radialSegments;
  36665. _this.tubularSegments = tubularSegments;
  36666. _this.p = p;
  36667. _this.q = q;
  36668. _this.side = side;
  36669. return _this;
  36670. }
  36671. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  36672. return BABYLON.VertexData.CreateTorusKnot({ radius: this.radius, tube: this.tube, radialSegments: this.radialSegments, tubularSegments: this.tubularSegments, p: this.p, q: this.q, sideOrientation: this.side });
  36673. };
  36674. TorusKnotGeometry.prototype.copy = function (id) {
  36675. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  36676. };
  36677. TorusKnotGeometry.prototype.serialize = function () {
  36678. var serializationObject = _super.prototype.serialize.call(this);
  36679. serializationObject.radius = this.radius;
  36680. serializationObject.tube = this.tube;
  36681. serializationObject.radialSegments = this.radialSegments;
  36682. serializationObject.tubularSegments = this.tubularSegments;
  36683. serializationObject.p = this.p;
  36684. serializationObject.q = this.q;
  36685. return serializationObject;
  36686. };
  36687. ;
  36688. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  36689. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  36690. return null; // null since geometry could be something else than a ground...
  36691. }
  36692. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  36693. if (BABYLON.Tags) {
  36694. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  36695. }
  36696. scene.pushGeometry(torusKnot, true);
  36697. return torusKnot;
  36698. };
  36699. return TorusKnotGeometry;
  36700. }(_PrimitiveGeometry));
  36701. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  36702. //}
  36703. })(BABYLON || (BABYLON = {}));
  36704. //# sourceMappingURL=babylon.geometry.js.map
  36705. var BABYLON;
  36706. (function (BABYLON) {
  36707. /**
  36708. * PostProcessManager is used to manage one or more post processes or post process pipelines
  36709. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  36710. */
  36711. var PostProcessManager = /** @class */ (function () {
  36712. /**
  36713. * Creates a new instance of @see PostProcess
  36714. * @param scene The scene that the post process is associated with.
  36715. */
  36716. function PostProcessManager(scene) {
  36717. this._vertexBuffers = {};
  36718. this._scene = scene;
  36719. }
  36720. PostProcessManager.prototype._prepareBuffers = function () {
  36721. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  36722. return;
  36723. }
  36724. // VBO
  36725. var vertices = [];
  36726. vertices.push(1, 1);
  36727. vertices.push(-1, 1);
  36728. vertices.push(-1, -1);
  36729. vertices.push(1, -1);
  36730. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  36731. this._buildIndexBuffer();
  36732. };
  36733. PostProcessManager.prototype._buildIndexBuffer = function () {
  36734. // Indices
  36735. var indices = [];
  36736. indices.push(0);
  36737. indices.push(1);
  36738. indices.push(2);
  36739. indices.push(0);
  36740. indices.push(2);
  36741. indices.push(3);
  36742. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  36743. };
  36744. /**
  36745. * Rebuilds the vertex buffers of the manager.
  36746. */
  36747. PostProcessManager.prototype._rebuild = function () {
  36748. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  36749. if (!vb) {
  36750. return;
  36751. }
  36752. vb._rebuild();
  36753. this._buildIndexBuffer();
  36754. };
  36755. // Methods
  36756. /**
  36757. * Prepares a frame to be run through a post process.
  36758. * @param sourceTexture The input texture to the post procesess. (default: null)
  36759. * @param postProcesses An array of post processes to be run. (default: null)
  36760. * @returns True if the post processes were able to be run.
  36761. */
  36762. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  36763. if (sourceTexture === void 0) { sourceTexture = null; }
  36764. if (postProcesses === void 0) { postProcesses = null; }
  36765. var camera = this._scene.activeCamera;
  36766. if (!camera) {
  36767. return false;
  36768. }
  36769. var postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  36770. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  36771. return false;
  36772. }
  36773. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  36774. return true;
  36775. };
  36776. /**
  36777. * Manually render a set of post processes to a texture.
  36778. * @param postProcesses An array of post processes to be run.
  36779. * @param targetTexture The target texture to render to.
  36780. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  36781. */
  36782. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  36783. if (targetTexture === void 0) { targetTexture = null; }
  36784. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  36785. var engine = this._scene.getEngine();
  36786. for (var index = 0; index < postProcesses.length; index++) {
  36787. if (index < postProcesses.length - 1) {
  36788. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  36789. }
  36790. else {
  36791. if (targetTexture) {
  36792. engine.bindFramebuffer(targetTexture, 0, undefined, undefined, forceFullscreenViewport);
  36793. }
  36794. else {
  36795. engine.restoreDefaultFramebuffer();
  36796. }
  36797. }
  36798. var pp = postProcesses[index];
  36799. var effect = pp.apply();
  36800. if (effect) {
  36801. pp.onBeforeRenderObservable.notifyObservers(effect);
  36802. // VBOs
  36803. this._prepareBuffers();
  36804. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  36805. // Draw order
  36806. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  36807. pp.onAfterRenderObservable.notifyObservers(effect);
  36808. }
  36809. }
  36810. // Restore depth buffer
  36811. engine.setDepthBuffer(true);
  36812. engine.setDepthWrite(true);
  36813. };
  36814. /**
  36815. * Finalize the result of the output of the postprocesses.
  36816. * @param doNotPresent If true the result will not be displayed to the screen.
  36817. * @param targetTexture The target texture to render to.
  36818. * @param faceIndex The index of the face to bind the target texture to.
  36819. * @param postProcesses The array of post processes to render.
  36820. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  36821. */
  36822. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  36823. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  36824. var camera = this._scene.activeCamera;
  36825. if (!camera) {
  36826. return;
  36827. }
  36828. postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  36829. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  36830. return;
  36831. }
  36832. var engine = this._scene.getEngine();
  36833. for (var index = 0, len = postProcesses.length; index < len; index++) {
  36834. if (index < len - 1) {
  36835. postProcesses[index + 1].activate(camera, targetTexture);
  36836. }
  36837. else {
  36838. if (targetTexture) {
  36839. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  36840. }
  36841. else {
  36842. engine.restoreDefaultFramebuffer();
  36843. }
  36844. }
  36845. if (doNotPresent) {
  36846. break;
  36847. }
  36848. var pp = postProcesses[index];
  36849. var effect = pp.apply();
  36850. if (effect) {
  36851. pp.onBeforeRenderObservable.notifyObservers(effect);
  36852. // VBOs
  36853. this._prepareBuffers();
  36854. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  36855. // Draw order
  36856. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  36857. pp.onAfterRenderObservable.notifyObservers(effect);
  36858. }
  36859. }
  36860. // Restore states
  36861. engine.setDepthBuffer(true);
  36862. engine.setDepthWrite(true);
  36863. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  36864. };
  36865. /**
  36866. * Disposes of the post process manager.
  36867. */
  36868. PostProcessManager.prototype.dispose = function () {
  36869. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  36870. if (buffer) {
  36871. buffer.dispose();
  36872. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  36873. }
  36874. if (this._indexBuffer) {
  36875. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  36876. this._indexBuffer = null;
  36877. }
  36878. };
  36879. return PostProcessManager;
  36880. }());
  36881. BABYLON.PostProcessManager = PostProcessManager;
  36882. })(BABYLON || (BABYLON = {}));
  36883. //# sourceMappingURL=babylon.postProcessManager.js.map
  36884. var BABYLON;
  36885. (function (BABYLON) {
  36886. /**
  36887. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  36888. */
  36889. var PerformanceMonitor = /** @class */ (function () {
  36890. /**
  36891. * constructor
  36892. * @param frameSampleSize The number of samples required to saturate the sliding window
  36893. */
  36894. function PerformanceMonitor(frameSampleSize) {
  36895. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  36896. this._enabled = true;
  36897. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  36898. }
  36899. /**
  36900. * Samples current frame
  36901. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  36902. */
  36903. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  36904. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  36905. if (!this._enabled)
  36906. return;
  36907. if (this._lastFrameTimeMs != null) {
  36908. var dt = timeMs - this._lastFrameTimeMs;
  36909. this._rollingFrameTime.add(dt);
  36910. }
  36911. this._lastFrameTimeMs = timeMs;
  36912. };
  36913. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  36914. /**
  36915. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  36916. * @return Average frame time in milliseconds
  36917. */
  36918. get: function () {
  36919. return this._rollingFrameTime.average;
  36920. },
  36921. enumerable: true,
  36922. configurable: true
  36923. });
  36924. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  36925. /**
  36926. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  36927. * @return Frame time variance in milliseconds squared
  36928. */
  36929. get: function () {
  36930. return this._rollingFrameTime.variance;
  36931. },
  36932. enumerable: true,
  36933. configurable: true
  36934. });
  36935. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  36936. /**
  36937. * Returns the frame time of the most recent frame
  36938. * @return Frame time in milliseconds
  36939. */
  36940. get: function () {
  36941. return this._rollingFrameTime.history(0);
  36942. },
  36943. enumerable: true,
  36944. configurable: true
  36945. });
  36946. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  36947. /**
  36948. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  36949. * @return Framerate in frames per second
  36950. */
  36951. get: function () {
  36952. return 1000.0 / this._rollingFrameTime.average;
  36953. },
  36954. enumerable: true,
  36955. configurable: true
  36956. });
  36957. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  36958. /**
  36959. * Returns the average framerate in frames per second using the most recent frame time
  36960. * @return Framerate in frames per second
  36961. */
  36962. get: function () {
  36963. var history = this._rollingFrameTime.history(0);
  36964. if (history === 0) {
  36965. return 0;
  36966. }
  36967. return 1000.0 / history;
  36968. },
  36969. enumerable: true,
  36970. configurable: true
  36971. });
  36972. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  36973. /**
  36974. * Returns true if enough samples have been taken to completely fill the sliding window
  36975. * @return true if saturated
  36976. */
  36977. get: function () {
  36978. return this._rollingFrameTime.isSaturated();
  36979. },
  36980. enumerable: true,
  36981. configurable: true
  36982. });
  36983. /**
  36984. * Enables contributions to the sliding window sample set
  36985. */
  36986. PerformanceMonitor.prototype.enable = function () {
  36987. this._enabled = true;
  36988. };
  36989. /**
  36990. * Disables contributions to the sliding window sample set
  36991. * Samples will not be interpolated over the disabled period
  36992. */
  36993. PerformanceMonitor.prototype.disable = function () {
  36994. this._enabled = false;
  36995. //clear last sample to avoid interpolating over the disabled period when next enabled
  36996. this._lastFrameTimeMs = null;
  36997. };
  36998. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  36999. /**
  37000. * Returns true if sampling is enabled
  37001. * @return true if enabled
  37002. */
  37003. get: function () {
  37004. return this._enabled;
  37005. },
  37006. enumerable: true,
  37007. configurable: true
  37008. });
  37009. /**
  37010. * Resets performance monitor
  37011. */
  37012. PerformanceMonitor.prototype.reset = function () {
  37013. //clear last sample to avoid interpolating over the disabled period when next enabled
  37014. this._lastFrameTimeMs = null;
  37015. //wipe record
  37016. this._rollingFrameTime.reset();
  37017. };
  37018. return PerformanceMonitor;
  37019. }());
  37020. BABYLON.PerformanceMonitor = PerformanceMonitor;
  37021. /**
  37022. * RollingAverage
  37023. *
  37024. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  37025. */
  37026. var RollingAverage = /** @class */ (function () {
  37027. /**
  37028. * constructor
  37029. * @param length The number of samples required to saturate the sliding window
  37030. */
  37031. function RollingAverage(length) {
  37032. this._samples = new Array(length);
  37033. this.reset();
  37034. }
  37035. /**
  37036. * Adds a sample to the sample set
  37037. * @param v The sample value
  37038. */
  37039. RollingAverage.prototype.add = function (v) {
  37040. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  37041. var delta;
  37042. //we need to check if we've already wrapped round
  37043. if (this.isSaturated()) {
  37044. //remove bottom of stack from mean
  37045. var bottomValue = this._samples[this._pos];
  37046. delta = bottomValue - this.average;
  37047. this.average -= delta / (this._sampleCount - 1);
  37048. this._m2 -= delta * (bottomValue - this.average);
  37049. }
  37050. else {
  37051. this._sampleCount++;
  37052. }
  37053. //add new value to mean
  37054. delta = v - this.average;
  37055. this.average += delta / (this._sampleCount);
  37056. this._m2 += delta * (v - this.average);
  37057. //set the new variance
  37058. this.variance = this._m2 / (this._sampleCount - 1);
  37059. this._samples[this._pos] = v;
  37060. this._pos++;
  37061. this._pos %= this._samples.length; //positive wrap around
  37062. };
  37063. /**
  37064. * Returns previously added values or null if outside of history or outside the sliding window domain
  37065. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  37066. * @return Value previously recorded with add() or null if outside of range
  37067. */
  37068. RollingAverage.prototype.history = function (i) {
  37069. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  37070. return 0;
  37071. }
  37072. var i0 = this._wrapPosition(this._pos - 1.0);
  37073. return this._samples[this._wrapPosition(i0 - i)];
  37074. };
  37075. /**
  37076. * Returns true if enough samples have been taken to completely fill the sliding window
  37077. * @return true if sample-set saturated
  37078. */
  37079. RollingAverage.prototype.isSaturated = function () {
  37080. return this._sampleCount >= this._samples.length;
  37081. };
  37082. /**
  37083. * Resets the rolling average (equivalent to 0 samples taken so far)
  37084. */
  37085. RollingAverage.prototype.reset = function () {
  37086. this.average = 0;
  37087. this.variance = 0;
  37088. this._sampleCount = 0;
  37089. this._pos = 0;
  37090. this._m2 = 0;
  37091. };
  37092. /**
  37093. * Wraps a value around the sample range boundaries
  37094. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  37095. * @return Wrapped position in sample range
  37096. */
  37097. RollingAverage.prototype._wrapPosition = function (i) {
  37098. var max = this._samples.length;
  37099. return ((i % max) + max) % max;
  37100. };
  37101. return RollingAverage;
  37102. }());
  37103. BABYLON.RollingAverage = RollingAverage;
  37104. })(BABYLON || (BABYLON = {}));
  37105. //# sourceMappingURL=babylon.performanceMonitor.js.map
  37106. var BABYLON;
  37107. (function (BABYLON) {
  37108. /**
  37109. * This groups together the common properties used for image processing either in direct forward pass
  37110. * or through post processing effect depending on the use of the image processing pipeline in your scene
  37111. * or not.
  37112. */
  37113. var ImageProcessingConfiguration = /** @class */ (function () {
  37114. function ImageProcessingConfiguration() {
  37115. /**
  37116. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  37117. */
  37118. this.colorCurves = new BABYLON.ColorCurves();
  37119. this._colorCurvesEnabled = false;
  37120. this._colorGradingEnabled = false;
  37121. this._colorGradingWithGreenDepth = true;
  37122. this._colorGradingBGR = true;
  37123. this._exposure = 1.0;
  37124. this._toneMappingEnabled = false;
  37125. this._contrast = 1.0;
  37126. /**
  37127. * Vignette stretch size.
  37128. */
  37129. this.vignetteStretch = 0;
  37130. /**
  37131. * Vignette centre X Offset.
  37132. */
  37133. this.vignetteCentreX = 0;
  37134. /**
  37135. * Vignette centre Y Offset.
  37136. */
  37137. this.vignetteCentreY = 0;
  37138. /**
  37139. * Vignette weight or intensity of the vignette effect.
  37140. */
  37141. this.vignetteWeight = 1.5;
  37142. /**
  37143. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  37144. * if vignetteEnabled is set to true.
  37145. */
  37146. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  37147. /**
  37148. * Camera field of view used by the Vignette effect.
  37149. */
  37150. this.vignetteCameraFov = 0.5;
  37151. this._grainEnabled = false;
  37152. this._grainIntensity = 30;
  37153. this._grainAnimated = false;
  37154. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  37155. this._vignetteEnabled = false;
  37156. this._applyByPostProcess = false;
  37157. this._isEnabled = true;
  37158. /**
  37159. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  37160. * @type {BABYLON.Observable}
  37161. */
  37162. this.onUpdateParameters = new BABYLON.Observable();
  37163. }
  37164. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  37165. /**
  37166. * Gets wether the color curves effect is enabled.
  37167. */
  37168. get: function () {
  37169. return this._colorCurvesEnabled;
  37170. },
  37171. /**
  37172. * Sets wether the color curves effect is enabled.
  37173. */
  37174. set: function (value) {
  37175. if (this._colorCurvesEnabled === value) {
  37176. return;
  37177. }
  37178. this._colorCurvesEnabled = value;
  37179. this._updateParameters();
  37180. },
  37181. enumerable: true,
  37182. configurable: true
  37183. });
  37184. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  37185. /**
  37186. * Gets wether the color grading effect is enabled.
  37187. */
  37188. get: function () {
  37189. return this._colorGradingEnabled;
  37190. },
  37191. /**
  37192. * Sets wether the color grading effect is enabled.
  37193. */
  37194. set: function (value) {
  37195. if (this._colorGradingEnabled === value) {
  37196. return;
  37197. }
  37198. this._colorGradingEnabled = value;
  37199. this._updateParameters();
  37200. },
  37201. enumerable: true,
  37202. configurable: true
  37203. });
  37204. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  37205. /**
  37206. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  37207. */
  37208. get: function () {
  37209. return this._colorGradingWithGreenDepth;
  37210. },
  37211. /**
  37212. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  37213. */
  37214. set: function (value) {
  37215. if (this._colorGradingWithGreenDepth === value) {
  37216. return;
  37217. }
  37218. this._colorGradingWithGreenDepth = value;
  37219. this._updateParameters();
  37220. },
  37221. enumerable: true,
  37222. configurable: true
  37223. });
  37224. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  37225. /**
  37226. * Gets wether the color grading texture contains BGR values.
  37227. */
  37228. get: function () {
  37229. return this._colorGradingBGR;
  37230. },
  37231. /**
  37232. * Sets wether the color grading texture contains BGR values.
  37233. */
  37234. set: function (value) {
  37235. if (this._colorGradingBGR === value) {
  37236. return;
  37237. }
  37238. this._colorGradingBGR = value;
  37239. this._updateParameters();
  37240. },
  37241. enumerable: true,
  37242. configurable: true
  37243. });
  37244. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  37245. /**
  37246. * Gets the Exposure used in the effect.
  37247. */
  37248. get: function () {
  37249. return this._exposure;
  37250. },
  37251. /**
  37252. * Sets the Exposure used in the effect.
  37253. */
  37254. set: function (value) {
  37255. if (this._exposure === value) {
  37256. return;
  37257. }
  37258. this._exposure = value;
  37259. this._updateParameters();
  37260. },
  37261. enumerable: true,
  37262. configurable: true
  37263. });
  37264. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  37265. /**
  37266. * Gets wether the tone mapping effect is enabled.
  37267. */
  37268. get: function () {
  37269. return this._toneMappingEnabled;
  37270. },
  37271. /**
  37272. * Sets wether the tone mapping effect is enabled.
  37273. */
  37274. set: function (value) {
  37275. if (this._toneMappingEnabled === value) {
  37276. return;
  37277. }
  37278. this._toneMappingEnabled = value;
  37279. this._updateParameters();
  37280. },
  37281. enumerable: true,
  37282. configurable: true
  37283. });
  37284. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  37285. /**
  37286. * Gets the contrast used in the effect.
  37287. */
  37288. get: function () {
  37289. return this._contrast;
  37290. },
  37291. /**
  37292. * Sets the contrast used in the effect.
  37293. */
  37294. set: function (value) {
  37295. if (this._contrast === value) {
  37296. return;
  37297. }
  37298. this._contrast = value;
  37299. this._updateParameters();
  37300. },
  37301. enumerable: true,
  37302. configurable: true
  37303. });
  37304. Object.defineProperty(ImageProcessingConfiguration.prototype, "grainEnabled", {
  37305. /**
  37306. * If the grain effect should be enabled.
  37307. */
  37308. get: function () {
  37309. return this._grainEnabled;
  37310. },
  37311. set: function (value) {
  37312. if (this._grainEnabled === value) {
  37313. return;
  37314. }
  37315. this._grainEnabled = value;
  37316. this._updateParameters();
  37317. },
  37318. enumerable: true,
  37319. configurable: true
  37320. });
  37321. Object.defineProperty(ImageProcessingConfiguration.prototype, "grainIntensity", {
  37322. /**
  37323. * Amount of grain to be applied by the grain effect.
  37324. */
  37325. get: function () {
  37326. return this._grainIntensity;
  37327. },
  37328. set: function (value) {
  37329. if (this._grainIntensity === value) {
  37330. return;
  37331. }
  37332. this._grainIntensity = value;
  37333. },
  37334. enumerable: true,
  37335. configurable: true
  37336. });
  37337. Object.defineProperty(ImageProcessingConfiguration.prototype, "grainAnimated", {
  37338. /**
  37339. * If the grain effect should be animated.
  37340. */
  37341. get: function () {
  37342. return this._grainAnimated;
  37343. },
  37344. set: function (value) {
  37345. if (this._grainAnimated === value) {
  37346. return;
  37347. }
  37348. this._grainAnimated = value;
  37349. this._updateParameters();
  37350. },
  37351. enumerable: true,
  37352. configurable: true
  37353. });
  37354. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  37355. /**
  37356. * Gets the vignette blend mode allowing different kind of effect.
  37357. */
  37358. get: function () {
  37359. return this._vignetteBlendMode;
  37360. },
  37361. /**
  37362. * Sets the vignette blend mode allowing different kind of effect.
  37363. */
  37364. set: function (value) {
  37365. if (this._vignetteBlendMode === value) {
  37366. return;
  37367. }
  37368. this._vignetteBlendMode = value;
  37369. this._updateParameters();
  37370. },
  37371. enumerable: true,
  37372. configurable: true
  37373. });
  37374. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  37375. /**
  37376. * Gets wether the vignette effect is enabled.
  37377. */
  37378. get: function () {
  37379. return this._vignetteEnabled;
  37380. },
  37381. /**
  37382. * Sets wether the vignette effect is enabled.
  37383. */
  37384. set: function (value) {
  37385. if (this._vignetteEnabled === value) {
  37386. return;
  37387. }
  37388. this._vignetteEnabled = value;
  37389. this._updateParameters();
  37390. },
  37391. enumerable: true,
  37392. configurable: true
  37393. });
  37394. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  37395. /**
  37396. * Gets wether the image processing is applied through a post process or not.
  37397. */
  37398. get: function () {
  37399. return this._applyByPostProcess;
  37400. },
  37401. /**
  37402. * Sets wether the image processing is applied through a post process or not.
  37403. */
  37404. set: function (value) {
  37405. if (this._applyByPostProcess === value) {
  37406. return;
  37407. }
  37408. this._applyByPostProcess = value;
  37409. this._updateParameters();
  37410. },
  37411. enumerable: true,
  37412. configurable: true
  37413. });
  37414. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  37415. /**
  37416. * Gets wether the image processing is enabled or not.
  37417. */
  37418. get: function () {
  37419. return this._isEnabled;
  37420. },
  37421. /**
  37422. * Sets wether the image processing is enabled or not.
  37423. */
  37424. set: function (value) {
  37425. if (this._isEnabled === value) {
  37426. return;
  37427. }
  37428. this._isEnabled = value;
  37429. this._updateParameters();
  37430. },
  37431. enumerable: true,
  37432. configurable: true
  37433. });
  37434. /**
  37435. * Method called each time the image processing information changes requires to recompile the effect.
  37436. */
  37437. ImageProcessingConfiguration.prototype._updateParameters = function () {
  37438. this.onUpdateParameters.notifyObservers(this);
  37439. };
  37440. ImageProcessingConfiguration.prototype.getClassName = function () {
  37441. return "ImageProcessingConfiguration";
  37442. };
  37443. /**
  37444. * Prepare the list of uniforms associated with the Image Processing effects.
  37445. * @param uniformsList The list of uniforms used in the effect
  37446. * @param defines the list of defines currently in use
  37447. */
  37448. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  37449. if (defines.EXPOSURE) {
  37450. uniforms.push("exposureLinear");
  37451. }
  37452. if (defines.CONTRAST) {
  37453. uniforms.push("contrast");
  37454. }
  37455. if (defines.COLORGRADING) {
  37456. uniforms.push("colorTransformSettings");
  37457. }
  37458. if (defines.VIGNETTE) {
  37459. uniforms.push("vInverseScreenSize");
  37460. uniforms.push("vignetteSettings1");
  37461. uniforms.push("vignetteSettings2");
  37462. }
  37463. if (defines.COLORCURVES) {
  37464. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  37465. }
  37466. if (defines.GRAIN) {
  37467. uniforms.push("grainVarianceAmount");
  37468. uniforms.push("grainAnimatedSeed");
  37469. }
  37470. };
  37471. /**
  37472. * Prepare the list of samplers associated with the Image Processing effects.
  37473. * @param uniformsList The list of uniforms used in the effect
  37474. * @param defines the list of defines currently in use
  37475. */
  37476. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  37477. if (defines.COLORGRADING) {
  37478. samplersList.push("txColorTransform");
  37479. }
  37480. };
  37481. /**
  37482. * Prepare the list of defines associated to the shader.
  37483. * @param defines the list of defines to complete
  37484. */
  37485. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  37486. if (forPostProcess === void 0) { forPostProcess = false; }
  37487. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  37488. defines.VIGNETTE = false;
  37489. defines.TONEMAPPING = false;
  37490. defines.CONTRAST = false;
  37491. defines.EXPOSURE = false;
  37492. defines.COLORCURVES = false;
  37493. defines.COLORGRADING = false;
  37494. defines.COLORGRADING3D = false;
  37495. defines.IMAGEPROCESSING = false;
  37496. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  37497. return;
  37498. }
  37499. defines.VIGNETTE = this.vignetteEnabled;
  37500. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  37501. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  37502. defines.TONEMAPPING = this.toneMappingEnabled;
  37503. defines.CONTRAST = (this.contrast !== 1.0);
  37504. defines.EXPOSURE = (this.exposure !== 1.0);
  37505. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  37506. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  37507. if (defines.COLORGRADING) {
  37508. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  37509. }
  37510. else {
  37511. defines.COLORGRADING3D = false;
  37512. }
  37513. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  37514. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  37515. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  37516. defines.GRAIN = this.grainEnabled;
  37517. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING || defines.GRAIN;
  37518. };
  37519. /**
  37520. * Returns true if all the image processing information are ready.
  37521. */
  37522. ImageProcessingConfiguration.prototype.isReady = function () {
  37523. // Color Grading texure can not be none blocking.
  37524. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  37525. };
  37526. /**
  37527. * Binds the image processing to the shader.
  37528. * @param effect The effect to bind to
  37529. */
  37530. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  37531. if (aspectRatio === void 0) { aspectRatio = 1; }
  37532. // Color Curves
  37533. if (this._colorCurvesEnabled && this.colorCurves) {
  37534. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  37535. }
  37536. // Vignette
  37537. if (this._vignetteEnabled) {
  37538. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  37539. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  37540. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  37541. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  37542. var vignetteScaleX = vignetteScaleY * aspectRatio;
  37543. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  37544. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  37545. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  37546. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  37547. var vignettePower = -2.0 * this.vignetteWeight;
  37548. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  37549. }
  37550. // Exposure
  37551. effect.setFloat("exposureLinear", this.exposure);
  37552. // Contrast
  37553. effect.setFloat("contrast", this.contrast);
  37554. // Color transform settings
  37555. if (this.colorGradingTexture) {
  37556. effect.setTexture("txColorTransform", this.colorGradingTexture);
  37557. var textureSize = this.colorGradingTexture.getSize().height;
  37558. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  37559. 0.5 / textureSize, // textureOffset
  37560. textureSize, // textureSize
  37561. this.colorGradingTexture.level // weight
  37562. );
  37563. }
  37564. effect.setFloat("grainVarianceAmount", this.grainIntensity);
  37565. effect.setFloat("grainAnimatedSeed", this.grainAnimated ? Math.random() + 1 : 1);
  37566. };
  37567. /**
  37568. * Clones the current image processing instance.
  37569. * @return The cloned image processing
  37570. */
  37571. ImageProcessingConfiguration.prototype.clone = function () {
  37572. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  37573. };
  37574. /**
  37575. * Serializes the current image processing instance to a json representation.
  37576. * @return a JSON representation
  37577. */
  37578. ImageProcessingConfiguration.prototype.serialize = function () {
  37579. return BABYLON.SerializationHelper.Serialize(this);
  37580. };
  37581. /**
  37582. * Parses the image processing from a json representation.
  37583. * @param source the JSON source to parse
  37584. * @return The parsed image processing
  37585. */
  37586. ImageProcessingConfiguration.Parse = function (source) {
  37587. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  37588. };
  37589. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  37590. /**
  37591. * Used to apply the vignette as a mix with the pixel color.
  37592. */
  37593. get: function () {
  37594. return this._VIGNETTEMODE_MULTIPLY;
  37595. },
  37596. enumerable: true,
  37597. configurable: true
  37598. });
  37599. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  37600. /**
  37601. * Used to apply the vignette as a replacement of the pixel color.
  37602. */
  37603. get: function () {
  37604. return this._VIGNETTEMODE_OPAQUE;
  37605. },
  37606. enumerable: true,
  37607. configurable: true
  37608. });
  37609. // Static constants associated to the image processing.
  37610. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  37611. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  37612. __decorate([
  37613. BABYLON.serializeAsColorCurves()
  37614. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  37615. __decorate([
  37616. BABYLON.serialize()
  37617. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  37618. __decorate([
  37619. BABYLON.serializeAsTexture()
  37620. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  37621. __decorate([
  37622. BABYLON.serialize()
  37623. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  37624. __decorate([
  37625. BABYLON.serialize()
  37626. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  37627. __decorate([
  37628. BABYLON.serialize()
  37629. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  37630. __decorate([
  37631. BABYLON.serialize()
  37632. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  37633. __decorate([
  37634. BABYLON.serialize()
  37635. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  37636. __decorate([
  37637. BABYLON.serialize()
  37638. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  37639. __decorate([
  37640. BABYLON.serialize()
  37641. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  37642. __decorate([
  37643. BABYLON.serialize()
  37644. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  37645. __decorate([
  37646. BABYLON.serialize()
  37647. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  37648. __decorate([
  37649. BABYLON.serialize()
  37650. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  37651. __decorate([
  37652. BABYLON.serializeAsColor4()
  37653. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  37654. __decorate([
  37655. BABYLON.serialize()
  37656. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  37657. __decorate([
  37658. BABYLON.serialize()
  37659. ], ImageProcessingConfiguration.prototype, "_grainEnabled", void 0);
  37660. __decorate([
  37661. BABYLON.serialize()
  37662. ], ImageProcessingConfiguration.prototype, "_grainIntensity", void 0);
  37663. __decorate([
  37664. BABYLON.serialize()
  37665. ], ImageProcessingConfiguration.prototype, "_grainAnimated", void 0);
  37666. __decorate([
  37667. BABYLON.serialize()
  37668. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  37669. __decorate([
  37670. BABYLON.serialize()
  37671. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  37672. __decorate([
  37673. BABYLON.serialize()
  37674. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  37675. __decorate([
  37676. BABYLON.serialize()
  37677. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  37678. return ImageProcessingConfiguration;
  37679. }());
  37680. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  37681. })(BABYLON || (BABYLON = {}));
  37682. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  37683. var BABYLON;
  37684. (function (BABYLON) {
  37685. /**
  37686. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  37687. * It can help converting any input color in a desired output one. This can then be used to create effects
  37688. * from sepia, black and white to sixties or futuristic rendering...
  37689. *
  37690. * The only supported format is currently 3dl.
  37691. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  37692. */
  37693. var ColorGradingTexture = /** @class */ (function (_super) {
  37694. __extends(ColorGradingTexture, _super);
  37695. /**
  37696. * Instantiates a ColorGradingTexture from the following parameters.
  37697. *
  37698. * @param url The location of the color gradind data (currently only supporting 3dl)
  37699. * @param scene The scene the texture will be used in
  37700. */
  37701. function ColorGradingTexture(url, scene) {
  37702. var _this = _super.call(this, scene) || this;
  37703. if (!url) {
  37704. return _this;
  37705. }
  37706. _this._engine = scene.getEngine();
  37707. _this._textureMatrix = BABYLON.Matrix.Identity();
  37708. _this.name = url;
  37709. _this.url = url;
  37710. _this.hasAlpha = false;
  37711. _this.isCube = false;
  37712. _this.is3D = _this._engine.webGLVersion > 1;
  37713. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  37714. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  37715. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  37716. _this.anisotropicFilteringLevel = 1;
  37717. _this._texture = _this._getFromCache(url, true);
  37718. if (!_this._texture) {
  37719. if (!scene.useDelayedTextureLoading) {
  37720. _this.loadTexture();
  37721. }
  37722. else {
  37723. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  37724. }
  37725. }
  37726. return _this;
  37727. }
  37728. /**
  37729. * Returns the texture matrix used in most of the material.
  37730. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  37731. */
  37732. ColorGradingTexture.prototype.getTextureMatrix = function () {
  37733. return this._textureMatrix;
  37734. };
  37735. /**
  37736. * Occurs when the file being loaded is a .3dl LUT file.
  37737. */
  37738. ColorGradingTexture.prototype.load3dlTexture = function () {
  37739. var engine = this._engine;
  37740. var texture;
  37741. if (engine.webGLVersion === 1) {
  37742. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  37743. }
  37744. else {
  37745. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  37746. }
  37747. this._texture = texture;
  37748. var callback = function (text) {
  37749. if (typeof text !== "string") {
  37750. return;
  37751. }
  37752. var data = null;
  37753. var tempData = null;
  37754. var line;
  37755. var lines = text.split('\n');
  37756. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  37757. var maxColor = 0;
  37758. for (var i = 0; i < lines.length; i++) {
  37759. line = lines[i];
  37760. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  37761. continue;
  37762. if (line.indexOf('#') === 0)
  37763. continue;
  37764. var words = line.split(" ");
  37765. if (size === 0) {
  37766. // Number of space + one
  37767. size = words.length;
  37768. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  37769. tempData = new Float32Array(size * size * size * 4);
  37770. continue;
  37771. }
  37772. if (size != 0) {
  37773. var r = Math.max(parseInt(words[0]), 0);
  37774. var g = Math.max(parseInt(words[1]), 0);
  37775. var b = Math.max(parseInt(words[2]), 0);
  37776. maxColor = Math.max(r, maxColor);
  37777. maxColor = Math.max(g, maxColor);
  37778. maxColor = Math.max(b, maxColor);
  37779. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  37780. if (tempData) {
  37781. tempData[pixelStorageIndex + 0] = r;
  37782. tempData[pixelStorageIndex + 1] = g;
  37783. tempData[pixelStorageIndex + 2] = b;
  37784. }
  37785. pixelIndexSlice++;
  37786. if (pixelIndexSlice % size == 0) {
  37787. pixelIndexH++;
  37788. pixelIndexSlice = 0;
  37789. if (pixelIndexH % size == 0) {
  37790. pixelIndexW++;
  37791. pixelIndexH = 0;
  37792. }
  37793. }
  37794. }
  37795. }
  37796. if (tempData && data) {
  37797. for (var i = 0; i < tempData.length; i++) {
  37798. if (i > 0 && (i + 1) % 4 === 0) {
  37799. data[i] = 255;
  37800. }
  37801. else {
  37802. var value = tempData[i];
  37803. data[i] = (value / maxColor * 255);
  37804. }
  37805. }
  37806. }
  37807. if (texture.is3D) {
  37808. texture.updateSize(size, size, size);
  37809. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  37810. }
  37811. else {
  37812. texture.updateSize(size * size, size);
  37813. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  37814. }
  37815. };
  37816. var scene = this.getScene();
  37817. if (scene) {
  37818. scene._loadFile(this.url, callback);
  37819. }
  37820. else {
  37821. this._engine._loadFile(this.url, callback);
  37822. }
  37823. return this._texture;
  37824. };
  37825. /**
  37826. * Starts the loading process of the texture.
  37827. */
  37828. ColorGradingTexture.prototype.loadTexture = function () {
  37829. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  37830. this.load3dlTexture();
  37831. }
  37832. };
  37833. /**
  37834. * Clones the color gradind texture.
  37835. */
  37836. ColorGradingTexture.prototype.clone = function () {
  37837. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  37838. // Base texture
  37839. newTexture.level = this.level;
  37840. return newTexture;
  37841. };
  37842. /**
  37843. * Called during delayed load for textures.
  37844. */
  37845. ColorGradingTexture.prototype.delayLoad = function () {
  37846. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  37847. return;
  37848. }
  37849. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  37850. this._texture = this._getFromCache(this.url, true);
  37851. if (!this._texture) {
  37852. this.loadTexture();
  37853. }
  37854. };
  37855. /**
  37856. * Parses a color grading texture serialized by Babylon.
  37857. * @param parsedTexture The texture information being parsedTexture
  37858. * @param scene The scene to load the texture in
  37859. * @param rootUrl The root url of the data assets to load
  37860. * @return A color gradind texture
  37861. */
  37862. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  37863. var texture = null;
  37864. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  37865. texture = new ColorGradingTexture(parsedTexture.name, scene);
  37866. texture.name = parsedTexture.name;
  37867. texture.level = parsedTexture.level;
  37868. }
  37869. return texture;
  37870. };
  37871. /**
  37872. * Serializes the LUT texture to json format.
  37873. */
  37874. ColorGradingTexture.prototype.serialize = function () {
  37875. if (!this.name) {
  37876. return null;
  37877. }
  37878. var serializationObject = {};
  37879. serializationObject.name = this.name;
  37880. serializationObject.level = this.level;
  37881. serializationObject.customType = "BABYLON.ColorGradingTexture";
  37882. return serializationObject;
  37883. };
  37884. /**
  37885. * Empty line regex stored for GC.
  37886. */
  37887. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  37888. return ColorGradingTexture;
  37889. }(BABYLON.BaseTexture));
  37890. BABYLON.ColorGradingTexture = ColorGradingTexture;
  37891. })(BABYLON || (BABYLON = {}));
  37892. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  37893. var BABYLON;
  37894. (function (BABYLON) {
  37895. /**
  37896. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  37897. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  37898. * These are similar to controls found in many professional imaging or colorist software. The global controls are applied to the entire image. For advanced tuning, extra controls are provided to adjust the shadow, midtone and highlight areas of the image;
  37899. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  37900. */
  37901. var ColorCurves = /** @class */ (function () {
  37902. function ColorCurves() {
  37903. this._dirty = true;
  37904. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  37905. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  37906. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  37907. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  37908. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  37909. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  37910. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  37911. this._globalHue = 30;
  37912. this._globalDensity = 0;
  37913. this._globalSaturation = 0;
  37914. this._globalExposure = 0;
  37915. this._highlightsHue = 30;
  37916. this._highlightsDensity = 0;
  37917. this._highlightsSaturation = 0;
  37918. this._highlightsExposure = 0;
  37919. this._midtonesHue = 30;
  37920. this._midtonesDensity = 0;
  37921. this._midtonesSaturation = 0;
  37922. this._midtonesExposure = 0;
  37923. this._shadowsHue = 30;
  37924. this._shadowsDensity = 0;
  37925. this._shadowsSaturation = 0;
  37926. this._shadowsExposure = 0;
  37927. }
  37928. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  37929. /**
  37930. * Gets the global Hue value.
  37931. * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).
  37932. */
  37933. get: function () {
  37934. return this._globalHue;
  37935. },
  37936. /**
  37937. * Sets the global Hue value.
  37938. * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).
  37939. */
  37940. set: function (value) {
  37941. this._globalHue = value;
  37942. this._dirty = true;
  37943. },
  37944. enumerable: true,
  37945. configurable: true
  37946. });
  37947. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  37948. /**
  37949. * Gets the global Density value.
  37950. * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.
  37951. * Values less than zero provide a filter of opposite hue.
  37952. */
  37953. get: function () {
  37954. return this._globalDensity;
  37955. },
  37956. /**
  37957. * Sets the global Density value.
  37958. * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.
  37959. * Values less than zero provide a filter of opposite hue.
  37960. */
  37961. set: function (value) {
  37962. this._globalDensity = value;
  37963. this._dirty = true;
  37964. },
  37965. enumerable: true,
  37966. configurable: true
  37967. });
  37968. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  37969. /**
  37970. * Gets the global Saturation value.
  37971. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
  37972. */
  37973. get: function () {
  37974. return this._globalSaturation;
  37975. },
  37976. /**
  37977. * Sets the global Saturation value.
  37978. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
  37979. */
  37980. set: function (value) {
  37981. this._globalSaturation = value;
  37982. this._dirty = true;
  37983. },
  37984. enumerable: true,
  37985. configurable: true
  37986. });
  37987. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  37988. /**
  37989. * Gets the highlights Hue value.
  37990. * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).
  37991. */
  37992. get: function () {
  37993. return this._highlightsHue;
  37994. },
  37995. /**
  37996. * Sets the highlights Hue value.
  37997. * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).
  37998. */
  37999. set: function (value) {
  38000. this._highlightsHue = value;
  38001. this._dirty = true;
  38002. },
  38003. enumerable: true,
  38004. configurable: true
  38005. });
  38006. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  38007. /**
  38008. * Gets the highlights Density value.
  38009. * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.
  38010. * Values less than zero provide a filter of opposite hue.
  38011. */
  38012. get: function () {
  38013. return this._highlightsDensity;
  38014. },
  38015. /**
  38016. * Sets the highlights Density value.
  38017. * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.
  38018. * Values less than zero provide a filter of opposite hue.
  38019. */
  38020. set: function (value) {
  38021. this._highlightsDensity = value;
  38022. this._dirty = true;
  38023. },
  38024. enumerable: true,
  38025. configurable: true
  38026. });
  38027. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  38028. /**
  38029. * Gets the highlights Saturation value.
  38030. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
  38031. */
  38032. get: function () {
  38033. return this._highlightsSaturation;
  38034. },
  38035. /**
  38036. * Sets the highlights Saturation value.
  38037. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
  38038. */
  38039. set: function (value) {
  38040. this._highlightsSaturation = value;
  38041. this._dirty = true;
  38042. },
  38043. enumerable: true,
  38044. configurable: true
  38045. });
  38046. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  38047. /**
  38048. * Gets the highlights Exposure value.
  38049. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure.
  38050. */
  38051. get: function () {
  38052. return this._highlightsExposure;
  38053. },
  38054. /**
  38055. * Sets the highlights Exposure value.
  38056. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure.
  38057. */
  38058. set: function (value) {
  38059. this._highlightsExposure = value;
  38060. this._dirty = true;
  38061. },
  38062. enumerable: true,
  38063. configurable: true
  38064. });
  38065. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  38066. /**
  38067. * Gets the midtones Hue value.
  38068. * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).
  38069. */
  38070. get: function () {
  38071. return this._midtonesHue;
  38072. },
  38073. /**
  38074. * Sets the midtones Hue value.
  38075. * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).
  38076. */
  38077. set: function (value) {
  38078. this._midtonesHue = value;
  38079. this._dirty = true;
  38080. },
  38081. enumerable: true,
  38082. configurable: true
  38083. });
  38084. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  38085. /**
  38086. * Gets the midtones Density value.
  38087. * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.
  38088. * Values less than zero provide a filter of opposite hue.
  38089. */
  38090. get: function () {
  38091. return this._midtonesDensity;
  38092. },
  38093. /**
  38094. * Sets the midtones Density value.
  38095. * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.
  38096. * Values less than zero provide a filter of opposite hue.
  38097. */
  38098. set: function (value) {
  38099. this._midtonesDensity = value;
  38100. this._dirty = true;
  38101. },
  38102. enumerable: true,
  38103. configurable: true
  38104. });
  38105. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  38106. /**
  38107. * Gets the midtones Saturation value.
  38108. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
  38109. */
  38110. get: function () {
  38111. return this._midtonesSaturation;
  38112. },
  38113. /**
  38114. * Sets the midtones Saturation value.
  38115. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
  38116. */
  38117. set: function (value) {
  38118. this._midtonesSaturation = value;
  38119. this._dirty = true;
  38120. },
  38121. enumerable: true,
  38122. configurable: true
  38123. });
  38124. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  38125. /**
  38126. * Gets the midtones Exposure value.
  38127. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure.
  38128. */
  38129. get: function () {
  38130. return this._midtonesExposure;
  38131. },
  38132. /**
  38133. * Sets the midtones Exposure value.
  38134. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure.
  38135. */
  38136. set: function (value) {
  38137. this._midtonesExposure = value;
  38138. this._dirty = true;
  38139. },
  38140. enumerable: true,
  38141. configurable: true
  38142. });
  38143. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  38144. /**
  38145. * Gets the shadows Hue value.
  38146. * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).
  38147. */
  38148. get: function () {
  38149. return this._shadowsHue;
  38150. },
  38151. /**
  38152. * Sets the shadows Hue value.
  38153. * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).
  38154. */
  38155. set: function (value) {
  38156. this._shadowsHue = value;
  38157. this._dirty = true;
  38158. },
  38159. enumerable: true,
  38160. configurable: true
  38161. });
  38162. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  38163. /**
  38164. * Gets the shadows Density value.
  38165. * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.
  38166. * Values less than zero provide a filter of opposite hue.
  38167. */
  38168. get: function () {
  38169. return this._shadowsDensity;
  38170. },
  38171. /**
  38172. * Sets the shadows Density value.
  38173. * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.
  38174. * Values less than zero provide a filter of opposite hue.
  38175. */
  38176. set: function (value) {
  38177. this._shadowsDensity = value;
  38178. this._dirty = true;
  38179. },
  38180. enumerable: true,
  38181. configurable: true
  38182. });
  38183. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  38184. /**
  38185. * Gets the shadows Saturation value.
  38186. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
  38187. */
  38188. get: function () {
  38189. return this._shadowsSaturation;
  38190. },
  38191. /**
  38192. * Sets the shadows Saturation value.
  38193. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
  38194. */
  38195. set: function (value) {
  38196. this._shadowsSaturation = value;
  38197. this._dirty = true;
  38198. },
  38199. enumerable: true,
  38200. configurable: true
  38201. });
  38202. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  38203. /**
  38204. * Gets the shadows Exposure value.
  38205. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure.
  38206. */
  38207. get: function () {
  38208. return this._shadowsExposure;
  38209. },
  38210. /**
  38211. * Sets the shadows Exposure value.
  38212. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure.
  38213. */
  38214. set: function (value) {
  38215. this._shadowsExposure = value;
  38216. this._dirty = true;
  38217. },
  38218. enumerable: true,
  38219. configurable: true
  38220. });
  38221. ColorCurves.prototype.getClassName = function () {
  38222. return "ColorCurves";
  38223. };
  38224. /**
  38225. * Binds the color curves to the shader.
  38226. * @param colorCurves The color curve to bind
  38227. * @param effect The effect to bind to
  38228. */
  38229. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  38230. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  38231. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  38232. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  38233. if (colorCurves._dirty) {
  38234. colorCurves._dirty = false;
  38235. // Fill in global info.
  38236. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  38237. // Compute highlights info.
  38238. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  38239. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  38240. // Compute midtones info.
  38241. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  38242. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  38243. // Compute shadows info.
  38244. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  38245. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  38246. // Compute deltas (neutral is midtones).
  38247. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  38248. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  38249. }
  38250. if (effect) {
  38251. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  38252. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  38253. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  38254. }
  38255. };
  38256. /**
  38257. * Prepare the list of uniforms associated with the ColorCurves effects.
  38258. * @param uniformsList The list of uniforms used in the effect
  38259. */
  38260. ColorCurves.PrepareUniforms = function (uniformsList) {
  38261. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  38262. };
  38263. /**
  38264. * Returns color grading data based on a hue, density, saturation and exposure value.
  38265. * @param filterHue The hue of the color filter.
  38266. * @param filterDensity The density of the color filter.
  38267. * @param saturation The saturation.
  38268. * @param exposure The exposure.
  38269. * @param result The result data container.
  38270. */
  38271. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  38272. if (hue == null) {
  38273. return;
  38274. }
  38275. hue = ColorCurves.clamp(hue, 0, 360);
  38276. density = ColorCurves.clamp(density, -100, 100);
  38277. saturation = ColorCurves.clamp(saturation, -100, 100);
  38278. exposure = ColorCurves.clamp(exposure, -100, 100);
  38279. // Remap the slider/config filter density with non-linear mapping and also scale by half
  38280. // so that the maximum filter density is only 50% control. This provides fine control
  38281. // for small values and reasonable range.
  38282. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  38283. density *= 0.5;
  38284. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  38285. if (density < 0) {
  38286. density *= -1;
  38287. hue = (hue + 180) % 360;
  38288. }
  38289. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  38290. result.scaleToRef(2, result);
  38291. result.a = 1 + 0.01 * saturation;
  38292. };
  38293. /**
  38294. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  38295. * @param value The input slider value in range [-100,100].
  38296. * @returns Adjusted value.
  38297. */
  38298. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  38299. value /= 100;
  38300. var x = Math.abs(value);
  38301. x = Math.pow(x, 2);
  38302. if (value < 0) {
  38303. x *= -1;
  38304. }
  38305. x *= 100;
  38306. return x;
  38307. };
  38308. /**
  38309. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  38310. * @param hue The hue (H) input.
  38311. * @param saturation The saturation (S) input.
  38312. * @param brightness The brightness (B) input.
  38313. * @result An RGBA color represented as Vector4.
  38314. */
  38315. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  38316. var h = ColorCurves.clamp(hue, 0, 360);
  38317. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  38318. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  38319. if (s === 0) {
  38320. result.r = v;
  38321. result.g = v;
  38322. result.b = v;
  38323. }
  38324. else {
  38325. // sector 0 to 5
  38326. h /= 60;
  38327. var i = Math.floor(h);
  38328. // fractional part of h
  38329. var f = h - i;
  38330. var p = v * (1 - s);
  38331. var q = v * (1 - s * f);
  38332. var t = v * (1 - s * (1 - f));
  38333. switch (i) {
  38334. case 0:
  38335. result.r = v;
  38336. result.g = t;
  38337. result.b = p;
  38338. break;
  38339. case 1:
  38340. result.r = q;
  38341. result.g = v;
  38342. result.b = p;
  38343. break;
  38344. case 2:
  38345. result.r = p;
  38346. result.g = v;
  38347. result.b = t;
  38348. break;
  38349. case 3:
  38350. result.r = p;
  38351. result.g = q;
  38352. result.b = v;
  38353. break;
  38354. case 4:
  38355. result.r = t;
  38356. result.g = p;
  38357. result.b = v;
  38358. break;
  38359. default:// case 5:
  38360. result.r = v;
  38361. result.g = p;
  38362. result.b = q;
  38363. break;
  38364. }
  38365. }
  38366. result.a = 1;
  38367. };
  38368. /**
  38369. * Returns a value clamped between min and max
  38370. * @param value The value to clamp
  38371. * @param min The minimum of value
  38372. * @param max The maximum of value
  38373. * @returns The clamped value.
  38374. */
  38375. ColorCurves.clamp = function (value, min, max) {
  38376. return Math.min(Math.max(value, min), max);
  38377. };
  38378. /**
  38379. * Clones the current color curve instance.
  38380. * @return The cloned curves
  38381. */
  38382. ColorCurves.prototype.clone = function () {
  38383. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  38384. };
  38385. /**
  38386. * Serializes the current color curve instance to a json representation.
  38387. * @return a JSON representation
  38388. */
  38389. ColorCurves.prototype.serialize = function () {
  38390. return BABYLON.SerializationHelper.Serialize(this);
  38391. };
  38392. /**
  38393. * Parses the color curve from a json representation.
  38394. * @param source the JSON source to parse
  38395. * @return The parsed curves
  38396. */
  38397. ColorCurves.Parse = function (source) {
  38398. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  38399. };
  38400. __decorate([
  38401. BABYLON.serialize()
  38402. ], ColorCurves.prototype, "_globalHue", void 0);
  38403. __decorate([
  38404. BABYLON.serialize()
  38405. ], ColorCurves.prototype, "_globalDensity", void 0);
  38406. __decorate([
  38407. BABYLON.serialize()
  38408. ], ColorCurves.prototype, "_globalSaturation", void 0);
  38409. __decorate([
  38410. BABYLON.serialize()
  38411. ], ColorCurves.prototype, "_globalExposure", void 0);
  38412. __decorate([
  38413. BABYLON.serialize()
  38414. ], ColorCurves.prototype, "_highlightsHue", void 0);
  38415. __decorate([
  38416. BABYLON.serialize()
  38417. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  38418. __decorate([
  38419. BABYLON.serialize()
  38420. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  38421. __decorate([
  38422. BABYLON.serialize()
  38423. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  38424. __decorate([
  38425. BABYLON.serialize()
  38426. ], ColorCurves.prototype, "_midtonesHue", void 0);
  38427. __decorate([
  38428. BABYLON.serialize()
  38429. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  38430. __decorate([
  38431. BABYLON.serialize()
  38432. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  38433. __decorate([
  38434. BABYLON.serialize()
  38435. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  38436. return ColorCurves;
  38437. }());
  38438. BABYLON.ColorCurves = ColorCurves;
  38439. })(BABYLON || (BABYLON = {}));
  38440. //# sourceMappingURL=babylon.colorCurves.js.map
  38441. //# sourceMappingURL=babylon.behavior.js.map
  38442. var BABYLON;
  38443. (function (BABYLON) {
  38444. /**
  38445. * "Static Class" containing the most commonly used helper while dealing with material for
  38446. * rendering purpose.
  38447. *
  38448. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  38449. *
  38450. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  38451. */
  38452. var MaterialHelper = /** @class */ (function () {
  38453. function MaterialHelper() {
  38454. }
  38455. /**
  38456. * Bind the current view position to an effect.
  38457. * @param effect The effect to be bound
  38458. * @param scene The scene the eyes position is used from
  38459. */
  38460. MaterialHelper.BindEyePosition = function (effect, scene) {
  38461. if (scene._forcedViewPosition) {
  38462. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  38463. return;
  38464. }
  38465. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  38466. };
  38467. /**
  38468. * Helps preparing the defines values about the UVs in used in the effect.
  38469. * UVs are shared as much as we can accross chanels in the shaders.
  38470. * @param texture The texture we are preparing the UVs for
  38471. * @param defines The defines to update
  38472. * @param key The chanel key "diffuse", "specular"... used in the shader
  38473. */
  38474. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  38475. defines._needUVs = true;
  38476. defines[key] = true;
  38477. if (texture.getTextureMatrix().isIdentity(true)) {
  38478. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  38479. if (texture.coordinatesIndex === 0) {
  38480. defines["MAINUV1"] = true;
  38481. }
  38482. else {
  38483. defines["MAINUV2"] = true;
  38484. }
  38485. }
  38486. else {
  38487. defines[key + "DIRECTUV"] = 0;
  38488. }
  38489. };
  38490. /**
  38491. * Binds a texture matrix value to its corrsponding uniform
  38492. * @param texture The texture to bind the matrix for
  38493. * @param uniformBuffer The uniform buffer receivin the data
  38494. * @param key The chanel key "diffuse", "specular"... used in the shader
  38495. */
  38496. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  38497. var matrix = texture.getTextureMatrix();
  38498. if (!matrix.isIdentity(true)) {
  38499. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  38500. }
  38501. };
  38502. /**
  38503. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  38504. * @param mesh defines the current mesh
  38505. * @param scene defines the current scene
  38506. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  38507. * @param pointsCloud defines if point cloud rendering has to be turned on
  38508. * @param fogEnabled defines if fog has to be turned on
  38509. * @param alphaTest defines if alpha testing has to be turned on
  38510. * @param defines defines the current list of defines
  38511. */
  38512. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  38513. if (defines._areMiscDirty) {
  38514. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  38515. defines["POINTSIZE"] = (pointsCloud || scene.forcePointsCloud);
  38516. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  38517. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  38518. defines["ALPHATEST"] = alphaTest;
  38519. }
  38520. };
  38521. /**
  38522. * Helper used to prepare the list of defines associated with frame values for shader compilation
  38523. * @param scene defines the current scene
  38524. * @param engine defines the current engine
  38525. * @param defines specifies the list of active defines
  38526. * @param useInstances defines if instances have to be turned on
  38527. * @param useClipPlane defines if clip plane have to be turned on
  38528. */
  38529. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  38530. if (useClipPlane === void 0) { useClipPlane = null; }
  38531. var changed = false;
  38532. if (useClipPlane == null) {
  38533. useClipPlane = (scene.clipPlane !== undefined && scene.clipPlane !== null);
  38534. }
  38535. if (defines["CLIPPLANE"] !== useClipPlane) {
  38536. defines["CLIPPLANE"] = useClipPlane;
  38537. changed = true;
  38538. }
  38539. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  38540. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  38541. changed = true;
  38542. }
  38543. if (defines["INSTANCES"] !== useInstances) {
  38544. defines["INSTANCES"] = useInstances;
  38545. changed = true;
  38546. }
  38547. if (changed) {
  38548. defines.markAsUnprocessed();
  38549. }
  38550. };
  38551. /**
  38552. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  38553. * @param mesh The mesh containing the geometry data we will draw
  38554. * @param defines The defines to update
  38555. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  38556. * @param useBones Precise whether bones should be used or not (override mesh info)
  38557. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  38558. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  38559. * @returns false if defines are considered not dirty and have not been checked
  38560. */
  38561. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  38562. if (useMorphTargets === void 0) { useMorphTargets = false; }
  38563. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  38564. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  38565. return false;
  38566. }
  38567. defines._normals = defines._needNormals;
  38568. defines._uvs = defines._needUVs;
  38569. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  38570. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  38571. defines["TANGENT"] = true;
  38572. }
  38573. if (defines._needUVs) {
  38574. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  38575. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  38576. }
  38577. else {
  38578. defines["UV1"] = false;
  38579. defines["UV2"] = false;
  38580. }
  38581. if (useVertexColor) {
  38582. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  38583. defines["VERTEXCOLOR"] = hasVertexColors;
  38584. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  38585. }
  38586. if (useBones) {
  38587. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  38588. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  38589. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  38590. }
  38591. else {
  38592. defines["NUM_BONE_INFLUENCERS"] = 0;
  38593. defines["BonesPerMesh"] = 0;
  38594. }
  38595. }
  38596. if (useMorphTargets) {
  38597. var manager = mesh.morphTargetManager;
  38598. if (manager) {
  38599. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  38600. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  38601. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  38602. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  38603. }
  38604. else {
  38605. defines["MORPHTARGETS_TANGENT"] = false;
  38606. defines["MORPHTARGETS_NORMAL"] = false;
  38607. defines["MORPHTARGETS"] = false;
  38608. defines["NUM_MORPH_INFLUENCERS"] = 0;
  38609. }
  38610. }
  38611. return true;
  38612. };
  38613. /**
  38614. * Prepares the defines related to the light information passed in parameter
  38615. * @param scene The scene we are intending to draw
  38616. * @param mesh The mesh the effect is compiling for
  38617. * @param defines The defines to update
  38618. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  38619. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  38620. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  38621. * @returns true if normals will be required for the rest of the effect
  38622. */
  38623. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  38624. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  38625. if (disableLighting === void 0) { disableLighting = false; }
  38626. if (!defines._areLightsDirty) {
  38627. return defines._needNormals;
  38628. }
  38629. var lightIndex = 0;
  38630. var needNormals = false;
  38631. var needRebuild = false;
  38632. var lightmapMode = false;
  38633. var shadowEnabled = false;
  38634. var specularEnabled = false;
  38635. if (scene.lightsEnabled && !disableLighting) {
  38636. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  38637. var light = _a[_i];
  38638. needNormals = true;
  38639. if (defines["LIGHT" + lightIndex] === undefined) {
  38640. needRebuild = true;
  38641. }
  38642. defines["LIGHT" + lightIndex] = true;
  38643. defines["SPOTLIGHT" + lightIndex] = false;
  38644. defines["HEMILIGHT" + lightIndex] = false;
  38645. defines["POINTLIGHT" + lightIndex] = false;
  38646. defines["DIRLIGHT" + lightIndex] = false;
  38647. var type;
  38648. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  38649. type = "SPOTLIGHT" + lightIndex;
  38650. var spotLight = light;
  38651. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = spotLight.projectionTexture ? spotLight.projectionTexture.isReady() : false;
  38652. }
  38653. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  38654. type = "HEMILIGHT" + lightIndex;
  38655. }
  38656. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  38657. type = "POINTLIGHT" + lightIndex;
  38658. }
  38659. else {
  38660. type = "DIRLIGHT" + lightIndex;
  38661. }
  38662. defines[type] = true;
  38663. // Specular
  38664. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  38665. specularEnabled = true;
  38666. }
  38667. // Shadows
  38668. defines["SHADOW" + lightIndex] = false;
  38669. defines["SHADOWPCF" + lightIndex] = false;
  38670. defines["SHADOWESM" + lightIndex] = false;
  38671. defines["SHADOWCUBE" + lightIndex] = false;
  38672. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  38673. var shadowGenerator = light.getShadowGenerator();
  38674. if (shadowGenerator) {
  38675. shadowEnabled = true;
  38676. shadowGenerator.prepareDefines(defines, lightIndex);
  38677. }
  38678. }
  38679. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  38680. lightmapMode = true;
  38681. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  38682. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  38683. }
  38684. else {
  38685. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  38686. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  38687. }
  38688. lightIndex++;
  38689. if (lightIndex === maxSimultaneousLights)
  38690. break;
  38691. }
  38692. }
  38693. defines["SPECULARTERM"] = specularEnabled;
  38694. defines["SHADOWS"] = shadowEnabled;
  38695. // Resetting all other lights if any
  38696. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  38697. if (defines["LIGHT" + index] !== undefined) {
  38698. defines["LIGHT" + index] = false;
  38699. defines["HEMILIGHT" + lightIndex] = false;
  38700. defines["POINTLIGHT" + lightIndex] = false;
  38701. defines["DIRLIGHT" + lightIndex] = false;
  38702. defines["SPOTLIGHT" + lightIndex] = false;
  38703. defines["SHADOW" + lightIndex] = false;
  38704. }
  38705. }
  38706. var caps = scene.getEngine().getCaps();
  38707. if (defines["SHADOWFLOAT"] === undefined) {
  38708. needRebuild = true;
  38709. }
  38710. defines["SHADOWFLOAT"] = shadowEnabled &&
  38711. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  38712. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  38713. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  38714. if (needRebuild) {
  38715. defines.rebuild();
  38716. }
  38717. return needNormals;
  38718. };
  38719. /**
  38720. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  38721. * that won t be acctive due to defines being turned off.
  38722. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  38723. * @param samplersList The samplers list
  38724. * @param defines The defines helping in the list generation
  38725. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  38726. */
  38727. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  38728. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  38729. var uniformsList;
  38730. var uniformBuffersList = null;
  38731. if (uniformsListOrOptions.uniformsNames) {
  38732. var options = uniformsListOrOptions;
  38733. uniformsList = options.uniformsNames;
  38734. uniformBuffersList = options.uniformBuffersNames;
  38735. samplersList = options.samplers;
  38736. defines = options.defines;
  38737. maxSimultaneousLights = options.maxSimultaneousLights;
  38738. }
  38739. else {
  38740. uniformsList = uniformsListOrOptions;
  38741. if (!samplersList) {
  38742. samplersList = [];
  38743. }
  38744. }
  38745. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  38746. if (!defines["LIGHT" + lightIndex]) {
  38747. break;
  38748. }
  38749. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  38750. if (uniformBuffersList) {
  38751. uniformBuffersList.push("Light" + lightIndex);
  38752. }
  38753. samplersList.push("shadowSampler" + lightIndex);
  38754. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  38755. samplersList.push("projectionLightSampler" + lightIndex);
  38756. uniformsList.push("textureProjectionMatrix" + lightIndex);
  38757. }
  38758. }
  38759. if (defines["NUM_MORPH_INFLUENCERS"]) {
  38760. uniformsList.push("morphTargetInfluences");
  38761. }
  38762. };
  38763. /**
  38764. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  38765. * @param defines The defines to update while falling back
  38766. * @param fallbacks The authorized effect fallbacks
  38767. * @param maxSimultaneousLights The maximum number of lights allowed
  38768. * @param rank the current rank of the Effect
  38769. * @returns The newly affected rank
  38770. */
  38771. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  38772. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  38773. if (rank === void 0) { rank = 0; }
  38774. var lightFallbackRank = 0;
  38775. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  38776. if (!defines["LIGHT" + lightIndex]) {
  38777. break;
  38778. }
  38779. if (lightIndex > 0) {
  38780. lightFallbackRank = rank + lightIndex;
  38781. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  38782. }
  38783. if (!defines["SHADOWS"]) {
  38784. if (defines["SHADOW" + lightIndex]) {
  38785. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  38786. }
  38787. if (defines["SHADOWPCF" + lightIndex]) {
  38788. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  38789. }
  38790. if (defines["SHADOWESM" + lightIndex]) {
  38791. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  38792. }
  38793. }
  38794. }
  38795. return lightFallbackRank++;
  38796. };
  38797. /**
  38798. * Prepares the list of attributes required for morph targets according to the effect defines.
  38799. * @param attribs The current list of supported attribs
  38800. * @param mesh The mesh to prepare the morph targets attributes for
  38801. * @param defines The current Defines of the effect
  38802. */
  38803. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  38804. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  38805. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  38806. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  38807. var manager = mesh.morphTargetManager;
  38808. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  38809. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  38810. for (var index = 0; index < influencers; index++) {
  38811. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  38812. if (normal) {
  38813. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  38814. }
  38815. if (tangent) {
  38816. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  38817. }
  38818. if (attribs.length > maxAttributesCount) {
  38819. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  38820. }
  38821. }
  38822. }
  38823. };
  38824. /**
  38825. * Prepares the list of attributes required for bones according to the effect defines.
  38826. * @param attribs The current list of supported attribs
  38827. * @param mesh The mesh to prepare the bones attributes for
  38828. * @param defines The current Defines of the effect
  38829. * @param fallbacks The current efffect fallback strategy
  38830. */
  38831. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  38832. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  38833. fallbacks.addCPUSkinningFallback(0, mesh);
  38834. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  38835. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  38836. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  38837. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  38838. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  38839. }
  38840. }
  38841. };
  38842. /**
  38843. * Prepares the list of attributes required for instances according to the effect defines.
  38844. * @param attribs The current list of supported attribs
  38845. * @param defines The current Defines of the effect
  38846. */
  38847. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  38848. if (defines["INSTANCES"]) {
  38849. attribs.push("world0");
  38850. attribs.push("world1");
  38851. attribs.push("world2");
  38852. attribs.push("world3");
  38853. }
  38854. };
  38855. /**
  38856. * Binds the light shadow information to the effect for the given mesh.
  38857. * @param light The light containing the generator
  38858. * @param scene The scene the lights belongs to
  38859. * @param mesh The mesh we are binding the information to render
  38860. * @param lightIndex The light index in the effect used to render the mesh
  38861. * @param effect The effect we are binding the data to
  38862. */
  38863. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  38864. if (light.shadowEnabled && mesh.receiveShadows) {
  38865. var shadowGenerator = light.getShadowGenerator();
  38866. if (shadowGenerator) {
  38867. shadowGenerator.bindShadowLight(lightIndex, effect);
  38868. }
  38869. }
  38870. };
  38871. /**
  38872. * Binds the light information to the effect.
  38873. * @param light The light containing the generator
  38874. * @param effect The effect we are binding the data to
  38875. * @param lightIndex The light index in the effect used to render
  38876. */
  38877. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  38878. light.transferToEffect(effect, lightIndex + "");
  38879. };
  38880. /**
  38881. * Binds the lights information from the scene to the effect for the given mesh.
  38882. * @param scene The scene the lights belongs to
  38883. * @param mesh The mesh we are binding the information to render
  38884. * @param effect The effect we are binding the data to
  38885. * @param defines The generated defines for the effect
  38886. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  38887. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  38888. */
  38889. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  38890. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  38891. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  38892. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  38893. for (var i = 0; i < len; i++) {
  38894. var light = mesh._lightSources[i];
  38895. var iAsString = i.toString();
  38896. var scaledIntensity = light.getScaledIntensity();
  38897. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  38898. MaterialHelper.BindLightProperties(light, effect, i);
  38899. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  38900. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  38901. if (defines["SPECULARTERM"]) {
  38902. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  38903. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  38904. }
  38905. // Shadows
  38906. if (scene.shadowsEnabled) {
  38907. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  38908. }
  38909. light._uniformBuffer.update();
  38910. }
  38911. };
  38912. /**
  38913. * Binds the fog information from the scene to the effect for the given mesh.
  38914. * @param scene The scene the lights belongs to
  38915. * @param mesh The mesh we are binding the information to render
  38916. * @param effect The effect we are binding the data to
  38917. */
  38918. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  38919. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  38920. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  38921. effect.setColor3("vFogColor", scene.fogColor);
  38922. }
  38923. };
  38924. /**
  38925. * Binds the bones information from the mesh to the effect.
  38926. * @param mesh The mesh we are binding the information to render
  38927. * @param effect The effect we are binding the data to
  38928. */
  38929. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  38930. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  38931. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  38932. if (matrices && effect) {
  38933. effect.setMatrices("mBones", matrices);
  38934. }
  38935. }
  38936. };
  38937. /**
  38938. * Binds the morph targets information from the mesh to the effect.
  38939. * @param abstractMesh The mesh we are binding the information to render
  38940. * @param effect The effect we are binding the data to
  38941. */
  38942. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  38943. var manager = abstractMesh.morphTargetManager;
  38944. if (!abstractMesh || !manager) {
  38945. return;
  38946. }
  38947. effect.setFloatArray("morphTargetInfluences", manager.influences);
  38948. };
  38949. /**
  38950. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  38951. * @param defines The generated defines used in the effect
  38952. * @param effect The effect we are binding the data to
  38953. * @param scene The scene we are willing to render with logarithmic scale for
  38954. */
  38955. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  38956. if (defines["LOGARITHMICDEPTH"]) {
  38957. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  38958. }
  38959. };
  38960. /**
  38961. * Binds the clip plane information from the scene to the effect.
  38962. * @param scene The scene the clip plane information are extracted from
  38963. * @param effect The effect we are binding the data to
  38964. */
  38965. MaterialHelper.BindClipPlane = function (effect, scene) {
  38966. if (scene.clipPlane) {
  38967. var clipPlane = scene.clipPlane;
  38968. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  38969. }
  38970. };
  38971. return MaterialHelper;
  38972. }());
  38973. BABYLON.MaterialHelper = MaterialHelper;
  38974. })(BABYLON || (BABYLON = {}));
  38975. //# sourceMappingURL=babylon.materialHelper.js.map
  38976. var BABYLON;
  38977. (function (BABYLON) {
  38978. var PushMaterial = /** @class */ (function (_super) {
  38979. __extends(PushMaterial, _super);
  38980. function PushMaterial(name, scene) {
  38981. var _this = _super.call(this, name, scene) || this;
  38982. _this._normalMatrix = new BABYLON.Matrix();
  38983. _this.storeEffectOnSubMeshes = true;
  38984. return _this;
  38985. }
  38986. PushMaterial.prototype.getEffect = function () {
  38987. return this._activeEffect;
  38988. };
  38989. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  38990. if (!mesh) {
  38991. return false;
  38992. }
  38993. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  38994. return true;
  38995. }
  38996. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  38997. };
  38998. /**
  38999. * Binds the given world matrix to the active effect
  39000. *
  39001. * @param world the matrix to bind
  39002. */
  39003. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  39004. this._activeEffect.setMatrix("world", world);
  39005. };
  39006. /**
  39007. * Binds the given normal matrix to the active effect
  39008. *
  39009. * @param normalMatrix the matrix to bind
  39010. */
  39011. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  39012. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  39013. };
  39014. PushMaterial.prototype.bind = function (world, mesh) {
  39015. if (!mesh) {
  39016. return;
  39017. }
  39018. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  39019. };
  39020. PushMaterial.prototype._afterBind = function (mesh, effect) {
  39021. if (effect === void 0) { effect = null; }
  39022. _super.prototype._afterBind.call(this, mesh);
  39023. this.getScene()._cachedEffect = effect;
  39024. };
  39025. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  39026. if (visibility === void 0) { visibility = 1; }
  39027. return scene.isCachedMaterialInvalid(this, effect, visibility);
  39028. };
  39029. return PushMaterial;
  39030. }(BABYLON.Material));
  39031. BABYLON.PushMaterial = PushMaterial;
  39032. })(BABYLON || (BABYLON = {}));
  39033. //# sourceMappingURL=babylon.pushMaterial.js.map
  39034. var BABYLON;
  39035. (function (BABYLON) {
  39036. /** @ignore */
  39037. var StandardMaterialDefines = /** @class */ (function (_super) {
  39038. __extends(StandardMaterialDefines, _super);
  39039. function StandardMaterialDefines() {
  39040. var _this = _super.call(this) || this;
  39041. _this.MAINUV1 = false;
  39042. _this.MAINUV2 = false;
  39043. _this.DIFFUSE = false;
  39044. _this.DIFFUSEDIRECTUV = 0;
  39045. _this.AMBIENT = false;
  39046. _this.AMBIENTDIRECTUV = 0;
  39047. _this.OPACITY = false;
  39048. _this.OPACITYDIRECTUV = 0;
  39049. _this.OPACITYRGB = false;
  39050. _this.REFLECTION = false;
  39051. _this.EMISSIVE = false;
  39052. _this.EMISSIVEDIRECTUV = 0;
  39053. _this.SPECULAR = false;
  39054. _this.SPECULARDIRECTUV = 0;
  39055. _this.BUMP = false;
  39056. _this.BUMPDIRECTUV = 0;
  39057. _this.PARALLAX = false;
  39058. _this.PARALLAXOCCLUSION = false;
  39059. _this.SPECULAROVERALPHA = false;
  39060. _this.CLIPPLANE = false;
  39061. _this.ALPHATEST = false;
  39062. _this.DEPTHPREPASS = false;
  39063. _this.ALPHAFROMDIFFUSE = false;
  39064. _this.POINTSIZE = false;
  39065. _this.FOG = false;
  39066. _this.SPECULARTERM = false;
  39067. _this.DIFFUSEFRESNEL = false;
  39068. _this.OPACITYFRESNEL = false;
  39069. _this.REFLECTIONFRESNEL = false;
  39070. _this.REFRACTIONFRESNEL = false;
  39071. _this.EMISSIVEFRESNEL = false;
  39072. _this.FRESNEL = false;
  39073. _this.NORMAL = false;
  39074. _this.UV1 = false;
  39075. _this.UV2 = false;
  39076. _this.VERTEXCOLOR = false;
  39077. _this.VERTEXALPHA = false;
  39078. _this.NUM_BONE_INFLUENCERS = 0;
  39079. _this.BonesPerMesh = 0;
  39080. _this.INSTANCES = false;
  39081. _this.GLOSSINESS = false;
  39082. _this.ROUGHNESS = false;
  39083. _this.EMISSIVEASILLUMINATION = false;
  39084. _this.LINKEMISSIVEWITHDIFFUSE = false;
  39085. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  39086. _this.LIGHTMAP = false;
  39087. _this.LIGHTMAPDIRECTUV = 0;
  39088. _this.OBJECTSPACE_NORMALMAP = false;
  39089. _this.USELIGHTMAPASSHADOWMAP = false;
  39090. _this.REFLECTIONMAP_3D = false;
  39091. _this.REFLECTIONMAP_SPHERICAL = false;
  39092. _this.REFLECTIONMAP_PLANAR = false;
  39093. _this.REFLECTIONMAP_CUBIC = false;
  39094. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  39095. _this.REFLECTIONMAP_PROJECTION = false;
  39096. _this.REFLECTIONMAP_SKYBOX = false;
  39097. _this.REFLECTIONMAP_EXPLICIT = false;
  39098. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  39099. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  39100. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  39101. _this.INVERTCUBICMAP = false;
  39102. _this.LOGARITHMICDEPTH = false;
  39103. _this.REFRACTION = false;
  39104. _this.REFRACTIONMAP_3D = false;
  39105. _this.REFLECTIONOVERALPHA = false;
  39106. _this.TWOSIDEDLIGHTING = false;
  39107. _this.SHADOWFLOAT = false;
  39108. _this.MORPHTARGETS = false;
  39109. _this.MORPHTARGETS_NORMAL = false;
  39110. _this.MORPHTARGETS_TANGENT = false;
  39111. _this.NUM_MORPH_INFLUENCERS = 0;
  39112. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  39113. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  39114. _this.IMAGEPROCESSING = false;
  39115. _this.VIGNETTE = false;
  39116. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  39117. _this.VIGNETTEBLENDMODEOPAQUE = false;
  39118. _this.TONEMAPPING = false;
  39119. _this.CONTRAST = false;
  39120. _this.COLORCURVES = false;
  39121. _this.COLORGRADING = false;
  39122. _this.COLORGRADING3D = false;
  39123. _this.SAMPLER3DGREENDEPTH = false;
  39124. _this.SAMPLER3DBGRMAP = false;
  39125. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  39126. _this.EXPOSURE = false;
  39127. _this.GRAIN = false;
  39128. _this.rebuild();
  39129. return _this;
  39130. }
  39131. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  39132. var modes = [
  39133. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  39134. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  39135. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  39136. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  39137. ];
  39138. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  39139. var mode = modes_1[_i];
  39140. this[mode] = (mode === modeToEnable);
  39141. }
  39142. };
  39143. return StandardMaterialDefines;
  39144. }(BABYLON.MaterialDefines));
  39145. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  39146. var StandardMaterial = /** @class */ (function (_super) {
  39147. __extends(StandardMaterial, _super);
  39148. function StandardMaterial(name, scene) {
  39149. var _this = _super.call(this, name, scene) || this;
  39150. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  39151. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  39152. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  39153. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  39154. _this.specularPower = 64;
  39155. _this._useAlphaFromDiffuseTexture = false;
  39156. _this._useEmissiveAsIllumination = false;
  39157. _this._linkEmissiveWithDiffuse = false;
  39158. _this._useSpecularOverAlpha = false;
  39159. _this._useReflectionOverAlpha = false;
  39160. _this._disableLighting = false;
  39161. _this._useObjectSpaceNormalMap = false;
  39162. _this._useParallax = false;
  39163. _this._useParallaxOcclusion = false;
  39164. _this.parallaxScaleBias = 0.05;
  39165. _this._roughness = 0;
  39166. _this.indexOfRefraction = 0.98;
  39167. _this.invertRefractionY = true;
  39168. _this._useLightmapAsShadowmap = false;
  39169. _this._useReflectionFresnelFromSpecular = false;
  39170. _this._useGlossinessFromSpecularMapAlpha = false;
  39171. _this._maxSimultaneousLights = 4;
  39172. /**
  39173. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  39174. */
  39175. _this._invertNormalMapX = false;
  39176. /**
  39177. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  39178. */
  39179. _this._invertNormalMapY = false;
  39180. /**
  39181. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  39182. */
  39183. _this._twoSidedLighting = false;
  39184. _this._renderTargets = new BABYLON.SmartArray(16);
  39185. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  39186. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  39187. // Setup the default processing configuration to the scene.
  39188. _this._attachImageProcessingConfiguration(null);
  39189. _this.getRenderTargetTextures = function () {
  39190. _this._renderTargets.reset();
  39191. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  39192. _this._renderTargets.push(_this._reflectionTexture);
  39193. }
  39194. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  39195. _this._renderTargets.push(_this._refractionTexture);
  39196. }
  39197. return _this._renderTargets;
  39198. };
  39199. return _this;
  39200. }
  39201. ;
  39202. ;
  39203. ;
  39204. ;
  39205. ;
  39206. ;
  39207. ;
  39208. ;
  39209. ;
  39210. ;
  39211. ;
  39212. ;
  39213. ;
  39214. ;
  39215. ;
  39216. ;
  39217. ;
  39218. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  39219. /**
  39220. * Gets the image processing configuration used either in this material.
  39221. */
  39222. get: function () {
  39223. return this._imageProcessingConfiguration;
  39224. },
  39225. /**
  39226. * Sets the Default image processing configuration used either in the this material.
  39227. *
  39228. * If sets to null, the scene one is in use.
  39229. */
  39230. set: function (value) {
  39231. this._attachImageProcessingConfiguration(value);
  39232. // Ensure the effect will be rebuilt.
  39233. this._markAllSubMeshesAsTexturesDirty();
  39234. },
  39235. enumerable: true,
  39236. configurable: true
  39237. });
  39238. /**
  39239. * Attaches a new image processing configuration to the Standard Material.
  39240. * @param configuration
  39241. */
  39242. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  39243. var _this = this;
  39244. if (configuration === this._imageProcessingConfiguration) {
  39245. return;
  39246. }
  39247. // Detaches observer.
  39248. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  39249. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  39250. }
  39251. // Pick the scene configuration if needed.
  39252. if (!configuration) {
  39253. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  39254. }
  39255. else {
  39256. this._imageProcessingConfiguration = configuration;
  39257. }
  39258. // Attaches observer.
  39259. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  39260. _this._markAllSubMeshesAsImageProcessingDirty();
  39261. });
  39262. };
  39263. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  39264. /**
  39265. * Gets wether the color curves effect is enabled.
  39266. */
  39267. get: function () {
  39268. return this.imageProcessingConfiguration.colorCurvesEnabled;
  39269. },
  39270. /**
  39271. * Sets wether the color curves effect is enabled.
  39272. */
  39273. set: function (value) {
  39274. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  39275. },
  39276. enumerable: true,
  39277. configurable: true
  39278. });
  39279. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  39280. /**
  39281. * Gets wether the color grading effect is enabled.
  39282. */
  39283. get: function () {
  39284. return this.imageProcessingConfiguration.colorGradingEnabled;
  39285. },
  39286. /**
  39287. * Gets wether the color grading effect is enabled.
  39288. */
  39289. set: function (value) {
  39290. this.imageProcessingConfiguration.colorGradingEnabled = value;
  39291. },
  39292. enumerable: true,
  39293. configurable: true
  39294. });
  39295. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  39296. /**
  39297. * Gets wether tonemapping is enabled or not.
  39298. */
  39299. get: function () {
  39300. return this._imageProcessingConfiguration.toneMappingEnabled;
  39301. },
  39302. /**
  39303. * Sets wether tonemapping is enabled or not
  39304. */
  39305. set: function (value) {
  39306. this._imageProcessingConfiguration.toneMappingEnabled = value;
  39307. },
  39308. enumerable: true,
  39309. configurable: true
  39310. });
  39311. ;
  39312. ;
  39313. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  39314. /**
  39315. * The camera exposure used on this material.
  39316. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  39317. * This corresponds to a photographic exposure.
  39318. */
  39319. get: function () {
  39320. return this._imageProcessingConfiguration.exposure;
  39321. },
  39322. /**
  39323. * The camera exposure used on this material.
  39324. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  39325. * This corresponds to a photographic exposure.
  39326. */
  39327. set: function (value) {
  39328. this._imageProcessingConfiguration.exposure = value;
  39329. },
  39330. enumerable: true,
  39331. configurable: true
  39332. });
  39333. ;
  39334. ;
  39335. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  39336. /**
  39337. * Gets The camera contrast used on this material.
  39338. */
  39339. get: function () {
  39340. return this._imageProcessingConfiguration.contrast;
  39341. },
  39342. /**
  39343. * Sets The camera contrast used on this material.
  39344. */
  39345. set: function (value) {
  39346. this._imageProcessingConfiguration.contrast = value;
  39347. },
  39348. enumerable: true,
  39349. configurable: true
  39350. });
  39351. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  39352. /**
  39353. * Gets the Color Grading 2D Lookup Texture.
  39354. */
  39355. get: function () {
  39356. return this._imageProcessingConfiguration.colorGradingTexture;
  39357. },
  39358. /**
  39359. * Sets the Color Grading 2D Lookup Texture.
  39360. */
  39361. set: function (value) {
  39362. this._imageProcessingConfiguration.colorGradingTexture = value;
  39363. },
  39364. enumerable: true,
  39365. configurable: true
  39366. });
  39367. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  39368. /**
  39369. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  39370. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  39371. * These are similar to controls found in many professional imaging or colorist software. The global controls are applied to the entire image. For advanced tuning, extra controls are provided to adjust the shadow, midtone and highlight areas of the image;
  39372. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  39373. */
  39374. get: function () {
  39375. return this._imageProcessingConfiguration.colorCurves;
  39376. },
  39377. /**
  39378. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  39379. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  39380. * These are similar to controls found in many professional imaging or colorist software. The global controls are applied to the entire image. For advanced tuning, extra controls are provided to adjust the shadow, midtone and highlight areas of the image;
  39381. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  39382. */
  39383. set: function (value) {
  39384. this._imageProcessingConfiguration.colorCurves = value;
  39385. },
  39386. enumerable: true,
  39387. configurable: true
  39388. });
  39389. StandardMaterial.prototype.getClassName = function () {
  39390. return "StandardMaterial";
  39391. };
  39392. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  39393. get: function () {
  39394. return this._useLogarithmicDepth;
  39395. },
  39396. set: function (value) {
  39397. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  39398. this._markAllSubMeshesAsMiscDirty();
  39399. },
  39400. enumerable: true,
  39401. configurable: true
  39402. });
  39403. StandardMaterial.prototype.needAlphaBlending = function () {
  39404. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  39405. };
  39406. StandardMaterial.prototype.needAlphaTesting = function () {
  39407. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  39408. };
  39409. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  39410. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  39411. };
  39412. StandardMaterial.prototype.getAlphaTestTexture = function () {
  39413. return this._diffuseTexture;
  39414. };
  39415. /**
  39416. * Child classes can use it to update shaders
  39417. */
  39418. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  39419. if (useInstances === void 0) { useInstances = false; }
  39420. if (subMesh.effect && this.isFrozen) {
  39421. if (this._wasPreviouslyReady && subMesh.effect) {
  39422. return true;
  39423. }
  39424. }
  39425. if (!subMesh._materialDefines) {
  39426. subMesh._materialDefines = new StandardMaterialDefines();
  39427. }
  39428. var scene = this.getScene();
  39429. var defines = subMesh._materialDefines;
  39430. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  39431. if (defines._renderId === scene.getRenderId()) {
  39432. return true;
  39433. }
  39434. }
  39435. var engine = scene.getEngine();
  39436. // Lights
  39437. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  39438. // Textures
  39439. if (defines._areTexturesDirty) {
  39440. defines._needUVs = false;
  39441. defines.MAINUV1 = false;
  39442. defines.MAINUV2 = false;
  39443. if (scene.texturesEnabled) {
  39444. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  39445. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  39446. return false;
  39447. }
  39448. else {
  39449. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  39450. }
  39451. }
  39452. else {
  39453. defines.DIFFUSE = false;
  39454. }
  39455. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  39456. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  39457. return false;
  39458. }
  39459. else {
  39460. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  39461. }
  39462. }
  39463. else {
  39464. defines.AMBIENT = false;
  39465. }
  39466. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  39467. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  39468. return false;
  39469. }
  39470. else {
  39471. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  39472. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  39473. }
  39474. }
  39475. else {
  39476. defines.OPACITY = false;
  39477. }
  39478. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  39479. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  39480. return false;
  39481. }
  39482. else {
  39483. defines._needNormals = true;
  39484. defines.REFLECTION = true;
  39485. defines.ROUGHNESS = (this._roughness > 0);
  39486. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  39487. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  39488. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  39489. switch (this._reflectionTexture.coordinatesMode) {
  39490. case BABYLON.Texture.CUBIC_MODE:
  39491. case BABYLON.Texture.INVCUBIC_MODE:
  39492. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  39493. break;
  39494. case BABYLON.Texture.EXPLICIT_MODE:
  39495. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  39496. break;
  39497. case BABYLON.Texture.PLANAR_MODE:
  39498. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  39499. break;
  39500. case BABYLON.Texture.PROJECTION_MODE:
  39501. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  39502. break;
  39503. case BABYLON.Texture.SKYBOX_MODE:
  39504. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  39505. break;
  39506. case BABYLON.Texture.SPHERICAL_MODE:
  39507. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  39508. break;
  39509. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  39510. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  39511. break;
  39512. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  39513. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  39514. break;
  39515. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  39516. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  39517. break;
  39518. }
  39519. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  39520. }
  39521. }
  39522. else {
  39523. defines.REFLECTION = false;
  39524. }
  39525. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  39526. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  39527. return false;
  39528. }
  39529. else {
  39530. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  39531. }
  39532. }
  39533. else {
  39534. defines.EMISSIVE = false;
  39535. }
  39536. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  39537. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  39538. return false;
  39539. }
  39540. else {
  39541. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  39542. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  39543. }
  39544. }
  39545. else {
  39546. defines.LIGHTMAP = false;
  39547. }
  39548. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  39549. if (!this._specularTexture.isReadyOrNotBlocking()) {
  39550. return false;
  39551. }
  39552. else {
  39553. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  39554. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  39555. }
  39556. }
  39557. else {
  39558. defines.SPECULAR = false;
  39559. }
  39560. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  39561. // Bump texure can not be not blocking.
  39562. if (!this._bumpTexture.isReady()) {
  39563. return false;
  39564. }
  39565. else {
  39566. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  39567. defines.PARALLAX = this._useParallax;
  39568. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  39569. }
  39570. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  39571. }
  39572. else {
  39573. defines.BUMP = false;
  39574. }
  39575. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  39576. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  39577. return false;
  39578. }
  39579. else {
  39580. defines._needUVs = true;
  39581. defines.REFRACTION = true;
  39582. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  39583. }
  39584. }
  39585. else {
  39586. defines.REFRACTION = false;
  39587. }
  39588. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  39589. }
  39590. else {
  39591. defines.DIFFUSE = false;
  39592. defines.AMBIENT = false;
  39593. defines.OPACITY = false;
  39594. defines.REFLECTION = false;
  39595. defines.EMISSIVE = false;
  39596. defines.LIGHTMAP = false;
  39597. defines.BUMP = false;
  39598. defines.REFRACTION = false;
  39599. }
  39600. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  39601. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  39602. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  39603. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  39604. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  39605. }
  39606. if (defines._areImageProcessingDirty) {
  39607. if (!this._imageProcessingConfiguration.isReady()) {
  39608. return false;
  39609. }
  39610. this._imageProcessingConfiguration.prepareDefines(defines);
  39611. }
  39612. if (defines._areFresnelDirty) {
  39613. if (StandardMaterial.FresnelEnabled) {
  39614. // Fresnel
  39615. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  39616. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  39617. this._reflectionFresnelParameters) {
  39618. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  39619. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  39620. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  39621. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  39622. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  39623. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  39624. defines._needNormals = true;
  39625. defines.FRESNEL = true;
  39626. }
  39627. }
  39628. else {
  39629. defines.FRESNEL = false;
  39630. }
  39631. }
  39632. // Misc.
  39633. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  39634. // Attribs
  39635. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  39636. // Values that need to be evaluated on every frame
  39637. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  39638. // Get correct effect
  39639. if (defines.isDirty) {
  39640. defines.markAsProcessed();
  39641. scene.resetCachedMaterial();
  39642. // Fallbacks
  39643. var fallbacks = new BABYLON.EffectFallbacks();
  39644. if (defines.REFLECTION) {
  39645. fallbacks.addFallback(0, "REFLECTION");
  39646. }
  39647. if (defines.SPECULAR) {
  39648. fallbacks.addFallback(0, "SPECULAR");
  39649. }
  39650. if (defines.BUMP) {
  39651. fallbacks.addFallback(0, "BUMP");
  39652. }
  39653. if (defines.PARALLAX) {
  39654. fallbacks.addFallback(1, "PARALLAX");
  39655. }
  39656. if (defines.PARALLAXOCCLUSION) {
  39657. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  39658. }
  39659. if (defines.SPECULAROVERALPHA) {
  39660. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  39661. }
  39662. if (defines.FOG) {
  39663. fallbacks.addFallback(1, "FOG");
  39664. }
  39665. if (defines.POINTSIZE) {
  39666. fallbacks.addFallback(0, "POINTSIZE");
  39667. }
  39668. if (defines.LOGARITHMICDEPTH) {
  39669. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  39670. }
  39671. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  39672. if (defines.SPECULARTERM) {
  39673. fallbacks.addFallback(0, "SPECULARTERM");
  39674. }
  39675. if (defines.DIFFUSEFRESNEL) {
  39676. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  39677. }
  39678. if (defines.OPACITYFRESNEL) {
  39679. fallbacks.addFallback(2, "OPACITYFRESNEL");
  39680. }
  39681. if (defines.REFLECTIONFRESNEL) {
  39682. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  39683. }
  39684. if (defines.EMISSIVEFRESNEL) {
  39685. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  39686. }
  39687. if (defines.FRESNEL) {
  39688. fallbacks.addFallback(4, "FRESNEL");
  39689. }
  39690. //Attributes
  39691. var attribs = [BABYLON.VertexBuffer.PositionKind];
  39692. if (defines.NORMAL) {
  39693. attribs.push(BABYLON.VertexBuffer.NormalKind);
  39694. }
  39695. if (defines.UV1) {
  39696. attribs.push(BABYLON.VertexBuffer.UVKind);
  39697. }
  39698. if (defines.UV2) {
  39699. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  39700. }
  39701. if (defines.VERTEXCOLOR) {
  39702. attribs.push(BABYLON.VertexBuffer.ColorKind);
  39703. }
  39704. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  39705. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  39706. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  39707. var shaderName = "default";
  39708. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  39709. "vFogInfos", "vFogColor", "pointSize",
  39710. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  39711. "mBones",
  39712. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  39713. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  39714. "vReflectionPosition", "vReflectionSize",
  39715. "logarithmicDepthConstant", "vTangentSpaceParams"
  39716. ];
  39717. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  39718. var uniformBuffers = ["Material", "Scene"];
  39719. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  39720. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  39721. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  39722. uniformsNames: uniforms,
  39723. uniformBuffersNames: uniformBuffers,
  39724. samplers: samplers,
  39725. defines: defines,
  39726. maxSimultaneousLights: this._maxSimultaneousLights
  39727. });
  39728. if (this.customShaderNameResolve) {
  39729. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  39730. }
  39731. var join = defines.toString();
  39732. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  39733. attributes: attribs,
  39734. uniformsNames: uniforms,
  39735. uniformBuffersNames: uniformBuffers,
  39736. samplers: samplers,
  39737. defines: join,
  39738. fallbacks: fallbacks,
  39739. onCompiled: this.onCompiled,
  39740. onError: this.onError,
  39741. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  39742. }, engine), defines);
  39743. this.buildUniformLayout();
  39744. }
  39745. if (!subMesh.effect || !subMesh.effect.isReady()) {
  39746. return false;
  39747. }
  39748. defines._renderId = scene.getRenderId();
  39749. this._wasPreviouslyReady = true;
  39750. return true;
  39751. };
  39752. StandardMaterial.prototype.buildUniformLayout = function () {
  39753. // Order is important !
  39754. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  39755. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  39756. this._uniformBuffer.addUniform("opacityParts", 4);
  39757. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  39758. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  39759. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  39760. this._uniformBuffer.addUniform("refractionRightColor", 4);
  39761. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  39762. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  39763. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  39764. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  39765. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  39766. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  39767. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  39768. this._uniformBuffer.addUniform("vReflectionSize", 3);
  39769. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  39770. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  39771. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  39772. this._uniformBuffer.addUniform("vBumpInfos", 3);
  39773. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  39774. this._uniformBuffer.addUniform("ambientMatrix", 16);
  39775. this._uniformBuffer.addUniform("opacityMatrix", 16);
  39776. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  39777. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  39778. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  39779. this._uniformBuffer.addUniform("specularMatrix", 16);
  39780. this._uniformBuffer.addUniform("bumpMatrix", 16);
  39781. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  39782. this._uniformBuffer.addUniform("refractionMatrix", 16);
  39783. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  39784. this._uniformBuffer.addUniform("vSpecularColor", 4);
  39785. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  39786. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  39787. this._uniformBuffer.addUniform("pointSize", 1);
  39788. this._uniformBuffer.create();
  39789. };
  39790. StandardMaterial.prototype.unbind = function () {
  39791. if (this._activeEffect) {
  39792. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  39793. this._activeEffect.setTexture("reflection2DSampler", null);
  39794. }
  39795. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  39796. this._activeEffect.setTexture("refraction2DSampler", null);
  39797. }
  39798. }
  39799. _super.prototype.unbind.call(this);
  39800. };
  39801. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  39802. var scene = this.getScene();
  39803. var defines = subMesh._materialDefines;
  39804. if (!defines) {
  39805. return;
  39806. }
  39807. var effect = subMesh.effect;
  39808. if (!effect) {
  39809. return;
  39810. }
  39811. this._activeEffect = effect;
  39812. // Matrices
  39813. this.bindOnlyWorldMatrix(world);
  39814. // Normal Matrix
  39815. if (defines.OBJECTSPACE_NORMALMAP) {
  39816. world.toNormalMatrix(this._normalMatrix);
  39817. this.bindOnlyNormalMatrix(this._normalMatrix);
  39818. }
  39819. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  39820. // Bones
  39821. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  39822. if (mustRebind) {
  39823. this._uniformBuffer.bindToEffect(effect, "Material");
  39824. this.bindViewProjection(effect);
  39825. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  39826. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  39827. // Fresnel
  39828. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  39829. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  39830. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  39831. }
  39832. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  39833. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  39834. }
  39835. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  39836. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  39837. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  39838. }
  39839. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  39840. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  39841. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  39842. }
  39843. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  39844. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  39845. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  39846. }
  39847. }
  39848. // Textures
  39849. if (scene.texturesEnabled) {
  39850. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  39851. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  39852. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  39853. }
  39854. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  39855. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  39856. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  39857. }
  39858. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  39859. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  39860. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  39861. }
  39862. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  39863. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  39864. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  39865. if (this._reflectionTexture.boundingBoxSize) {
  39866. var cubeTexture = this._reflectionTexture;
  39867. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  39868. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  39869. }
  39870. }
  39871. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  39872. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  39873. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  39874. }
  39875. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  39876. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  39877. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  39878. }
  39879. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  39880. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  39881. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  39882. }
  39883. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  39884. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  39885. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  39886. if (scene._mirroredCameraPosition) {
  39887. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  39888. }
  39889. else {
  39890. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  39891. }
  39892. }
  39893. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  39894. var depth = 1.0;
  39895. if (!this._refractionTexture.isCube) {
  39896. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  39897. if (this._refractionTexture.depth) {
  39898. depth = this._refractionTexture.depth;
  39899. }
  39900. }
  39901. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  39902. }
  39903. }
  39904. // Point size
  39905. if (this.pointsCloud) {
  39906. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  39907. }
  39908. if (defines.SPECULARTERM) {
  39909. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  39910. }
  39911. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  39912. // Diffuse
  39913. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  39914. }
  39915. // Textures
  39916. if (scene.texturesEnabled) {
  39917. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  39918. effect.setTexture("diffuseSampler", this._diffuseTexture);
  39919. }
  39920. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  39921. effect.setTexture("ambientSampler", this._ambientTexture);
  39922. }
  39923. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  39924. effect.setTexture("opacitySampler", this._opacityTexture);
  39925. }
  39926. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  39927. if (this._reflectionTexture.isCube) {
  39928. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  39929. }
  39930. else {
  39931. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  39932. }
  39933. }
  39934. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  39935. effect.setTexture("emissiveSampler", this._emissiveTexture);
  39936. }
  39937. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  39938. effect.setTexture("lightmapSampler", this._lightmapTexture);
  39939. }
  39940. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  39941. effect.setTexture("specularSampler", this._specularTexture);
  39942. }
  39943. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  39944. effect.setTexture("bumpSampler", this._bumpTexture);
  39945. }
  39946. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  39947. var depth = 1.0;
  39948. if (this._refractionTexture.isCube) {
  39949. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  39950. }
  39951. else {
  39952. effect.setTexture("refraction2DSampler", this._refractionTexture);
  39953. }
  39954. }
  39955. }
  39956. // Clip plane
  39957. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  39958. // Colors
  39959. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  39960. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  39961. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  39962. }
  39963. if (mustRebind || !this.isFrozen) {
  39964. // Lights
  39965. if (scene.lightsEnabled && !this._disableLighting) {
  39966. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  39967. }
  39968. // View
  39969. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  39970. this.bindView(effect);
  39971. }
  39972. // Fog
  39973. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  39974. // Morph targets
  39975. if (defines.NUM_MORPH_INFLUENCERS) {
  39976. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  39977. }
  39978. // Log. depth
  39979. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  39980. // image processing
  39981. if (!this._imageProcessingConfiguration.applyByPostProcess) {
  39982. this._imageProcessingConfiguration.bind(this._activeEffect);
  39983. }
  39984. }
  39985. this._uniformBuffer.update();
  39986. this._afterBind(mesh, this._activeEffect);
  39987. };
  39988. StandardMaterial.prototype.getAnimatables = function () {
  39989. var results = [];
  39990. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  39991. results.push(this._diffuseTexture);
  39992. }
  39993. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  39994. results.push(this._ambientTexture);
  39995. }
  39996. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  39997. results.push(this._opacityTexture);
  39998. }
  39999. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  40000. results.push(this._reflectionTexture);
  40001. }
  40002. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  40003. results.push(this._emissiveTexture);
  40004. }
  40005. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  40006. results.push(this._specularTexture);
  40007. }
  40008. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  40009. results.push(this._bumpTexture);
  40010. }
  40011. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  40012. results.push(this._lightmapTexture);
  40013. }
  40014. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  40015. results.push(this._refractionTexture);
  40016. }
  40017. return results;
  40018. };
  40019. StandardMaterial.prototype.getActiveTextures = function () {
  40020. var activeTextures = _super.prototype.getActiveTextures.call(this);
  40021. if (this._diffuseTexture) {
  40022. activeTextures.push(this._diffuseTexture);
  40023. }
  40024. if (this._ambientTexture) {
  40025. activeTextures.push(this._ambientTexture);
  40026. }
  40027. if (this._opacityTexture) {
  40028. activeTextures.push(this._opacityTexture);
  40029. }
  40030. if (this._reflectionTexture) {
  40031. activeTextures.push(this._reflectionTexture);
  40032. }
  40033. if (this._emissiveTexture) {
  40034. activeTextures.push(this._emissiveTexture);
  40035. }
  40036. if (this._specularTexture) {
  40037. activeTextures.push(this._specularTexture);
  40038. }
  40039. if (this._bumpTexture) {
  40040. activeTextures.push(this._bumpTexture);
  40041. }
  40042. if (this._lightmapTexture) {
  40043. activeTextures.push(this._lightmapTexture);
  40044. }
  40045. if (this._refractionTexture) {
  40046. activeTextures.push(this._refractionTexture);
  40047. }
  40048. return activeTextures;
  40049. };
  40050. StandardMaterial.prototype.hasTexture = function (texture) {
  40051. if (_super.prototype.hasTexture.call(this, texture)) {
  40052. return true;
  40053. }
  40054. if (this._diffuseTexture === texture) {
  40055. return true;
  40056. }
  40057. if (this._ambientTexture === texture) {
  40058. return true;
  40059. }
  40060. if (this._opacityTexture === texture) {
  40061. return true;
  40062. }
  40063. if (this._reflectionTexture === texture) {
  40064. return true;
  40065. }
  40066. if (this._emissiveTexture === texture) {
  40067. return true;
  40068. }
  40069. if (this._specularTexture === texture) {
  40070. return true;
  40071. }
  40072. if (this._bumpTexture === texture) {
  40073. return true;
  40074. }
  40075. if (this._lightmapTexture === texture) {
  40076. return true;
  40077. }
  40078. if (this._refractionTexture === texture) {
  40079. return true;
  40080. }
  40081. return false;
  40082. };
  40083. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  40084. if (forceDisposeTextures) {
  40085. if (this._diffuseTexture) {
  40086. this._diffuseTexture.dispose();
  40087. }
  40088. if (this._ambientTexture) {
  40089. this._ambientTexture.dispose();
  40090. }
  40091. if (this._opacityTexture) {
  40092. this._opacityTexture.dispose();
  40093. }
  40094. if (this._reflectionTexture) {
  40095. this._reflectionTexture.dispose();
  40096. }
  40097. if (this._emissiveTexture) {
  40098. this._emissiveTexture.dispose();
  40099. }
  40100. if (this._specularTexture) {
  40101. this._specularTexture.dispose();
  40102. }
  40103. if (this._bumpTexture) {
  40104. this._bumpTexture.dispose();
  40105. }
  40106. if (this._lightmapTexture) {
  40107. this._lightmapTexture.dispose();
  40108. }
  40109. if (this._refractionTexture) {
  40110. this._refractionTexture.dispose();
  40111. }
  40112. }
  40113. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  40114. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  40115. }
  40116. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  40117. };
  40118. StandardMaterial.prototype.clone = function (name) {
  40119. var _this = this;
  40120. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  40121. result.name = name;
  40122. result.id = name;
  40123. return result;
  40124. };
  40125. StandardMaterial.prototype.serialize = function () {
  40126. return BABYLON.SerializationHelper.Serialize(this);
  40127. };
  40128. // Statics
  40129. StandardMaterial.Parse = function (source, scene, rootUrl) {
  40130. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  40131. };
  40132. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  40133. get: function () {
  40134. return StandardMaterial._DiffuseTextureEnabled;
  40135. },
  40136. set: function (value) {
  40137. if (StandardMaterial._DiffuseTextureEnabled === value) {
  40138. return;
  40139. }
  40140. StandardMaterial._DiffuseTextureEnabled = value;
  40141. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40142. },
  40143. enumerable: true,
  40144. configurable: true
  40145. });
  40146. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  40147. get: function () {
  40148. return StandardMaterial._AmbientTextureEnabled;
  40149. },
  40150. set: function (value) {
  40151. if (StandardMaterial._AmbientTextureEnabled === value) {
  40152. return;
  40153. }
  40154. StandardMaterial._AmbientTextureEnabled = value;
  40155. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40156. },
  40157. enumerable: true,
  40158. configurable: true
  40159. });
  40160. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  40161. get: function () {
  40162. return StandardMaterial._OpacityTextureEnabled;
  40163. },
  40164. set: function (value) {
  40165. if (StandardMaterial._OpacityTextureEnabled === value) {
  40166. return;
  40167. }
  40168. StandardMaterial._OpacityTextureEnabled = value;
  40169. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40170. },
  40171. enumerable: true,
  40172. configurable: true
  40173. });
  40174. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  40175. get: function () {
  40176. return StandardMaterial._ReflectionTextureEnabled;
  40177. },
  40178. set: function (value) {
  40179. if (StandardMaterial._ReflectionTextureEnabled === value) {
  40180. return;
  40181. }
  40182. StandardMaterial._ReflectionTextureEnabled = value;
  40183. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40184. },
  40185. enumerable: true,
  40186. configurable: true
  40187. });
  40188. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  40189. get: function () {
  40190. return StandardMaterial._EmissiveTextureEnabled;
  40191. },
  40192. set: function (value) {
  40193. if (StandardMaterial._EmissiveTextureEnabled === value) {
  40194. return;
  40195. }
  40196. StandardMaterial._EmissiveTextureEnabled = value;
  40197. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40198. },
  40199. enumerable: true,
  40200. configurable: true
  40201. });
  40202. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  40203. get: function () {
  40204. return StandardMaterial._SpecularTextureEnabled;
  40205. },
  40206. set: function (value) {
  40207. if (StandardMaterial._SpecularTextureEnabled === value) {
  40208. return;
  40209. }
  40210. StandardMaterial._SpecularTextureEnabled = value;
  40211. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40212. },
  40213. enumerable: true,
  40214. configurable: true
  40215. });
  40216. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  40217. get: function () {
  40218. return StandardMaterial._BumpTextureEnabled;
  40219. },
  40220. set: function (value) {
  40221. if (StandardMaterial._BumpTextureEnabled === value) {
  40222. return;
  40223. }
  40224. StandardMaterial._BumpTextureEnabled = value;
  40225. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40226. },
  40227. enumerable: true,
  40228. configurable: true
  40229. });
  40230. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  40231. get: function () {
  40232. return StandardMaterial._LightmapTextureEnabled;
  40233. },
  40234. set: function (value) {
  40235. if (StandardMaterial._LightmapTextureEnabled === value) {
  40236. return;
  40237. }
  40238. StandardMaterial._LightmapTextureEnabled = value;
  40239. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40240. },
  40241. enumerable: true,
  40242. configurable: true
  40243. });
  40244. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  40245. get: function () {
  40246. return StandardMaterial._RefractionTextureEnabled;
  40247. },
  40248. set: function (value) {
  40249. if (StandardMaterial._RefractionTextureEnabled === value) {
  40250. return;
  40251. }
  40252. StandardMaterial._RefractionTextureEnabled = value;
  40253. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40254. },
  40255. enumerable: true,
  40256. configurable: true
  40257. });
  40258. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  40259. get: function () {
  40260. return StandardMaterial._ColorGradingTextureEnabled;
  40261. },
  40262. set: function (value) {
  40263. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  40264. return;
  40265. }
  40266. StandardMaterial._ColorGradingTextureEnabled = value;
  40267. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40268. },
  40269. enumerable: true,
  40270. configurable: true
  40271. });
  40272. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  40273. get: function () {
  40274. return StandardMaterial._FresnelEnabled;
  40275. },
  40276. set: function (value) {
  40277. if (StandardMaterial._FresnelEnabled === value) {
  40278. return;
  40279. }
  40280. StandardMaterial._FresnelEnabled = value;
  40281. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  40282. },
  40283. enumerable: true,
  40284. configurable: true
  40285. });
  40286. // Flags used to enable or disable a type of texture for all Standard Materials
  40287. StandardMaterial._DiffuseTextureEnabled = true;
  40288. StandardMaterial._AmbientTextureEnabled = true;
  40289. StandardMaterial._OpacityTextureEnabled = true;
  40290. StandardMaterial._ReflectionTextureEnabled = true;
  40291. StandardMaterial._EmissiveTextureEnabled = true;
  40292. StandardMaterial._SpecularTextureEnabled = true;
  40293. StandardMaterial._BumpTextureEnabled = true;
  40294. StandardMaterial._LightmapTextureEnabled = true;
  40295. StandardMaterial._RefractionTextureEnabled = true;
  40296. StandardMaterial._ColorGradingTextureEnabled = true;
  40297. StandardMaterial._FresnelEnabled = true;
  40298. __decorate([
  40299. BABYLON.serializeAsTexture("diffuseTexture")
  40300. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  40301. __decorate([
  40302. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  40303. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  40304. __decorate([
  40305. BABYLON.serializeAsTexture("ambientTexture")
  40306. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  40307. __decorate([
  40308. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40309. ], StandardMaterial.prototype, "ambientTexture", void 0);
  40310. __decorate([
  40311. BABYLON.serializeAsTexture("opacityTexture")
  40312. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  40313. __decorate([
  40314. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  40315. ], StandardMaterial.prototype, "opacityTexture", void 0);
  40316. __decorate([
  40317. BABYLON.serializeAsTexture("reflectionTexture")
  40318. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  40319. __decorate([
  40320. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40321. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  40322. __decorate([
  40323. BABYLON.serializeAsTexture("emissiveTexture")
  40324. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  40325. __decorate([
  40326. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40327. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  40328. __decorate([
  40329. BABYLON.serializeAsTexture("specularTexture")
  40330. ], StandardMaterial.prototype, "_specularTexture", void 0);
  40331. __decorate([
  40332. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40333. ], StandardMaterial.prototype, "specularTexture", void 0);
  40334. __decorate([
  40335. BABYLON.serializeAsTexture("bumpTexture")
  40336. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  40337. __decorate([
  40338. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40339. ], StandardMaterial.prototype, "bumpTexture", void 0);
  40340. __decorate([
  40341. BABYLON.serializeAsTexture("lightmapTexture")
  40342. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  40343. __decorate([
  40344. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40345. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  40346. __decorate([
  40347. BABYLON.serializeAsTexture("refractionTexture")
  40348. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  40349. __decorate([
  40350. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40351. ], StandardMaterial.prototype, "refractionTexture", void 0);
  40352. __decorate([
  40353. BABYLON.serializeAsColor3("ambient")
  40354. ], StandardMaterial.prototype, "ambientColor", void 0);
  40355. __decorate([
  40356. BABYLON.serializeAsColor3("diffuse")
  40357. ], StandardMaterial.prototype, "diffuseColor", void 0);
  40358. __decorate([
  40359. BABYLON.serializeAsColor3("specular")
  40360. ], StandardMaterial.prototype, "specularColor", void 0);
  40361. __decorate([
  40362. BABYLON.serializeAsColor3("emissive")
  40363. ], StandardMaterial.prototype, "emissiveColor", void 0);
  40364. __decorate([
  40365. BABYLON.serialize()
  40366. ], StandardMaterial.prototype, "specularPower", void 0);
  40367. __decorate([
  40368. BABYLON.serialize("useAlphaFromDiffuseTexture")
  40369. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  40370. __decorate([
  40371. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40372. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  40373. __decorate([
  40374. BABYLON.serialize("useEmissiveAsIllumination")
  40375. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  40376. __decorate([
  40377. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40378. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  40379. __decorate([
  40380. BABYLON.serialize("linkEmissiveWithDiffuse")
  40381. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  40382. __decorate([
  40383. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40384. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  40385. __decorate([
  40386. BABYLON.serialize("useSpecularOverAlpha")
  40387. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  40388. __decorate([
  40389. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40390. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  40391. __decorate([
  40392. BABYLON.serialize("useReflectionOverAlpha")
  40393. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  40394. __decorate([
  40395. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40396. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  40397. __decorate([
  40398. BABYLON.serialize("disableLighting")
  40399. ], StandardMaterial.prototype, "_disableLighting", void 0);
  40400. __decorate([
  40401. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  40402. ], StandardMaterial.prototype, "disableLighting", void 0);
  40403. __decorate([
  40404. BABYLON.serialize("useObjectSpaceNormalMap")
  40405. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  40406. __decorate([
  40407. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40408. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  40409. __decorate([
  40410. BABYLON.serialize("useParallax")
  40411. ], StandardMaterial.prototype, "_useParallax", void 0);
  40412. __decorate([
  40413. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40414. ], StandardMaterial.prototype, "useParallax", void 0);
  40415. __decorate([
  40416. BABYLON.serialize("useParallaxOcclusion")
  40417. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  40418. __decorate([
  40419. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40420. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  40421. __decorate([
  40422. BABYLON.serialize()
  40423. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  40424. __decorate([
  40425. BABYLON.serialize("roughness")
  40426. ], StandardMaterial.prototype, "_roughness", void 0);
  40427. __decorate([
  40428. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40429. ], StandardMaterial.prototype, "roughness", void 0);
  40430. __decorate([
  40431. BABYLON.serialize()
  40432. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  40433. __decorate([
  40434. BABYLON.serialize()
  40435. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  40436. __decorate([
  40437. BABYLON.serialize("useLightmapAsShadowmap")
  40438. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  40439. __decorate([
  40440. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40441. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  40442. __decorate([
  40443. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  40444. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  40445. __decorate([
  40446. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40447. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  40448. __decorate([
  40449. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  40450. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  40451. __decorate([
  40452. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  40453. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  40454. __decorate([
  40455. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  40456. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  40457. __decorate([
  40458. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40459. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  40460. __decorate([
  40461. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  40462. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  40463. __decorate([
  40464. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40465. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  40466. __decorate([
  40467. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  40468. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  40469. __decorate([
  40470. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40471. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  40472. __decorate([
  40473. BABYLON.serialize("useReflectionFresnelFromSpecular")
  40474. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  40475. __decorate([
  40476. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40477. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  40478. __decorate([
  40479. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  40480. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  40481. __decorate([
  40482. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40483. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  40484. __decorate([
  40485. BABYLON.serialize("maxSimultaneousLights")
  40486. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  40487. __decorate([
  40488. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  40489. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  40490. __decorate([
  40491. BABYLON.serialize("invertNormalMapX")
  40492. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  40493. __decorate([
  40494. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40495. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  40496. __decorate([
  40497. BABYLON.serialize("invertNormalMapY")
  40498. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  40499. __decorate([
  40500. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40501. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  40502. __decorate([
  40503. BABYLON.serialize("twoSidedLighting")
  40504. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  40505. __decorate([
  40506. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40507. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  40508. __decorate([
  40509. BABYLON.serialize()
  40510. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  40511. return StandardMaterial;
  40512. }(BABYLON.PushMaterial));
  40513. BABYLON.StandardMaterial = StandardMaterial;
  40514. })(BABYLON || (BABYLON = {}));
  40515. //# sourceMappingURL=babylon.standardMaterial.js.map
  40516. var BABYLON;
  40517. (function (BABYLON) {
  40518. /**
  40519. * Manages the defines for the PBR Material.
  40520. */
  40521. var PBRMaterialDefines = /** @class */ (function (_super) {
  40522. __extends(PBRMaterialDefines, _super);
  40523. /**
  40524. * Initializes the PBR Material defines.
  40525. */
  40526. function PBRMaterialDefines() {
  40527. var _this = _super.call(this) || this;
  40528. _this.PBR = true;
  40529. _this.MAINUV1 = false;
  40530. _this.MAINUV2 = false;
  40531. _this.UV1 = false;
  40532. _this.UV2 = false;
  40533. _this.ALBEDO = false;
  40534. _this.ALBEDODIRECTUV = 0;
  40535. _this.VERTEXCOLOR = false;
  40536. _this.AMBIENT = false;
  40537. _this.AMBIENTDIRECTUV = 0;
  40538. _this.AMBIENTINGRAYSCALE = false;
  40539. _this.OPACITY = false;
  40540. _this.VERTEXALPHA = false;
  40541. _this.OPACITYDIRECTUV = 0;
  40542. _this.OPACITYRGB = false;
  40543. _this.ALPHATEST = false;
  40544. _this.DEPTHPREPASS = false;
  40545. _this.ALPHABLEND = false;
  40546. _this.ALPHAFROMALBEDO = false;
  40547. _this.ALPHATESTVALUE = 0.5;
  40548. _this.SPECULAROVERALPHA = false;
  40549. _this.RADIANCEOVERALPHA = false;
  40550. _this.ALPHAFRESNEL = false;
  40551. _this.LINEARALPHAFRESNEL = false;
  40552. _this.PREMULTIPLYALPHA = false;
  40553. _this.EMISSIVE = false;
  40554. _this.EMISSIVEDIRECTUV = 0;
  40555. _this.REFLECTIVITY = false;
  40556. _this.REFLECTIVITYDIRECTUV = 0;
  40557. _this.SPECULARTERM = false;
  40558. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  40559. _this.MICROSURFACEAUTOMATIC = false;
  40560. _this.LODBASEDMICROSFURACE = false;
  40561. _this.MICROSURFACEMAP = false;
  40562. _this.MICROSURFACEMAPDIRECTUV = 0;
  40563. _this.METALLICWORKFLOW = false;
  40564. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  40565. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  40566. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  40567. _this.AOSTOREINMETALMAPRED = false;
  40568. _this.ENVIRONMENTBRDF = false;
  40569. _this.NORMAL = false;
  40570. _this.TANGENT = false;
  40571. _this.BUMP = false;
  40572. _this.BUMPDIRECTUV = 0;
  40573. _this.OBJECTSPACE_NORMALMAP = false;
  40574. _this.PARALLAX = false;
  40575. _this.PARALLAXOCCLUSION = false;
  40576. _this.NORMALXYSCALE = true;
  40577. _this.LIGHTMAP = false;
  40578. _this.LIGHTMAPDIRECTUV = 0;
  40579. _this.USELIGHTMAPASSHADOWMAP = false;
  40580. _this.REFLECTION = false;
  40581. _this.REFLECTIONMAP_3D = false;
  40582. _this.REFLECTIONMAP_SPHERICAL = false;
  40583. _this.REFLECTIONMAP_PLANAR = false;
  40584. _this.REFLECTIONMAP_CUBIC = false;
  40585. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  40586. _this.REFLECTIONMAP_PROJECTION = false;
  40587. _this.REFLECTIONMAP_SKYBOX = false;
  40588. _this.REFLECTIONMAP_EXPLICIT = false;
  40589. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  40590. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  40591. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  40592. _this.INVERTCUBICMAP = false;
  40593. _this.USESPHERICALFROMREFLECTIONMAP = false;
  40594. _this.USESPHERICALINVERTEX = false;
  40595. _this.REFLECTIONMAP_OPPOSITEZ = false;
  40596. _this.LODINREFLECTIONALPHA = false;
  40597. _this.GAMMAREFLECTION = false;
  40598. _this.RADIANCEOCCLUSION = false;
  40599. _this.HORIZONOCCLUSION = false;
  40600. _this.REFRACTION = false;
  40601. _this.REFRACTIONMAP_3D = false;
  40602. _this.REFRACTIONMAP_OPPOSITEZ = false;
  40603. _this.LODINREFRACTIONALPHA = false;
  40604. _this.GAMMAREFRACTION = false;
  40605. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  40606. _this.INSTANCES = false;
  40607. _this.NUM_BONE_INFLUENCERS = 0;
  40608. _this.BonesPerMesh = 0;
  40609. _this.NONUNIFORMSCALING = false;
  40610. _this.MORPHTARGETS = false;
  40611. _this.MORPHTARGETS_NORMAL = false;
  40612. _this.MORPHTARGETS_TANGENT = false;
  40613. _this.NUM_MORPH_INFLUENCERS = 0;
  40614. _this.IMAGEPROCESSING = false;
  40615. _this.VIGNETTE = false;
  40616. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  40617. _this.VIGNETTEBLENDMODEOPAQUE = false;
  40618. _this.TONEMAPPING = false;
  40619. _this.CONTRAST = false;
  40620. _this.COLORCURVES = false;
  40621. _this.COLORGRADING = false;
  40622. _this.COLORGRADING3D = false;
  40623. _this.SAMPLER3DGREENDEPTH = false;
  40624. _this.SAMPLER3DBGRMAP = false;
  40625. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  40626. _this.EXPOSURE = false;
  40627. _this.GRAIN = false;
  40628. _this.USEPHYSICALLIGHTFALLOFF = false;
  40629. _this.TWOSIDEDLIGHTING = false;
  40630. _this.SHADOWFLOAT = false;
  40631. _this.CLIPPLANE = false;
  40632. _this.POINTSIZE = false;
  40633. _this.FOG = false;
  40634. _this.LOGARITHMICDEPTH = false;
  40635. _this.FORCENORMALFORWARD = false;
  40636. _this.rebuild();
  40637. return _this;
  40638. }
  40639. /**
  40640. * Resets the PBR Material defines.
  40641. */
  40642. PBRMaterialDefines.prototype.reset = function () {
  40643. _super.prototype.reset.call(this);
  40644. this.ALPHATESTVALUE = 0.5;
  40645. this.PBR = true;
  40646. };
  40647. return PBRMaterialDefines;
  40648. }(BABYLON.MaterialDefines));
  40649. /**
  40650. * The Physically based material base class of BJS.
  40651. *
  40652. * This offers the main features of a standard PBR material.
  40653. * For more information, please refer to the documentation :
  40654. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  40655. */
  40656. var PBRBaseMaterial = /** @class */ (function (_super) {
  40657. __extends(PBRBaseMaterial, _super);
  40658. /**
  40659. * Instantiates a new PBRMaterial instance.
  40660. *
  40661. * @param name The material name
  40662. * @param scene The scene the material will be use in.
  40663. */
  40664. function PBRBaseMaterial(name, scene) {
  40665. var _this = _super.call(this, name, scene) || this;
  40666. /**
  40667. * Intensity of the direct lights e.g. the four lights available in your scene.
  40668. * This impacts both the direct diffuse and specular highlights.
  40669. */
  40670. _this._directIntensity = 1.0;
  40671. /**
  40672. * Intensity of the emissive part of the material.
  40673. * This helps controlling the emissive effect without modifying the emissive color.
  40674. */
  40675. _this._emissiveIntensity = 1.0;
  40676. /**
  40677. * Intensity of the environment e.g. how much the environment will light the object
  40678. * either through harmonics for rough material or through the refelction for shiny ones.
  40679. */
  40680. _this._environmentIntensity = 1.0;
  40681. /**
  40682. * This is a special control allowing the reduction of the specular highlights coming from the
  40683. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  40684. */
  40685. _this._specularIntensity = 1.0;
  40686. /**
  40687. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  40688. */
  40689. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  40690. /**
  40691. * Debug Control allowing disabling the bump map on this material.
  40692. */
  40693. _this._disableBumpMap = false;
  40694. /**
  40695. * AKA Occlusion Texture Intensity in other nomenclature.
  40696. */
  40697. _this._ambientTextureStrength = 1.0;
  40698. /**
  40699. * The color of a material in ambient lighting.
  40700. */
  40701. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  40702. /**
  40703. * AKA Diffuse Color in other nomenclature.
  40704. */
  40705. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  40706. /**
  40707. * AKA Specular Color in other nomenclature.
  40708. */
  40709. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  40710. /**
  40711. * The color applied when light is reflected from a material.
  40712. */
  40713. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  40714. /**
  40715. * The color applied when light is emitted from a material.
  40716. */
  40717. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  40718. /**
  40719. * AKA Glossiness in other nomenclature.
  40720. */
  40721. _this._microSurface = 0.9;
  40722. /**
  40723. * source material index of refraction (IOR)' / 'destination material IOR.
  40724. */
  40725. _this._indexOfRefraction = 0.66;
  40726. /**
  40727. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  40728. */
  40729. _this._invertRefractionY = false;
  40730. /**
  40731. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  40732. * Materials half opaque for instance using refraction could benefit from this control.
  40733. */
  40734. _this._linkRefractionWithTransparency = false;
  40735. /**
  40736. * Specifies that the material will use the light map as a show map.
  40737. */
  40738. _this._useLightmapAsShadowmap = false;
  40739. /**
  40740. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  40741. * makes the reflect vector face the model (under horizon).
  40742. */
  40743. _this._useHorizonOcclusion = true;
  40744. /**
  40745. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  40746. * too much the area relying on ambient texture to define their ambient occlusion.
  40747. */
  40748. _this._useRadianceOcclusion = true;
  40749. /**
  40750. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  40751. */
  40752. _this._useAlphaFromAlbedoTexture = false;
  40753. /**
  40754. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  40755. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  40756. */
  40757. _this._useSpecularOverAlpha = true;
  40758. /**
  40759. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  40760. */
  40761. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  40762. /**
  40763. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  40764. */
  40765. _this._useRoughnessFromMetallicTextureAlpha = true;
  40766. /**
  40767. * Specifies if the metallic texture contains the roughness information in its green channel.
  40768. */
  40769. _this._useRoughnessFromMetallicTextureGreen = false;
  40770. /**
  40771. * Specifies if the metallic texture contains the metallness information in its blue channel.
  40772. */
  40773. _this._useMetallnessFromMetallicTextureBlue = false;
  40774. /**
  40775. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  40776. */
  40777. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  40778. /**
  40779. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  40780. */
  40781. _this._useAmbientInGrayScale = false;
  40782. /**
  40783. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  40784. * The material will try to infer what glossiness each pixel should be.
  40785. */
  40786. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  40787. /**
  40788. * BJS is using an harcoded light falloff based on a manually sets up range.
  40789. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  40790. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  40791. */
  40792. _this._usePhysicalLightFalloff = true;
  40793. /**
  40794. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  40795. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  40796. */
  40797. _this._useRadianceOverAlpha = true;
  40798. /**
  40799. * Allows using an object space normal map (instead of tangent space).
  40800. */
  40801. _this._useObjectSpaceNormalMap = false;
  40802. /**
  40803. * Allows using the bump map in parallax mode.
  40804. */
  40805. _this._useParallax = false;
  40806. /**
  40807. * Allows using the bump map in parallax occlusion mode.
  40808. */
  40809. _this._useParallaxOcclusion = false;
  40810. /**
  40811. * Controls the scale bias of the parallax mode.
  40812. */
  40813. _this._parallaxScaleBias = 0.05;
  40814. /**
  40815. * If sets to true, disables all the lights affecting the material.
  40816. */
  40817. _this._disableLighting = false;
  40818. /**
  40819. * Number of Simultaneous lights allowed on the material.
  40820. */
  40821. _this._maxSimultaneousLights = 4;
  40822. /**
  40823. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  40824. */
  40825. _this._invertNormalMapX = false;
  40826. /**
  40827. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  40828. */
  40829. _this._invertNormalMapY = false;
  40830. /**
  40831. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  40832. */
  40833. _this._twoSidedLighting = false;
  40834. /**
  40835. * Defines the alpha limits in alpha test mode.
  40836. */
  40837. _this._alphaCutOff = 0.4;
  40838. /**
  40839. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  40840. */
  40841. _this._forceAlphaTest = false;
  40842. /**
  40843. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  40844. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  40845. */
  40846. _this._useAlphaFresnel = false;
  40847. /**
  40848. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  40849. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  40850. */
  40851. _this._useLinearAlphaFresnel = false;
  40852. /**
  40853. * The transparency mode of the material.
  40854. */
  40855. _this._transparencyMode = null;
  40856. /**
  40857. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  40858. * from cos thetav and roughness:
  40859. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  40860. */
  40861. _this._environmentBRDFTexture = null;
  40862. /**
  40863. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  40864. */
  40865. _this._forceIrradianceInFragment = false;
  40866. /**
  40867. * Force normal to face away from face.
  40868. */
  40869. _this._forceNormalForward = false;
  40870. /**
  40871. * Stores the available render targets.
  40872. */
  40873. _this._renderTargets = new BABYLON.SmartArray(16);
  40874. /**
  40875. * Sets the global ambient color for the material used in lighting calculations.
  40876. */
  40877. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  40878. // Setup the default processing configuration to the scene.
  40879. _this._attachImageProcessingConfiguration(null);
  40880. _this.getRenderTargetTextures = function () {
  40881. _this._renderTargets.reset();
  40882. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  40883. _this._renderTargets.push(_this._reflectionTexture);
  40884. }
  40885. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  40886. _this._renderTargets.push(_this._refractionTexture);
  40887. }
  40888. return _this._renderTargets;
  40889. };
  40890. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  40891. return _this;
  40892. }
  40893. /**
  40894. * Attaches a new image processing configuration to the PBR Material.
  40895. * @param configuration
  40896. */
  40897. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  40898. var _this = this;
  40899. if (configuration === this._imageProcessingConfiguration) {
  40900. return;
  40901. }
  40902. // Detaches observer.
  40903. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  40904. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  40905. }
  40906. // Pick the scene configuration if needed.
  40907. if (!configuration) {
  40908. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  40909. }
  40910. else {
  40911. this._imageProcessingConfiguration = configuration;
  40912. }
  40913. // Attaches observer.
  40914. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  40915. _this._markAllSubMeshesAsImageProcessingDirty();
  40916. });
  40917. };
  40918. /**
  40919. * Gets the name of the material class.
  40920. */
  40921. PBRBaseMaterial.prototype.getClassName = function () {
  40922. return "PBRBaseMaterial";
  40923. };
  40924. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  40925. /**
  40926. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  40927. */
  40928. get: function () {
  40929. return this._useLogarithmicDepth;
  40930. },
  40931. /**
  40932. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  40933. */
  40934. set: function (value) {
  40935. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  40936. },
  40937. enumerable: true,
  40938. configurable: true
  40939. });
  40940. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  40941. /**
  40942. * Gets the current transparency mode.
  40943. */
  40944. get: function () {
  40945. return this._transparencyMode;
  40946. },
  40947. /**
  40948. * Sets the transparency mode of the material.
  40949. */
  40950. set: function (value) {
  40951. if (this._transparencyMode === value) {
  40952. return;
  40953. }
  40954. this._transparencyMode = value;
  40955. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  40956. this._markAllSubMeshesAsTexturesAndMiscDirty();
  40957. },
  40958. enumerable: true,
  40959. configurable: true
  40960. });
  40961. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  40962. /**
  40963. * Returns true if alpha blending should be disabled.
  40964. */
  40965. get: function () {
  40966. return (this._linkRefractionWithTransparency ||
  40967. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  40968. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  40969. },
  40970. enumerable: true,
  40971. configurable: true
  40972. });
  40973. /**
  40974. * Specifies whether or not this material should be rendered in alpha blend mode.
  40975. */
  40976. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  40977. if (this._disableAlphaBlending) {
  40978. return false;
  40979. }
  40980. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  40981. };
  40982. /**
  40983. * Specifies if the mesh will require alpha blending.
  40984. * @param mesh - BJS mesh.
  40985. */
  40986. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  40987. if (this._disableAlphaBlending) {
  40988. return false;
  40989. }
  40990. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  40991. };
  40992. /**
  40993. * Specifies whether or not this material should be rendered in alpha test mode.
  40994. */
  40995. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  40996. if (this._forceAlphaTest) {
  40997. return true;
  40998. }
  40999. if (this._linkRefractionWithTransparency) {
  41000. return false;
  41001. }
  41002. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  41003. };
  41004. /**
  41005. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  41006. */
  41007. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  41008. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  41009. };
  41010. /**
  41011. * Gets the texture used for the alpha test.
  41012. */
  41013. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  41014. return this._albedoTexture;
  41015. };
  41016. /**
  41017. * Specifies that the submesh is ready to be used.
  41018. * @param mesh - BJS mesh.
  41019. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  41020. * @param useInstances - Specifies that instances should be used.
  41021. * @returns - boolean indicating that the submesh is ready or not.
  41022. */
  41023. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  41024. if (subMesh.effect && this.isFrozen) {
  41025. if (this._wasPreviouslyReady) {
  41026. return true;
  41027. }
  41028. }
  41029. if (!subMesh._materialDefines) {
  41030. subMesh._materialDefines = new PBRMaterialDefines();
  41031. }
  41032. var defines = subMesh._materialDefines;
  41033. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  41034. if (defines._renderId === this.getScene().getRenderId()) {
  41035. return true;
  41036. }
  41037. }
  41038. var scene = this.getScene();
  41039. var engine = scene.getEngine();
  41040. if (defines._areTexturesDirty) {
  41041. if (scene.texturesEnabled) {
  41042. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  41043. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  41044. return false;
  41045. }
  41046. }
  41047. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  41048. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  41049. return false;
  41050. }
  41051. }
  41052. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  41053. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  41054. return false;
  41055. }
  41056. }
  41057. var reflectionTexture = this._getReflectionTexture();
  41058. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41059. if (!reflectionTexture.isReadyOrNotBlocking()) {
  41060. return false;
  41061. }
  41062. }
  41063. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  41064. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  41065. return false;
  41066. }
  41067. }
  41068. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  41069. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  41070. return false;
  41071. }
  41072. }
  41073. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  41074. if (this._metallicTexture) {
  41075. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  41076. return false;
  41077. }
  41078. }
  41079. else if (this._reflectivityTexture) {
  41080. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  41081. return false;
  41082. }
  41083. }
  41084. if (this._microSurfaceTexture) {
  41085. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  41086. return false;
  41087. }
  41088. }
  41089. }
  41090. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  41091. // Bump texture cannot be not blocking.
  41092. if (!this._bumpTexture.isReady()) {
  41093. return false;
  41094. }
  41095. }
  41096. var refractionTexture = this._getRefractionTexture();
  41097. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  41098. if (!refractionTexture.isReadyOrNotBlocking()) {
  41099. return false;
  41100. }
  41101. }
  41102. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41103. // This is blocking.
  41104. if (!this._environmentBRDFTexture.isReady()) {
  41105. return false;
  41106. }
  41107. }
  41108. }
  41109. }
  41110. if (defines._areImageProcessingDirty) {
  41111. if (!this._imageProcessingConfiguration.isReady()) {
  41112. return false;
  41113. }
  41114. }
  41115. if (!engine.getCaps().standardDerivatives) {
  41116. var bufferMesh = null;
  41117. if (mesh.getClassName() === "InstancedMesh") {
  41118. bufferMesh = mesh.sourceMesh;
  41119. }
  41120. else if (mesh.getClassName() === "Mesh") {
  41121. bufferMesh = mesh;
  41122. }
  41123. if (bufferMesh && bufferMesh.geometry && bufferMesh.geometry.isReady() && !bufferMesh.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  41124. bufferMesh.createNormals(true);
  41125. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + bufferMesh.name);
  41126. }
  41127. }
  41128. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  41129. if (effect) {
  41130. scene.resetCachedMaterial();
  41131. subMesh.setEffect(effect, defines);
  41132. this.buildUniformLayout();
  41133. }
  41134. if (!subMesh.effect || !subMesh.effect.isReady()) {
  41135. return false;
  41136. }
  41137. defines._renderId = scene.getRenderId();
  41138. this._wasPreviouslyReady = true;
  41139. return true;
  41140. };
  41141. /**
  41142. * Specifies if the material uses metallic roughness workflow.
  41143. * @returns boolean specifiying if the material uses metallic roughness workflow.
  41144. */
  41145. PBRBaseMaterial.prototype.isMetallicWorkflow = function () {
  41146. if (this._metallic != null || this._roughness != null || this._metallicTexture) {
  41147. return true;
  41148. }
  41149. return false;
  41150. };
  41151. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  41152. if (onCompiled === void 0) { onCompiled = null; }
  41153. if (onError === void 0) { onError = null; }
  41154. if (useInstances === void 0) { useInstances = null; }
  41155. if (useClipPlane === void 0) { useClipPlane = null; }
  41156. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  41157. if (!defines.isDirty) {
  41158. return null;
  41159. }
  41160. defines.markAsProcessed();
  41161. var scene = this.getScene();
  41162. var engine = scene.getEngine();
  41163. // Fallbacks
  41164. var fallbacks = new BABYLON.EffectFallbacks();
  41165. var fallbackRank = 0;
  41166. if (defines.USESPHERICALINVERTEX) {
  41167. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  41168. }
  41169. if (defines.FOG) {
  41170. fallbacks.addFallback(fallbackRank, "FOG");
  41171. }
  41172. if (defines.POINTSIZE) {
  41173. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  41174. }
  41175. if (defines.LOGARITHMICDEPTH) {
  41176. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  41177. }
  41178. if (defines.PARALLAX) {
  41179. fallbacks.addFallback(fallbackRank, "PARALLAX");
  41180. }
  41181. if (defines.PARALLAXOCCLUSION) {
  41182. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  41183. }
  41184. if (defines.ENVIRONMENTBRDF) {
  41185. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  41186. }
  41187. if (defines.TANGENT) {
  41188. fallbacks.addFallback(fallbackRank++, "TANGENT");
  41189. }
  41190. if (defines.BUMP) {
  41191. fallbacks.addFallback(fallbackRank++, "BUMP");
  41192. }
  41193. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  41194. if (defines.SPECULARTERM) {
  41195. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  41196. }
  41197. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  41198. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  41199. }
  41200. if (defines.LIGHTMAP) {
  41201. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  41202. }
  41203. if (defines.NORMAL) {
  41204. fallbacks.addFallback(fallbackRank++, "NORMAL");
  41205. }
  41206. if (defines.AMBIENT) {
  41207. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  41208. }
  41209. if (defines.EMISSIVE) {
  41210. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  41211. }
  41212. if (defines.VERTEXCOLOR) {
  41213. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  41214. }
  41215. if (defines.NUM_BONE_INFLUENCERS > 0) {
  41216. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  41217. }
  41218. if (defines.MORPHTARGETS) {
  41219. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  41220. }
  41221. //Attributes
  41222. var attribs = [BABYLON.VertexBuffer.PositionKind];
  41223. if (defines.NORMAL) {
  41224. attribs.push(BABYLON.VertexBuffer.NormalKind);
  41225. }
  41226. if (defines.TANGENT) {
  41227. attribs.push(BABYLON.VertexBuffer.TangentKind);
  41228. }
  41229. if (defines.UV1) {
  41230. attribs.push(BABYLON.VertexBuffer.UVKind);
  41231. }
  41232. if (defines.UV2) {
  41233. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  41234. }
  41235. if (defines.VERTEXCOLOR) {
  41236. attribs.push(BABYLON.VertexBuffer.ColorKind);
  41237. }
  41238. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  41239. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  41240. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  41241. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  41242. "vFogInfos", "vFogColor", "pointSize",
  41243. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  41244. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  41245. "mBones",
  41246. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  41247. "vLightingIntensity",
  41248. "logarithmicDepthConstant",
  41249. "vSphericalX", "vSphericalY", "vSphericalZ",
  41250. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  41251. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  41252. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  41253. "vTangentSpaceParams"
  41254. ];
  41255. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  41256. "bumpSampler", "lightmapSampler", "opacitySampler",
  41257. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  41258. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  41259. "microSurfaceSampler", "environmentBrdfSampler"];
  41260. var uniformBuffers = ["Material", "Scene"];
  41261. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  41262. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  41263. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  41264. uniformsNames: uniforms,
  41265. uniformBuffersNames: uniformBuffers,
  41266. samplers: samplers,
  41267. defines: defines,
  41268. maxSimultaneousLights: this._maxSimultaneousLights
  41269. });
  41270. var join = defines.toString();
  41271. return engine.createEffect("pbr", {
  41272. attributes: attribs,
  41273. uniformsNames: uniforms,
  41274. uniformBuffersNames: uniformBuffers,
  41275. samplers: samplers,
  41276. defines: join,
  41277. fallbacks: fallbacks,
  41278. onCompiled: onCompiled,
  41279. onError: onError,
  41280. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  41281. }, engine);
  41282. };
  41283. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  41284. if (useInstances === void 0) { useInstances = null; }
  41285. if (useClipPlane === void 0) { useClipPlane = null; }
  41286. var scene = this.getScene();
  41287. var engine = scene.getEngine();
  41288. // Lights
  41289. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  41290. defines._needNormals = true;
  41291. // Textures
  41292. defines.METALLICWORKFLOW = this.isMetallicWorkflow();
  41293. if (defines._areTexturesDirty) {
  41294. defines._needUVs = false;
  41295. if (scene.texturesEnabled) {
  41296. if (scene.getEngine().getCaps().textureLOD) {
  41297. defines.LODBASEDMICROSFURACE = true;
  41298. }
  41299. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  41300. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  41301. }
  41302. else {
  41303. defines.ALBEDO = false;
  41304. }
  41305. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  41306. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  41307. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  41308. }
  41309. else {
  41310. defines.AMBIENT = false;
  41311. }
  41312. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  41313. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  41314. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  41315. }
  41316. else {
  41317. defines.OPACITY = false;
  41318. }
  41319. var reflectionTexture = this._getReflectionTexture();
  41320. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41321. defines.REFLECTION = true;
  41322. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  41323. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  41324. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  41325. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  41326. defines.INVERTCUBICMAP = true;
  41327. }
  41328. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  41329. switch (reflectionTexture.coordinatesMode) {
  41330. case BABYLON.Texture.CUBIC_MODE:
  41331. case BABYLON.Texture.INVCUBIC_MODE:
  41332. defines.REFLECTIONMAP_CUBIC = true;
  41333. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  41334. break;
  41335. case BABYLON.Texture.EXPLICIT_MODE:
  41336. defines.REFLECTIONMAP_EXPLICIT = true;
  41337. break;
  41338. case BABYLON.Texture.PLANAR_MODE:
  41339. defines.REFLECTIONMAP_PLANAR = true;
  41340. break;
  41341. case BABYLON.Texture.PROJECTION_MODE:
  41342. defines.REFLECTIONMAP_PROJECTION = true;
  41343. break;
  41344. case BABYLON.Texture.SKYBOX_MODE:
  41345. defines.REFLECTIONMAP_SKYBOX = true;
  41346. break;
  41347. case BABYLON.Texture.SPHERICAL_MODE:
  41348. defines.REFLECTIONMAP_SPHERICAL = true;
  41349. break;
  41350. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  41351. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  41352. break;
  41353. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  41354. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  41355. break;
  41356. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  41357. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  41358. break;
  41359. }
  41360. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  41361. if (reflectionTexture.sphericalPolynomial) {
  41362. defines.USESPHERICALFROMREFLECTIONMAP = true;
  41363. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  41364. defines.USESPHERICALINVERTEX = false;
  41365. }
  41366. else {
  41367. defines.USESPHERICALINVERTEX = true;
  41368. }
  41369. }
  41370. }
  41371. }
  41372. else {
  41373. defines.REFLECTION = false;
  41374. defines.REFLECTIONMAP_3D = false;
  41375. defines.REFLECTIONMAP_SPHERICAL = false;
  41376. defines.REFLECTIONMAP_PLANAR = false;
  41377. defines.REFLECTIONMAP_CUBIC = false;
  41378. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  41379. defines.REFLECTIONMAP_PROJECTION = false;
  41380. defines.REFLECTIONMAP_SKYBOX = false;
  41381. defines.REFLECTIONMAP_EXPLICIT = false;
  41382. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  41383. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  41384. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  41385. defines.INVERTCUBICMAP = false;
  41386. defines.USESPHERICALFROMREFLECTIONMAP = false;
  41387. defines.USESPHERICALINVERTEX = false;
  41388. defines.REFLECTIONMAP_OPPOSITEZ = false;
  41389. defines.LODINREFLECTIONALPHA = false;
  41390. defines.GAMMAREFLECTION = false;
  41391. }
  41392. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  41393. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  41394. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  41395. }
  41396. else {
  41397. defines.LIGHTMAP = false;
  41398. }
  41399. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  41400. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  41401. }
  41402. else {
  41403. defines.EMISSIVE = false;
  41404. }
  41405. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  41406. if (this._metallicTexture) {
  41407. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  41408. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  41409. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  41410. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  41411. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  41412. }
  41413. else if (this._reflectivityTexture) {
  41414. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  41415. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  41416. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  41417. }
  41418. else {
  41419. defines.REFLECTIVITY = false;
  41420. }
  41421. if (this._microSurfaceTexture) {
  41422. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  41423. }
  41424. else {
  41425. defines.MICROSURFACEMAP = false;
  41426. }
  41427. }
  41428. else {
  41429. defines.REFLECTIVITY = false;
  41430. defines.MICROSURFACEMAP = false;
  41431. }
  41432. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  41433. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  41434. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  41435. defines.PARALLAX = true;
  41436. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  41437. }
  41438. else {
  41439. defines.PARALLAX = false;
  41440. }
  41441. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  41442. }
  41443. else {
  41444. defines.BUMP = false;
  41445. }
  41446. var refractionTexture = this._getRefractionTexture();
  41447. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  41448. defines.REFRACTION = true;
  41449. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  41450. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  41451. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  41452. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  41453. if (this._linkRefractionWithTransparency) {
  41454. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  41455. }
  41456. }
  41457. else {
  41458. defines.REFRACTION = false;
  41459. }
  41460. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41461. defines.ENVIRONMENTBRDF = true;
  41462. }
  41463. else {
  41464. defines.ENVIRONMENTBRDF = false;
  41465. }
  41466. if (this._shouldUseAlphaFromAlbedoTexture()) {
  41467. defines.ALPHAFROMALBEDO = true;
  41468. }
  41469. else {
  41470. defines.ALPHAFROMALBEDO = false;
  41471. }
  41472. }
  41473. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  41474. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  41475. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  41476. if (!this.backFaceCulling && this._twoSidedLighting) {
  41477. defines.TWOSIDEDLIGHTING = true;
  41478. }
  41479. else {
  41480. defines.TWOSIDEDLIGHTING = false;
  41481. }
  41482. defines.ALPHATESTVALUE = this._alphaCutOff;
  41483. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  41484. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  41485. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  41486. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  41487. }
  41488. if (defines._areImageProcessingDirty) {
  41489. this._imageProcessingConfiguration.prepareDefines(defines);
  41490. }
  41491. defines.FORCENORMALFORWARD = this._forceNormalForward;
  41492. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  41493. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  41494. // Misc.
  41495. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  41496. // Values that need to be evaluated on every frame
  41497. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  41498. // Attribs
  41499. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  41500. };
  41501. /**
  41502. * Force shader compilation
  41503. */
  41504. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  41505. var _this = this;
  41506. var localOptions = __assign({ clipPlane: false }, options);
  41507. var defines = new PBRMaterialDefines();
  41508. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  41509. if (effect.isReady()) {
  41510. if (onCompiled) {
  41511. onCompiled(this);
  41512. }
  41513. }
  41514. else {
  41515. effect.onCompileObservable.add(function () {
  41516. if (onCompiled) {
  41517. onCompiled(_this);
  41518. }
  41519. });
  41520. }
  41521. };
  41522. /**
  41523. * Initializes the uniform buffer layout for the shader.
  41524. */
  41525. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  41526. // Order is important !
  41527. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  41528. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  41529. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  41530. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  41531. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  41532. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  41533. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  41534. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  41535. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  41536. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  41537. this._uniformBuffer.addUniform("vReflectionSize", 3);
  41538. this._uniformBuffer.addUniform("vBumpInfos", 3);
  41539. this._uniformBuffer.addUniform("albedoMatrix", 16);
  41540. this._uniformBuffer.addUniform("ambientMatrix", 16);
  41541. this._uniformBuffer.addUniform("opacityMatrix", 16);
  41542. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  41543. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  41544. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  41545. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  41546. this._uniformBuffer.addUniform("bumpMatrix", 16);
  41547. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  41548. this._uniformBuffer.addUniform("refractionMatrix", 16);
  41549. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  41550. this._uniformBuffer.addUniform("vReflectionColor", 3);
  41551. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  41552. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  41553. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  41554. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  41555. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  41556. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  41557. this._uniformBuffer.addUniform("pointSize", 1);
  41558. this._uniformBuffer.create();
  41559. };
  41560. /**
  41561. * Unbinds the textures.
  41562. */
  41563. PBRBaseMaterial.prototype.unbind = function () {
  41564. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  41565. this._uniformBuffer.setTexture("reflectionSampler", null);
  41566. }
  41567. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  41568. this._uniformBuffer.setTexture("refractionSampler", null);
  41569. }
  41570. _super.prototype.unbind.call(this);
  41571. };
  41572. /**
  41573. * Binds the submesh data.
  41574. * @param world - The world matrix.
  41575. * @param mesh - The BJS mesh.
  41576. * @param subMesh - A submesh of the BJS mesh.
  41577. */
  41578. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  41579. var scene = this.getScene();
  41580. var defines = subMesh._materialDefines;
  41581. if (!defines) {
  41582. return;
  41583. }
  41584. var effect = subMesh.effect;
  41585. if (!effect) {
  41586. return;
  41587. }
  41588. this._activeEffect = effect;
  41589. // Matrices
  41590. this.bindOnlyWorldMatrix(world);
  41591. // Normal Matrix
  41592. if (defines.OBJECTSPACE_NORMALMAP) {
  41593. world.toNormalMatrix(this._normalMatrix);
  41594. this.bindOnlyNormalMatrix(this._normalMatrix);
  41595. }
  41596. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  41597. // Bones
  41598. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  41599. var reflectionTexture = null;
  41600. if (mustRebind) {
  41601. this._uniformBuffer.bindToEffect(effect, "Material");
  41602. this.bindViewProjection(effect);
  41603. reflectionTexture = this._getReflectionTexture();
  41604. var refractionTexture = this._getRefractionTexture();
  41605. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  41606. // Texture uniforms
  41607. if (scene.texturesEnabled) {
  41608. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  41609. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  41610. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  41611. }
  41612. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  41613. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  41614. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  41615. }
  41616. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  41617. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  41618. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  41619. }
  41620. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41621. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  41622. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  41623. if (reflectionTexture.boundingBoxSize) {
  41624. var cubeTexture = reflectionTexture;
  41625. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  41626. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  41627. }
  41628. var polynomials = reflectionTexture.sphericalPolynomial;
  41629. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  41630. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  41631. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  41632. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  41633. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  41634. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  41635. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  41636. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  41637. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  41638. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  41639. }
  41640. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  41641. }
  41642. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  41643. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  41644. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  41645. }
  41646. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  41647. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  41648. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  41649. }
  41650. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  41651. if (this._metallicTexture) {
  41652. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  41653. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  41654. }
  41655. else if (this._reflectivityTexture) {
  41656. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  41657. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  41658. }
  41659. if (this._microSurfaceTexture) {
  41660. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  41661. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  41662. }
  41663. }
  41664. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  41665. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  41666. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  41667. if (scene._mirroredCameraPosition) {
  41668. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  41669. }
  41670. else {
  41671. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  41672. }
  41673. }
  41674. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  41675. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  41676. var depth = 1.0;
  41677. if (!refractionTexture.isCube) {
  41678. if (refractionTexture.depth) {
  41679. depth = refractionTexture.depth;
  41680. }
  41681. }
  41682. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  41683. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  41684. }
  41685. }
  41686. // Point size
  41687. if (this.pointsCloud) {
  41688. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  41689. }
  41690. // Colors
  41691. if (defines.METALLICWORKFLOW) {
  41692. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  41693. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  41694. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  41695. }
  41696. else {
  41697. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  41698. }
  41699. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  41700. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  41701. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  41702. // Misc
  41703. this._lightingInfos.x = this._directIntensity;
  41704. this._lightingInfos.y = this._emissiveIntensity;
  41705. this._lightingInfos.z = this._environmentIntensity;
  41706. this._lightingInfos.w = this._specularIntensity;
  41707. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  41708. }
  41709. // Textures
  41710. if (scene.texturesEnabled) {
  41711. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  41712. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  41713. }
  41714. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  41715. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  41716. }
  41717. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  41718. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  41719. }
  41720. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41721. if (defines.LODBASEDMICROSFURACE) {
  41722. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  41723. }
  41724. else {
  41725. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  41726. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  41727. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  41728. }
  41729. }
  41730. if (defines.ENVIRONMENTBRDF) {
  41731. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  41732. }
  41733. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  41734. if (defines.LODBASEDMICROSFURACE) {
  41735. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  41736. }
  41737. else {
  41738. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  41739. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  41740. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  41741. }
  41742. }
  41743. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  41744. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  41745. }
  41746. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  41747. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  41748. }
  41749. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  41750. if (this._metallicTexture) {
  41751. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  41752. }
  41753. else if (this._reflectivityTexture) {
  41754. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  41755. }
  41756. if (this._microSurfaceTexture) {
  41757. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  41758. }
  41759. }
  41760. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  41761. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  41762. }
  41763. }
  41764. // Clip plane
  41765. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  41766. // Colors
  41767. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  41768. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  41769. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  41770. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  41771. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  41772. }
  41773. if (mustRebind || !this.isFrozen) {
  41774. // Lights
  41775. if (scene.lightsEnabled && !this._disableLighting) {
  41776. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  41777. }
  41778. // View
  41779. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  41780. this.bindView(effect);
  41781. }
  41782. // Fog
  41783. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  41784. // Morph targets
  41785. if (defines.NUM_MORPH_INFLUENCERS) {
  41786. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  41787. }
  41788. // image processing
  41789. this._imageProcessingConfiguration.bind(this._activeEffect);
  41790. // Log. depth
  41791. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  41792. }
  41793. this._uniformBuffer.update();
  41794. this._afterBind(mesh);
  41795. };
  41796. /**
  41797. * Returns the animatable textures.
  41798. * @returns - Array of animatable textures.
  41799. */
  41800. PBRBaseMaterial.prototype.getAnimatables = function () {
  41801. var results = [];
  41802. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  41803. results.push(this._albedoTexture);
  41804. }
  41805. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  41806. results.push(this._ambientTexture);
  41807. }
  41808. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  41809. results.push(this._opacityTexture);
  41810. }
  41811. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  41812. results.push(this._reflectionTexture);
  41813. }
  41814. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  41815. results.push(this._emissiveTexture);
  41816. }
  41817. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  41818. results.push(this._metallicTexture);
  41819. }
  41820. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  41821. results.push(this._reflectivityTexture);
  41822. }
  41823. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  41824. results.push(this._bumpTexture);
  41825. }
  41826. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  41827. results.push(this._lightmapTexture);
  41828. }
  41829. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  41830. results.push(this._refractionTexture);
  41831. }
  41832. return results;
  41833. };
  41834. /**
  41835. * Returns the texture used for reflections.
  41836. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  41837. */
  41838. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  41839. if (this._reflectionTexture) {
  41840. return this._reflectionTexture;
  41841. }
  41842. return this.getScene().environmentTexture;
  41843. };
  41844. /**
  41845. * Returns the texture used for refraction or null if none is used.
  41846. * @returns - Refection texture if present. If no refraction texture and refraction
  41847. * is linked with transparency, returns environment texture. Otherwise, returns null.
  41848. */
  41849. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  41850. if (this._refractionTexture) {
  41851. return this._refractionTexture;
  41852. }
  41853. if (this._linkRefractionWithTransparency) {
  41854. return this.getScene().environmentTexture;
  41855. }
  41856. return null;
  41857. };
  41858. /**
  41859. * Disposes the resources of the material.
  41860. * @param forceDisposeEffect - Forces the disposal of effects.
  41861. * @param forceDisposeTextures - Forces the disposal of all textures.
  41862. */
  41863. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  41864. if (forceDisposeTextures) {
  41865. if (this._albedoTexture) {
  41866. this._albedoTexture.dispose();
  41867. }
  41868. if (this._ambientTexture) {
  41869. this._ambientTexture.dispose();
  41870. }
  41871. if (this._opacityTexture) {
  41872. this._opacityTexture.dispose();
  41873. }
  41874. if (this._reflectionTexture) {
  41875. this._reflectionTexture.dispose();
  41876. }
  41877. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  41878. this._environmentBRDFTexture.dispose();
  41879. }
  41880. if (this._emissiveTexture) {
  41881. this._emissiveTexture.dispose();
  41882. }
  41883. if (this._metallicTexture) {
  41884. this._metallicTexture.dispose();
  41885. }
  41886. if (this._reflectivityTexture) {
  41887. this._reflectivityTexture.dispose();
  41888. }
  41889. if (this._bumpTexture) {
  41890. this._bumpTexture.dispose();
  41891. }
  41892. if (this._lightmapTexture) {
  41893. this._lightmapTexture.dispose();
  41894. }
  41895. if (this._refractionTexture) {
  41896. this._refractionTexture.dispose();
  41897. }
  41898. }
  41899. this._renderTargets.dispose();
  41900. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  41901. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  41902. }
  41903. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  41904. };
  41905. /**
  41906. * Stores the reflectivity values based on metallic roughness workflow.
  41907. */
  41908. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  41909. __decorate([
  41910. BABYLON.serializeAsImageProcessingConfiguration()
  41911. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  41912. __decorate([
  41913. BABYLON.serialize()
  41914. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  41915. __decorate([
  41916. BABYLON.serialize()
  41917. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  41918. return PBRBaseMaterial;
  41919. }(BABYLON.PushMaterial));
  41920. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  41921. })(BABYLON || (BABYLON = {}));
  41922. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  41923. var BABYLON;
  41924. (function (BABYLON) {
  41925. /**
  41926. * The Physically based simple base material of BJS.
  41927. *
  41928. * This enables better naming and convention enforcements on top of the pbrMaterial.
  41929. * It is used as the base class for both the specGloss and metalRough conventions.
  41930. */
  41931. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  41932. __extends(PBRBaseSimpleMaterial, _super);
  41933. /**
  41934. * Instantiates a new PBRMaterial instance.
  41935. *
  41936. * @param name The material name
  41937. * @param scene The scene the material will be use in.
  41938. */
  41939. function PBRBaseSimpleMaterial(name, scene) {
  41940. var _this = _super.call(this, name, scene) || this;
  41941. /**
  41942. * Number of Simultaneous lights allowed on the material.
  41943. */
  41944. _this.maxSimultaneousLights = 4;
  41945. /**
  41946. * If sets to true, disables all the lights affecting the material.
  41947. */
  41948. _this.disableLighting = false;
  41949. /**
  41950. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  41951. */
  41952. _this.invertNormalMapX = false;
  41953. /**
  41954. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  41955. */
  41956. _this.invertNormalMapY = false;
  41957. /**
  41958. * Emissivie color used to self-illuminate the model.
  41959. */
  41960. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  41961. /**
  41962. * Occlusion Channel Strenght.
  41963. */
  41964. _this.occlusionStrength = 1.0;
  41965. _this.useLightmapAsShadowmap = false;
  41966. _this._useAlphaFromAlbedoTexture = true;
  41967. _this._useAmbientInGrayScale = true;
  41968. return _this;
  41969. }
  41970. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  41971. /**
  41972. * Gets the current double sided mode.
  41973. */
  41974. get: function () {
  41975. return this._twoSidedLighting;
  41976. },
  41977. /**
  41978. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  41979. */
  41980. set: function (value) {
  41981. if (this._twoSidedLighting === value) {
  41982. return;
  41983. }
  41984. this._twoSidedLighting = value;
  41985. this.backFaceCulling = !value;
  41986. this._markAllSubMeshesAsTexturesDirty();
  41987. },
  41988. enumerable: true,
  41989. configurable: true
  41990. });
  41991. /**
  41992. * Return the active textures of the material.
  41993. */
  41994. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  41995. var activeTextures = _super.prototype.getActiveTextures.call(this);
  41996. if (this.environmentTexture) {
  41997. activeTextures.push(this.environmentTexture);
  41998. }
  41999. if (this.normalTexture) {
  42000. activeTextures.push(this.normalTexture);
  42001. }
  42002. if (this.emissiveTexture) {
  42003. activeTextures.push(this.emissiveTexture);
  42004. }
  42005. if (this.occlusionTexture) {
  42006. activeTextures.push(this.occlusionTexture);
  42007. }
  42008. if (this.lightmapTexture) {
  42009. activeTextures.push(this.lightmapTexture);
  42010. }
  42011. return activeTextures;
  42012. };
  42013. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  42014. if (_super.prototype.hasTexture.call(this, texture)) {
  42015. return true;
  42016. }
  42017. if (this.lightmapTexture === texture) {
  42018. return true;
  42019. }
  42020. return false;
  42021. };
  42022. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  42023. return "PBRBaseSimpleMaterial";
  42024. };
  42025. __decorate([
  42026. BABYLON.serialize(),
  42027. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  42028. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  42029. __decorate([
  42030. BABYLON.serialize(),
  42031. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  42032. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  42033. __decorate([
  42034. BABYLON.serializeAsTexture(),
  42035. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  42036. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  42037. __decorate([
  42038. BABYLON.serialize(),
  42039. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42040. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  42041. __decorate([
  42042. BABYLON.serialize(),
  42043. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42044. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  42045. __decorate([
  42046. BABYLON.serializeAsTexture(),
  42047. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  42048. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  42049. __decorate([
  42050. BABYLON.serializeAsColor3("emissive"),
  42051. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42052. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  42053. __decorate([
  42054. BABYLON.serializeAsTexture(),
  42055. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42056. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  42057. __decorate([
  42058. BABYLON.serialize(),
  42059. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  42060. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  42061. __decorate([
  42062. BABYLON.serializeAsTexture(),
  42063. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  42064. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  42065. __decorate([
  42066. BABYLON.serialize(),
  42067. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  42068. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  42069. __decorate([
  42070. BABYLON.serialize()
  42071. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  42072. __decorate([
  42073. BABYLON.serializeAsTexture(),
  42074. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  42075. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  42076. __decorate([
  42077. BABYLON.serialize(),
  42078. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42079. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  42080. return PBRBaseSimpleMaterial;
  42081. }(BABYLON.PBRBaseMaterial));
  42082. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  42083. })(BABYLON || (BABYLON = {}));
  42084. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  42085. var BABYLON;
  42086. (function (BABYLON) {
  42087. /**
  42088. * The Physically based material of BJS.
  42089. *
  42090. * This offers the main features of a standard PBR material.
  42091. * For more information, please refer to the documentation :
  42092. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  42093. */
  42094. var PBRMaterial = /** @class */ (function (_super) {
  42095. __extends(PBRMaterial, _super);
  42096. /**
  42097. * Instantiates a new PBRMaterial instance.
  42098. *
  42099. * @param name The material name
  42100. * @param scene The scene the material will be use in.
  42101. */
  42102. function PBRMaterial(name, scene) {
  42103. var _this = _super.call(this, name, scene) || this;
  42104. /**
  42105. * Intensity of the direct lights e.g. the four lights available in your scene.
  42106. * This impacts both the direct diffuse and specular highlights.
  42107. */
  42108. _this.directIntensity = 1.0;
  42109. /**
  42110. * Intensity of the emissive part of the material.
  42111. * This helps controlling the emissive effect without modifying the emissive color.
  42112. */
  42113. _this.emissiveIntensity = 1.0;
  42114. /**
  42115. * Intensity of the environment e.g. how much the environment will light the object
  42116. * either through harmonics for rough material or through the refelction for shiny ones.
  42117. */
  42118. _this.environmentIntensity = 1.0;
  42119. /**
  42120. * This is a special control allowing the reduction of the specular highlights coming from the
  42121. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  42122. */
  42123. _this.specularIntensity = 1.0;
  42124. /**
  42125. * Debug Control allowing disabling the bump map on this material.
  42126. */
  42127. _this.disableBumpMap = false;
  42128. /**
  42129. * AKA Occlusion Texture Intensity in other nomenclature.
  42130. */
  42131. _this.ambientTextureStrength = 1.0;
  42132. /**
  42133. * The color of a material in ambient lighting.
  42134. */
  42135. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  42136. /**
  42137. * AKA Diffuse Color in other nomenclature.
  42138. */
  42139. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  42140. /**
  42141. * AKA Specular Color in other nomenclature.
  42142. */
  42143. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  42144. /**
  42145. * The color reflected from the material.
  42146. */
  42147. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  42148. /**
  42149. * The color emitted from the material.
  42150. */
  42151. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  42152. /**
  42153. * AKA Glossiness in other nomenclature.
  42154. */
  42155. _this.microSurface = 1.0;
  42156. /**
  42157. * source material index of refraction (IOR)' / 'destination material IOR.
  42158. */
  42159. _this.indexOfRefraction = 0.66;
  42160. /**
  42161. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  42162. */
  42163. _this.invertRefractionY = false;
  42164. /**
  42165. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  42166. * Materials half opaque for instance using refraction could benefit from this control.
  42167. */
  42168. _this.linkRefractionWithTransparency = false;
  42169. _this.useLightmapAsShadowmap = false;
  42170. /**
  42171. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  42172. */
  42173. _this.useAlphaFromAlbedoTexture = false;
  42174. /**
  42175. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  42176. */
  42177. _this.forceAlphaTest = false;
  42178. /**
  42179. * Defines the alpha limits in alpha test mode.
  42180. */
  42181. _this.alphaCutOff = 0.4;
  42182. /**
  42183. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  42184. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  42185. */
  42186. _this.useSpecularOverAlpha = true;
  42187. /**
  42188. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  42189. */
  42190. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  42191. /**
  42192. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  42193. */
  42194. _this.useRoughnessFromMetallicTextureAlpha = true;
  42195. /**
  42196. * Specifies if the metallic texture contains the roughness information in its green channel.
  42197. */
  42198. _this.useRoughnessFromMetallicTextureGreen = false;
  42199. /**
  42200. * Specifies if the metallic texture contains the metallness information in its blue channel.
  42201. */
  42202. _this.useMetallnessFromMetallicTextureBlue = false;
  42203. /**
  42204. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  42205. */
  42206. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  42207. /**
  42208. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  42209. */
  42210. _this.useAmbientInGrayScale = false;
  42211. /**
  42212. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  42213. * The material will try to infer what glossiness each pixel should be.
  42214. */
  42215. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  42216. /**
  42217. * BJS is using an harcoded light falloff based on a manually sets up range.
  42218. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  42219. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  42220. */
  42221. _this.usePhysicalLightFalloff = true;
  42222. /**
  42223. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  42224. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  42225. */
  42226. _this.useRadianceOverAlpha = true;
  42227. /**
  42228. * Allows using an object space normal map (instead of tangent space).
  42229. */
  42230. _this.useObjectSpaceNormalMap = false;
  42231. /**
  42232. * Allows using the bump map in parallax mode.
  42233. */
  42234. _this.useParallax = false;
  42235. /**
  42236. * Allows using the bump map in parallax occlusion mode.
  42237. */
  42238. _this.useParallaxOcclusion = false;
  42239. /**
  42240. * Controls the scale bias of the parallax mode.
  42241. */
  42242. _this.parallaxScaleBias = 0.05;
  42243. /**
  42244. * If sets to true, disables all the lights affecting the material.
  42245. */
  42246. _this.disableLighting = false;
  42247. /**
  42248. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  42249. */
  42250. _this.forceIrradianceInFragment = false;
  42251. /**
  42252. * Number of Simultaneous lights allowed on the material.
  42253. */
  42254. _this.maxSimultaneousLights = 4;
  42255. /**
  42256. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  42257. */
  42258. _this.invertNormalMapX = false;
  42259. /**
  42260. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  42261. */
  42262. _this.invertNormalMapY = false;
  42263. /**
  42264. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  42265. */
  42266. _this.twoSidedLighting = false;
  42267. /**
  42268. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  42269. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  42270. */
  42271. _this.useAlphaFresnel = false;
  42272. /**
  42273. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  42274. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  42275. */
  42276. _this.useLinearAlphaFresnel = false;
  42277. /**
  42278. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  42279. * And/Or occlude the blended part.
  42280. */
  42281. _this.environmentBRDFTexture = null;
  42282. /**
  42283. * Force normal to face away from face.
  42284. */
  42285. _this.forceNormalForward = false;
  42286. /**
  42287. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  42288. * makes the reflect vector face the model (under horizon).
  42289. */
  42290. _this.useHorizonOcclusion = true;
  42291. /**
  42292. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  42293. * too much the area relying on ambient texture to define their ambient occlusion.
  42294. */
  42295. _this.useRadianceOcclusion = true;
  42296. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  42297. return _this;
  42298. }
  42299. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  42300. /**
  42301. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  42302. */
  42303. get: function () {
  42304. return this._PBRMATERIAL_OPAQUE;
  42305. },
  42306. enumerable: true,
  42307. configurable: true
  42308. });
  42309. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  42310. /**
  42311. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  42312. */
  42313. get: function () {
  42314. return this._PBRMATERIAL_ALPHATEST;
  42315. },
  42316. enumerable: true,
  42317. configurable: true
  42318. });
  42319. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  42320. /**
  42321. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  42322. */
  42323. get: function () {
  42324. return this._PBRMATERIAL_ALPHABLEND;
  42325. },
  42326. enumerable: true,
  42327. configurable: true
  42328. });
  42329. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  42330. /**
  42331. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  42332. * They are also discarded below the alpha cutoff threshold to improve performances.
  42333. */
  42334. get: function () {
  42335. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  42336. },
  42337. enumerable: true,
  42338. configurable: true
  42339. });
  42340. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  42341. /**
  42342. * Gets the image processing configuration used either in this material.
  42343. */
  42344. get: function () {
  42345. return this._imageProcessingConfiguration;
  42346. },
  42347. /**
  42348. * Sets the Default image processing configuration used either in the this material.
  42349. *
  42350. * If sets to null, the scene one is in use.
  42351. */
  42352. set: function (value) {
  42353. this._attachImageProcessingConfiguration(value);
  42354. // Ensure the effect will be rebuilt.
  42355. this._markAllSubMeshesAsTexturesDirty();
  42356. },
  42357. enumerable: true,
  42358. configurable: true
  42359. });
  42360. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  42361. /**
  42362. * Gets wether the color curves effect is enabled.
  42363. */
  42364. get: function () {
  42365. return this.imageProcessingConfiguration.colorCurvesEnabled;
  42366. },
  42367. /**
  42368. * Sets wether the color curves effect is enabled.
  42369. */
  42370. set: function (value) {
  42371. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  42372. },
  42373. enumerable: true,
  42374. configurable: true
  42375. });
  42376. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  42377. /**
  42378. * Gets wether the color grading effect is enabled.
  42379. */
  42380. get: function () {
  42381. return this.imageProcessingConfiguration.colorGradingEnabled;
  42382. },
  42383. /**
  42384. * Gets wether the color grading effect is enabled.
  42385. */
  42386. set: function (value) {
  42387. this.imageProcessingConfiguration.colorGradingEnabled = value;
  42388. },
  42389. enumerable: true,
  42390. configurable: true
  42391. });
  42392. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  42393. /**
  42394. * Gets wether tonemapping is enabled or not.
  42395. */
  42396. get: function () {
  42397. return this._imageProcessingConfiguration.toneMappingEnabled;
  42398. },
  42399. /**
  42400. * Sets wether tonemapping is enabled or not
  42401. */
  42402. set: function (value) {
  42403. this._imageProcessingConfiguration.toneMappingEnabled = value;
  42404. },
  42405. enumerable: true,
  42406. configurable: true
  42407. });
  42408. ;
  42409. ;
  42410. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  42411. /**
  42412. * The camera exposure used on this material.
  42413. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42414. * This corresponds to a photographic exposure.
  42415. */
  42416. get: function () {
  42417. return this._imageProcessingConfiguration.exposure;
  42418. },
  42419. /**
  42420. * The camera exposure used on this material.
  42421. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42422. * This corresponds to a photographic exposure.
  42423. */
  42424. set: function (value) {
  42425. this._imageProcessingConfiguration.exposure = value;
  42426. },
  42427. enumerable: true,
  42428. configurable: true
  42429. });
  42430. ;
  42431. ;
  42432. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  42433. /**
  42434. * Gets The camera contrast used on this material.
  42435. */
  42436. get: function () {
  42437. return this._imageProcessingConfiguration.contrast;
  42438. },
  42439. /**
  42440. * Sets The camera contrast used on this material.
  42441. */
  42442. set: function (value) {
  42443. this._imageProcessingConfiguration.contrast = value;
  42444. },
  42445. enumerable: true,
  42446. configurable: true
  42447. });
  42448. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  42449. /**
  42450. * Gets the Color Grading 2D Lookup Texture.
  42451. */
  42452. get: function () {
  42453. return this._imageProcessingConfiguration.colorGradingTexture;
  42454. },
  42455. /**
  42456. * Sets the Color Grading 2D Lookup Texture.
  42457. */
  42458. set: function (value) {
  42459. this._imageProcessingConfiguration.colorGradingTexture = value;
  42460. },
  42461. enumerable: true,
  42462. configurable: true
  42463. });
  42464. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  42465. /**
  42466. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42467. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42468. * These are similar to controls found in many professional imaging or colorist software. The global controls are applied to the entire image. For advanced tuning, extra controls are provided to adjust the shadow, midtone and highlight areas of the image;
  42469. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42470. */
  42471. get: function () {
  42472. return this._imageProcessingConfiguration.colorCurves;
  42473. },
  42474. /**
  42475. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42476. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42477. * These are similar to controls found in many professional imaging or colorist software. The global controls are applied to the entire image. For advanced tuning, extra controls are provided to adjust the shadow, midtone and highlight areas of the image;
  42478. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42479. */
  42480. set: function (value) {
  42481. this._imageProcessingConfiguration.colorCurves = value;
  42482. },
  42483. enumerable: true,
  42484. configurable: true
  42485. });
  42486. /**
  42487. * Returns the name of this material class.
  42488. */
  42489. PBRMaterial.prototype.getClassName = function () {
  42490. return "PBRMaterial";
  42491. };
  42492. /**
  42493. * Returns an array of the actively used textures.
  42494. * @returns - Array of BaseTextures
  42495. */
  42496. PBRMaterial.prototype.getActiveTextures = function () {
  42497. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42498. if (this._albedoTexture) {
  42499. activeTextures.push(this._albedoTexture);
  42500. }
  42501. if (this._ambientTexture) {
  42502. activeTextures.push(this._ambientTexture);
  42503. }
  42504. if (this._opacityTexture) {
  42505. activeTextures.push(this._opacityTexture);
  42506. }
  42507. if (this._reflectionTexture) {
  42508. activeTextures.push(this._reflectionTexture);
  42509. }
  42510. if (this._emissiveTexture) {
  42511. activeTextures.push(this._emissiveTexture);
  42512. }
  42513. if (this._reflectivityTexture) {
  42514. activeTextures.push(this._reflectivityTexture);
  42515. }
  42516. if (this._metallicTexture) {
  42517. activeTextures.push(this._metallicTexture);
  42518. }
  42519. if (this._microSurfaceTexture) {
  42520. activeTextures.push(this._microSurfaceTexture);
  42521. }
  42522. if (this._bumpTexture) {
  42523. activeTextures.push(this._bumpTexture);
  42524. }
  42525. if (this._lightmapTexture) {
  42526. activeTextures.push(this._lightmapTexture);
  42527. }
  42528. if (this._refractionTexture) {
  42529. activeTextures.push(this._refractionTexture);
  42530. }
  42531. return activeTextures;
  42532. };
  42533. /**
  42534. * Checks to see if a texture is used in the material.
  42535. * @param texture - Base texture to use.
  42536. * @returns - Boolean specifying if a texture is used in the material.
  42537. */
  42538. PBRMaterial.prototype.hasTexture = function (texture) {
  42539. if (_super.prototype.hasTexture.call(this, texture)) {
  42540. return true;
  42541. }
  42542. if (this._albedoTexture === texture) {
  42543. return true;
  42544. }
  42545. if (this._ambientTexture === texture) {
  42546. return true;
  42547. }
  42548. if (this._opacityTexture === texture) {
  42549. return true;
  42550. }
  42551. if (this._reflectionTexture === texture) {
  42552. return true;
  42553. }
  42554. if (this._reflectivityTexture === texture) {
  42555. return true;
  42556. }
  42557. if (this._metallicTexture === texture) {
  42558. return true;
  42559. }
  42560. if (this._microSurfaceTexture === texture) {
  42561. return true;
  42562. }
  42563. if (this._bumpTexture === texture) {
  42564. return true;
  42565. }
  42566. if (this._lightmapTexture === texture) {
  42567. return true;
  42568. }
  42569. if (this._refractionTexture === texture) {
  42570. return true;
  42571. }
  42572. return false;
  42573. };
  42574. /**
  42575. * Makes a duplicate of the current material.
  42576. * @param name - name to use for the new material.
  42577. */
  42578. PBRMaterial.prototype.clone = function (name) {
  42579. var _this = this;
  42580. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  42581. clone.id = name;
  42582. clone.name = name;
  42583. return clone;
  42584. };
  42585. /**
  42586. * Serializes this PBR Material.
  42587. * @returns - An object with the serialized material.
  42588. */
  42589. PBRMaterial.prototype.serialize = function () {
  42590. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  42591. serializationObject.customType = "BABYLON.PBRMaterial";
  42592. return serializationObject;
  42593. };
  42594. // Statics
  42595. /**
  42596. * Parses a PBR Material from a serialized object.
  42597. * @param source - Serialized object.
  42598. * @param scene - BJS scene instance.
  42599. * @param rootUrl - url for the scene object
  42600. * @returns - PBRMaterial
  42601. */
  42602. PBRMaterial.Parse = function (source, scene, rootUrl) {
  42603. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  42604. };
  42605. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  42606. /**
  42607. * Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  42608. */
  42609. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  42610. /**
  42611. * Represents the value for Alpha Blend. Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  42612. */
  42613. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  42614. /**
  42615. * Represents the value for Alpha Test and Blend. Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  42616. * They are also discarded below the alpha cutoff threshold to improve performances.
  42617. */
  42618. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  42619. __decorate([
  42620. BABYLON.serialize(),
  42621. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42622. ], PBRMaterial.prototype, "directIntensity", void 0);
  42623. __decorate([
  42624. BABYLON.serialize(),
  42625. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42626. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  42627. __decorate([
  42628. BABYLON.serialize(),
  42629. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42630. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  42631. __decorate([
  42632. BABYLON.serialize(),
  42633. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42634. ], PBRMaterial.prototype, "specularIntensity", void 0);
  42635. __decorate([
  42636. BABYLON.serialize(),
  42637. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42638. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  42639. __decorate([
  42640. BABYLON.serializeAsTexture(),
  42641. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42642. ], PBRMaterial.prototype, "albedoTexture", void 0);
  42643. __decorate([
  42644. BABYLON.serializeAsTexture(),
  42645. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42646. ], PBRMaterial.prototype, "ambientTexture", void 0);
  42647. __decorate([
  42648. BABYLON.serialize(),
  42649. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42650. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  42651. __decorate([
  42652. BABYLON.serializeAsTexture(),
  42653. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42654. ], PBRMaterial.prototype, "opacityTexture", void 0);
  42655. __decorate([
  42656. BABYLON.serializeAsTexture(),
  42657. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42658. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  42659. __decorate([
  42660. BABYLON.serializeAsTexture(),
  42661. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42662. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  42663. __decorate([
  42664. BABYLON.serializeAsTexture(),
  42665. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42666. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  42667. __decorate([
  42668. BABYLON.serializeAsTexture(),
  42669. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42670. ], PBRMaterial.prototype, "metallicTexture", void 0);
  42671. __decorate([
  42672. BABYLON.serialize(),
  42673. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42674. ], PBRMaterial.prototype, "metallic", void 0);
  42675. __decorate([
  42676. BABYLON.serialize(),
  42677. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42678. ], PBRMaterial.prototype, "roughness", void 0);
  42679. __decorate([
  42680. BABYLON.serializeAsTexture(),
  42681. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42682. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  42683. __decorate([
  42684. BABYLON.serializeAsTexture(),
  42685. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42686. ], PBRMaterial.prototype, "bumpTexture", void 0);
  42687. __decorate([
  42688. BABYLON.serializeAsTexture(),
  42689. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  42690. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  42691. __decorate([
  42692. BABYLON.serializeAsTexture(),
  42693. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42694. ], PBRMaterial.prototype, "refractionTexture", void 0);
  42695. __decorate([
  42696. BABYLON.serializeAsColor3("ambient"),
  42697. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42698. ], PBRMaterial.prototype, "ambientColor", void 0);
  42699. __decorate([
  42700. BABYLON.serializeAsColor3("albedo"),
  42701. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42702. ], PBRMaterial.prototype, "albedoColor", void 0);
  42703. __decorate([
  42704. BABYLON.serializeAsColor3("reflectivity"),
  42705. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42706. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  42707. __decorate([
  42708. BABYLON.serializeAsColor3("reflection"),
  42709. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42710. ], PBRMaterial.prototype, "reflectionColor", void 0);
  42711. __decorate([
  42712. BABYLON.serializeAsColor3("emissive"),
  42713. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42714. ], PBRMaterial.prototype, "emissiveColor", void 0);
  42715. __decorate([
  42716. BABYLON.serialize(),
  42717. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42718. ], PBRMaterial.prototype, "microSurface", void 0);
  42719. __decorate([
  42720. BABYLON.serialize(),
  42721. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42722. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  42723. __decorate([
  42724. BABYLON.serialize(),
  42725. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42726. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  42727. __decorate([
  42728. BABYLON.serialize(),
  42729. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42730. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  42731. __decorate([
  42732. BABYLON.serialize(),
  42733. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42734. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  42735. __decorate([
  42736. BABYLON.serialize(),
  42737. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42738. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  42739. __decorate([
  42740. BABYLON.serialize(),
  42741. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42742. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  42743. __decorate([
  42744. BABYLON.serialize(),
  42745. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42746. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  42747. __decorate([
  42748. BABYLON.serialize(),
  42749. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42750. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  42751. __decorate([
  42752. BABYLON.serialize(),
  42753. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42754. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  42755. __decorate([
  42756. BABYLON.serialize(),
  42757. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42758. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  42759. __decorate([
  42760. BABYLON.serialize(),
  42761. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42762. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  42763. __decorate([
  42764. BABYLON.serialize(),
  42765. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42766. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  42767. __decorate([
  42768. BABYLON.serialize(),
  42769. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42770. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  42771. __decorate([
  42772. BABYLON.serialize(),
  42773. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42774. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  42775. __decorate([
  42776. BABYLON.serialize(),
  42777. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42778. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  42779. __decorate([
  42780. BABYLON.serialize(),
  42781. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42782. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  42783. __decorate([
  42784. BABYLON.serialize(),
  42785. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42786. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  42787. __decorate([
  42788. BABYLON.serialize(),
  42789. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42790. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  42791. __decorate([
  42792. BABYLON.serialize(),
  42793. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42794. ], PBRMaterial.prototype, "useParallax", void 0);
  42795. __decorate([
  42796. BABYLON.serialize(),
  42797. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42798. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  42799. __decorate([
  42800. BABYLON.serialize(),
  42801. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42802. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  42803. __decorate([
  42804. BABYLON.serialize(),
  42805. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  42806. ], PBRMaterial.prototype, "disableLighting", void 0);
  42807. __decorate([
  42808. BABYLON.serialize(),
  42809. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42810. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  42811. __decorate([
  42812. BABYLON.serialize(),
  42813. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  42814. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  42815. __decorate([
  42816. BABYLON.serialize(),
  42817. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42818. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  42819. __decorate([
  42820. BABYLON.serialize(),
  42821. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42822. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  42823. __decorate([
  42824. BABYLON.serialize(),
  42825. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42826. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  42827. __decorate([
  42828. BABYLON.serialize(),
  42829. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42830. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  42831. __decorate([
  42832. BABYLON.serialize(),
  42833. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42834. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  42835. __decorate([
  42836. BABYLON.serializeAsTexture(),
  42837. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42838. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  42839. __decorate([
  42840. BABYLON.serialize(),
  42841. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42842. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  42843. __decorate([
  42844. BABYLON.serialize(),
  42845. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42846. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  42847. __decorate([
  42848. BABYLON.serialize(),
  42849. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42850. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  42851. return PBRMaterial;
  42852. }(BABYLON.PBRBaseMaterial));
  42853. BABYLON.PBRMaterial = PBRMaterial;
  42854. })(BABYLON || (BABYLON = {}));
  42855. //# sourceMappingURL=babylon.pbrMaterial.js.map
  42856. var BABYLON;
  42857. (function (BABYLON) {
  42858. /**
  42859. * The PBR material of BJS following the metal roughness convention.
  42860. *
  42861. * This fits to the PBR convention in the GLTF definition:
  42862. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  42863. */
  42864. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  42865. __extends(PBRMetallicRoughnessMaterial, _super);
  42866. /**
  42867. * Instantiates a new PBRMetalRoughnessMaterial instance.
  42868. *
  42869. * @param name The material name
  42870. * @param scene The scene the material will be use in.
  42871. */
  42872. function PBRMetallicRoughnessMaterial(name, scene) {
  42873. var _this = _super.call(this, name, scene) || this;
  42874. _this._useRoughnessFromMetallicTextureAlpha = false;
  42875. _this._useRoughnessFromMetallicTextureGreen = true;
  42876. _this._useMetallnessFromMetallicTextureBlue = true;
  42877. _this.metallic = 1.0;
  42878. _this.roughness = 1.0;
  42879. return _this;
  42880. }
  42881. /**
  42882. * Return the currrent class name of the material.
  42883. */
  42884. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  42885. return "PBRMetallicRoughnessMaterial";
  42886. };
  42887. /**
  42888. * Return the active textures of the material.
  42889. */
  42890. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  42891. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42892. if (this.baseTexture) {
  42893. activeTextures.push(this.baseTexture);
  42894. }
  42895. if (this.metallicRoughnessTexture) {
  42896. activeTextures.push(this.metallicRoughnessTexture);
  42897. }
  42898. return activeTextures;
  42899. };
  42900. /**
  42901. * Checks to see if a texture is used in the material.
  42902. * @param texture - Base texture to use.
  42903. * @returns - Boolean specifying if a texture is used in the material.
  42904. */
  42905. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  42906. if (_super.prototype.hasTexture.call(this, texture)) {
  42907. return true;
  42908. }
  42909. if (this.baseTexture === texture) {
  42910. return true;
  42911. }
  42912. if (this.metallicRoughnessTexture === texture) {
  42913. return true;
  42914. }
  42915. return false;
  42916. };
  42917. /**
  42918. * Makes a duplicate of the current material.
  42919. * @param name - name to use for the new material.
  42920. */
  42921. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  42922. var _this = this;
  42923. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  42924. clone.id = name;
  42925. clone.name = name;
  42926. return clone;
  42927. };
  42928. /**
  42929. * Serialize the material to a parsable JSON object.
  42930. */
  42931. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  42932. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  42933. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  42934. return serializationObject;
  42935. };
  42936. /**
  42937. * Parses a JSON object correponding to the serialize function.
  42938. */
  42939. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  42940. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  42941. };
  42942. __decorate([
  42943. BABYLON.serializeAsColor3(),
  42944. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  42945. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  42946. __decorate([
  42947. BABYLON.serializeAsTexture(),
  42948. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  42949. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  42950. __decorate([
  42951. BABYLON.serialize(),
  42952. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42953. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  42954. __decorate([
  42955. BABYLON.serialize(),
  42956. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42957. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  42958. __decorate([
  42959. BABYLON.serializeAsTexture(),
  42960. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  42961. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  42962. return PBRMetallicRoughnessMaterial;
  42963. }(BABYLON.PBRBaseSimpleMaterial));
  42964. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  42965. })(BABYLON || (BABYLON = {}));
  42966. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  42967. var BABYLON;
  42968. (function (BABYLON) {
  42969. /**
  42970. * The PBR material of BJS following the specular glossiness convention.
  42971. *
  42972. * This fits to the PBR convention in the GLTF definition:
  42973. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  42974. */
  42975. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  42976. __extends(PBRSpecularGlossinessMaterial, _super);
  42977. /**
  42978. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  42979. *
  42980. * @param name The material name
  42981. * @param scene The scene the material will be use in.
  42982. */
  42983. function PBRSpecularGlossinessMaterial(name, scene) {
  42984. var _this = _super.call(this, name, scene) || this;
  42985. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  42986. return _this;
  42987. }
  42988. /**
  42989. * Return the currrent class name of the material.
  42990. */
  42991. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  42992. return "PBRSpecularGlossinessMaterial";
  42993. };
  42994. /**
  42995. * Return the active textures of the material.
  42996. */
  42997. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  42998. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42999. if (this.diffuseTexture) {
  43000. activeTextures.push(this.diffuseTexture);
  43001. }
  43002. if (this.specularGlossinessTexture) {
  43003. activeTextures.push(this.specularGlossinessTexture);
  43004. }
  43005. return activeTextures;
  43006. };
  43007. /**
  43008. * Checks to see if a texture is used in the material.
  43009. * @param texture - Base texture to use.
  43010. * @returns - Boolean specifying if a texture is used in the material.
  43011. */
  43012. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  43013. if (_super.prototype.hasTexture.call(this, texture)) {
  43014. return true;
  43015. }
  43016. if (this.diffuseTexture === texture) {
  43017. return true;
  43018. }
  43019. if (this.specularGlossinessTexture === texture) {
  43020. return true;
  43021. }
  43022. return false;
  43023. };
  43024. /**
  43025. * Makes a duplicate of the current material.
  43026. * @param name - name to use for the new material.
  43027. */
  43028. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  43029. var _this = this;
  43030. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  43031. clone.id = name;
  43032. clone.name = name;
  43033. return clone;
  43034. };
  43035. /**
  43036. * Serialize the material to a parsable JSON object.
  43037. */
  43038. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  43039. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  43040. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  43041. return serializationObject;
  43042. };
  43043. /**
  43044. * Parses a JSON object correponding to the serialize function.
  43045. */
  43046. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  43047. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  43048. };
  43049. __decorate([
  43050. BABYLON.serializeAsColor3("diffuse"),
  43051. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  43052. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  43053. __decorate([
  43054. BABYLON.serializeAsTexture(),
  43055. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  43056. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  43057. __decorate([
  43058. BABYLON.serializeAsColor3("specular"),
  43059. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  43060. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  43061. __decorate([
  43062. BABYLON.serialize(),
  43063. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  43064. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  43065. __decorate([
  43066. BABYLON.serializeAsTexture(),
  43067. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  43068. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  43069. return PBRSpecularGlossinessMaterial;
  43070. }(BABYLON.PBRBaseSimpleMaterial));
  43071. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  43072. })(BABYLON || (BABYLON = {}));
  43073. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  43074. var BABYLON;
  43075. (function (BABYLON) {
  43076. BABYLON.CameraInputTypes = {};
  43077. var CameraInputsManager = /** @class */ (function () {
  43078. function CameraInputsManager(camera) {
  43079. this.attached = {};
  43080. this.camera = camera;
  43081. this.checkInputs = function () { };
  43082. }
  43083. /**
  43084. * Add an input method to a camera.
  43085. * builtin inputs example: camera.inputs.addGamepad();
  43086. * custom inputs example: camera.inputs.add(new BABYLON.FreeCameraGamepadInput());
  43087. * @param input camera input method
  43088. */
  43089. CameraInputsManager.prototype.add = function (input) {
  43090. var type = input.getSimpleName();
  43091. if (this.attached[type]) {
  43092. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  43093. return;
  43094. }
  43095. this.attached[type] = input;
  43096. input.camera = this.camera;
  43097. //for checkInputs, we are dynamically creating a function
  43098. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  43099. if (input.checkInputs) {
  43100. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  43101. }
  43102. if (this.attachedElement) {
  43103. input.attachControl(this.attachedElement);
  43104. }
  43105. };
  43106. /**
  43107. * Remove a specific input method from a camera
  43108. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  43109. * @param inputToRemove camera input method
  43110. */
  43111. CameraInputsManager.prototype.remove = function (inputToRemove) {
  43112. for (var cam in this.attached) {
  43113. var input = this.attached[cam];
  43114. if (input === inputToRemove) {
  43115. input.detachControl(this.attachedElement);
  43116. input.camera = null;
  43117. delete this.attached[cam];
  43118. this.rebuildInputCheck();
  43119. }
  43120. }
  43121. };
  43122. CameraInputsManager.prototype.removeByType = function (inputType) {
  43123. for (var cam in this.attached) {
  43124. var input = this.attached[cam];
  43125. if (input.getClassName() === inputType) {
  43126. input.detachControl(this.attachedElement);
  43127. input.camera = null;
  43128. delete this.attached[cam];
  43129. this.rebuildInputCheck();
  43130. }
  43131. }
  43132. };
  43133. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  43134. var current = this.checkInputs;
  43135. return function () {
  43136. current();
  43137. fn();
  43138. };
  43139. };
  43140. CameraInputsManager.prototype.attachInput = function (input) {
  43141. if (this.attachedElement) {
  43142. input.attachControl(this.attachedElement, this.noPreventDefault);
  43143. }
  43144. };
  43145. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  43146. if (noPreventDefault === void 0) { noPreventDefault = false; }
  43147. if (this.attachedElement) {
  43148. return;
  43149. }
  43150. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  43151. this.attachedElement = element;
  43152. this.noPreventDefault = noPreventDefault;
  43153. for (var cam in this.attached) {
  43154. this.attached[cam].attachControl(element, noPreventDefault);
  43155. }
  43156. };
  43157. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  43158. if (disconnect === void 0) { disconnect = false; }
  43159. if (this.attachedElement !== element) {
  43160. return;
  43161. }
  43162. for (var cam in this.attached) {
  43163. this.attached[cam].detachControl(element);
  43164. if (disconnect) {
  43165. this.attached[cam].camera = null;
  43166. }
  43167. }
  43168. this.attachedElement = null;
  43169. };
  43170. CameraInputsManager.prototype.rebuildInputCheck = function () {
  43171. this.checkInputs = function () { };
  43172. for (var cam in this.attached) {
  43173. var input = this.attached[cam];
  43174. if (input.checkInputs) {
  43175. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  43176. }
  43177. }
  43178. };
  43179. /**
  43180. * Remove all attached input methods from a camera
  43181. */
  43182. CameraInputsManager.prototype.clear = function () {
  43183. if (this.attachedElement) {
  43184. this.detachElement(this.attachedElement, true);
  43185. }
  43186. this.attached = {};
  43187. this.attachedElement = null;
  43188. this.checkInputs = function () { };
  43189. };
  43190. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  43191. var inputs = {};
  43192. for (var cam in this.attached) {
  43193. var input = this.attached[cam];
  43194. var res = BABYLON.SerializationHelper.Serialize(input);
  43195. inputs[input.getClassName()] = res;
  43196. }
  43197. serializedCamera.inputsmgr = inputs;
  43198. };
  43199. CameraInputsManager.prototype.parse = function (parsedCamera) {
  43200. var parsedInputs = parsedCamera.inputsmgr;
  43201. if (parsedInputs) {
  43202. this.clear();
  43203. for (var n in parsedInputs) {
  43204. var construct = BABYLON.CameraInputTypes[n];
  43205. if (construct) {
  43206. var parsedinput = parsedInputs[n];
  43207. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  43208. this.add(input);
  43209. }
  43210. }
  43211. }
  43212. else {
  43213. //2016-03-08 this part is for managing backward compatibility
  43214. for (var n in this.attached) {
  43215. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  43216. if (construct) {
  43217. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  43218. this.remove(this.attached[n]);
  43219. this.add(input);
  43220. }
  43221. }
  43222. }
  43223. };
  43224. return CameraInputsManager;
  43225. }());
  43226. BABYLON.CameraInputsManager = CameraInputsManager;
  43227. })(BABYLON || (BABYLON = {}));
  43228. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  43229. var BABYLON;
  43230. (function (BABYLON) {
  43231. var TargetCamera = /** @class */ (function (_super) {
  43232. __extends(TargetCamera, _super);
  43233. function TargetCamera(name, position, scene) {
  43234. var _this = _super.call(this, name, position, scene) || this;
  43235. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  43236. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  43237. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  43238. _this.speed = 2.0;
  43239. _this.noRotationConstraint = false;
  43240. _this.lockedTarget = null;
  43241. _this._currentTarget = BABYLON.Vector3.Zero();
  43242. _this._viewMatrix = BABYLON.Matrix.Zero();
  43243. _this._camMatrix = BABYLON.Matrix.Zero();
  43244. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  43245. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  43246. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  43247. _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
  43248. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  43249. _this._lookAtTemp = BABYLON.Matrix.Zero();
  43250. _this._tempMatrix = BABYLON.Matrix.Zero();
  43251. return _this;
  43252. }
  43253. TargetCamera.prototype.getFrontPosition = function (distance) {
  43254. this.getWorldMatrix();
  43255. var direction = this.getTarget().subtract(this.position);
  43256. direction.normalize();
  43257. direction.scaleInPlace(distance);
  43258. return this.globalPosition.add(direction);
  43259. };
  43260. TargetCamera.prototype._getLockedTargetPosition = function () {
  43261. if (!this.lockedTarget) {
  43262. return null;
  43263. }
  43264. if (this.lockedTarget.absolutePosition) {
  43265. this.lockedTarget.computeWorldMatrix();
  43266. }
  43267. return this.lockedTarget.absolutePosition || this.lockedTarget;
  43268. };
  43269. TargetCamera.prototype.storeState = function () {
  43270. this._storedPosition = this.position.clone();
  43271. this._storedRotation = this.rotation.clone();
  43272. if (this.rotationQuaternion) {
  43273. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  43274. }
  43275. return _super.prototype.storeState.call(this);
  43276. };
  43277. /**
  43278. * Restored camera state. You must call storeState() first
  43279. */
  43280. TargetCamera.prototype._restoreStateValues = function () {
  43281. if (!_super.prototype._restoreStateValues.call(this)) {
  43282. return false;
  43283. }
  43284. this.position = this._storedPosition.clone();
  43285. this.rotation = this._storedRotation.clone();
  43286. if (this.rotationQuaternion) {
  43287. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  43288. }
  43289. this.cameraDirection.copyFromFloats(0, 0, 0);
  43290. this.cameraRotation.copyFromFloats(0, 0);
  43291. return true;
  43292. };
  43293. // Cache
  43294. TargetCamera.prototype._initCache = function () {
  43295. _super.prototype._initCache.call(this);
  43296. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  43297. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  43298. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  43299. };
  43300. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  43301. if (!ignoreParentClass) {
  43302. _super.prototype._updateCache.call(this);
  43303. }
  43304. var lockedTargetPosition = this._getLockedTargetPosition();
  43305. if (!lockedTargetPosition) {
  43306. this._cache.lockedTarget = null;
  43307. }
  43308. else {
  43309. if (!this._cache.lockedTarget) {
  43310. this._cache.lockedTarget = lockedTargetPosition.clone();
  43311. }
  43312. else {
  43313. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  43314. }
  43315. }
  43316. this._cache.rotation.copyFrom(this.rotation);
  43317. if (this.rotationQuaternion)
  43318. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  43319. };
  43320. // Synchronized
  43321. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  43322. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  43323. return false;
  43324. }
  43325. var lockedTargetPosition = this._getLockedTargetPosition();
  43326. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  43327. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  43328. };
  43329. // Methods
  43330. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  43331. var engine = this.getEngine();
  43332. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  43333. };
  43334. // Target
  43335. TargetCamera.prototype.setTarget = function (target) {
  43336. this.upVector.normalize();
  43337. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  43338. this._camMatrix.invert();
  43339. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  43340. var vDir = target.subtract(this.position);
  43341. if (vDir.x >= 0.0) {
  43342. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  43343. }
  43344. else {
  43345. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  43346. }
  43347. this.rotation.z = 0;
  43348. if (isNaN(this.rotation.x)) {
  43349. this.rotation.x = 0;
  43350. }
  43351. if (isNaN(this.rotation.y)) {
  43352. this.rotation.y = 0;
  43353. }
  43354. if (isNaN(this.rotation.z)) {
  43355. this.rotation.z = 0;
  43356. }
  43357. if (this.rotationQuaternion) {
  43358. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  43359. }
  43360. };
  43361. /**
  43362. * Return the current target position of the camera. This value is expressed in local space.
  43363. */
  43364. TargetCamera.prototype.getTarget = function () {
  43365. return this._currentTarget;
  43366. };
  43367. TargetCamera.prototype._decideIfNeedsToMove = function () {
  43368. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  43369. };
  43370. TargetCamera.prototype._updatePosition = function () {
  43371. if (this.parent) {
  43372. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  43373. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  43374. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  43375. return;
  43376. }
  43377. this.position.addInPlace(this.cameraDirection);
  43378. };
  43379. TargetCamera.prototype._checkInputs = function () {
  43380. var needToMove = this._decideIfNeedsToMove();
  43381. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  43382. // Move
  43383. if (needToMove) {
  43384. this._updatePosition();
  43385. }
  43386. // Rotate
  43387. if (needToRotate) {
  43388. this.rotation.x += this.cameraRotation.x;
  43389. this.rotation.y += this.cameraRotation.y;
  43390. //rotate, if quaternion is set and rotation was used
  43391. if (this.rotationQuaternion) {
  43392. var len = this.rotation.lengthSquared();
  43393. if (len) {
  43394. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  43395. }
  43396. }
  43397. if (!this.noRotationConstraint) {
  43398. var limit = (Math.PI / 2) * 0.95;
  43399. if (this.rotation.x > limit)
  43400. this.rotation.x = limit;
  43401. if (this.rotation.x < -limit)
  43402. this.rotation.x = -limit;
  43403. }
  43404. }
  43405. // Inertia
  43406. if (needToMove) {
  43407. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  43408. this.cameraDirection.x = 0;
  43409. }
  43410. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  43411. this.cameraDirection.y = 0;
  43412. }
  43413. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  43414. this.cameraDirection.z = 0;
  43415. }
  43416. this.cameraDirection.scaleInPlace(this.inertia);
  43417. }
  43418. if (needToRotate) {
  43419. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  43420. this.cameraRotation.x = 0;
  43421. }
  43422. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  43423. this.cameraRotation.y = 0;
  43424. }
  43425. this.cameraRotation.scaleInPlace(this.inertia);
  43426. }
  43427. _super.prototype._checkInputs.call(this);
  43428. };
  43429. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  43430. if (this.rotationQuaternion) {
  43431. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  43432. }
  43433. else {
  43434. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  43435. }
  43436. //update the up vector!
  43437. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
  43438. };
  43439. TargetCamera.prototype._getViewMatrix = function () {
  43440. if (this.lockedTarget) {
  43441. this.setTarget(this._getLockedTargetPosition());
  43442. }
  43443. // Compute
  43444. this._updateCameraRotationMatrix();
  43445. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  43446. // Computing target and final matrix
  43447. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  43448. if (this.getScene().useRightHandedSystem) {
  43449. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  43450. }
  43451. else {
  43452. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  43453. }
  43454. return this._viewMatrix;
  43455. };
  43456. /**
  43457. * @override
  43458. * Override Camera.createRigCamera
  43459. */
  43460. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  43461. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  43462. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  43463. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  43464. if (!this.rotationQuaternion) {
  43465. this.rotationQuaternion = new BABYLON.Quaternion();
  43466. }
  43467. rigCamera._cameraRigParams = {};
  43468. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  43469. }
  43470. return rigCamera;
  43471. }
  43472. return null;
  43473. };
  43474. /**
  43475. * @override
  43476. * Override Camera._updateRigCameras
  43477. */
  43478. TargetCamera.prototype._updateRigCameras = function () {
  43479. var camLeft = this._rigCameras[0];
  43480. var camRight = this._rigCameras[1];
  43481. switch (this.cameraRigMode) {
  43482. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  43483. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  43484. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  43485. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  43486. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  43487. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  43488. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  43489. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  43490. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  43491. camLeft.setTarget(this.getTarget());
  43492. camRight.setTarget(this.getTarget());
  43493. break;
  43494. case BABYLON.Camera.RIG_MODE_VR:
  43495. if (camLeft.rotationQuaternion) {
  43496. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  43497. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  43498. }
  43499. else {
  43500. camLeft.rotation.copyFrom(this.rotation);
  43501. camRight.rotation.copyFrom(this.rotation);
  43502. }
  43503. camLeft.position.copyFrom(this.position);
  43504. camRight.position.copyFrom(this.position);
  43505. break;
  43506. }
  43507. _super.prototype._updateRigCameras.call(this);
  43508. };
  43509. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  43510. if (!this._rigCamTransformMatrix) {
  43511. this._rigCamTransformMatrix = new BABYLON.Matrix();
  43512. }
  43513. var target = this.getTarget();
  43514. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  43515. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  43516. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  43517. };
  43518. TargetCamera.prototype.getClassName = function () {
  43519. return "TargetCamera";
  43520. };
  43521. __decorate([
  43522. BABYLON.serializeAsVector3()
  43523. ], TargetCamera.prototype, "rotation", void 0);
  43524. __decorate([
  43525. BABYLON.serialize()
  43526. ], TargetCamera.prototype, "speed", void 0);
  43527. __decorate([
  43528. BABYLON.serializeAsMeshReference("lockedTargetId")
  43529. ], TargetCamera.prototype, "lockedTarget", void 0);
  43530. return TargetCamera;
  43531. }(BABYLON.Camera));
  43532. BABYLON.TargetCamera = TargetCamera;
  43533. })(BABYLON || (BABYLON = {}));
  43534. //# sourceMappingURL=babylon.targetCamera.js.map
  43535. var BABYLON;
  43536. (function (BABYLON) {
  43537. var FreeCameraMouseInput = /** @class */ (function () {
  43538. function FreeCameraMouseInput(touchEnabled) {
  43539. if (touchEnabled === void 0) { touchEnabled = true; }
  43540. this.touchEnabled = touchEnabled;
  43541. this.buttons = [0, 1, 2];
  43542. this.angularSensibility = 2000.0;
  43543. this.previousPosition = null;
  43544. }
  43545. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  43546. var _this = this;
  43547. var engine = this.camera.getEngine();
  43548. if (!this._pointerInput) {
  43549. this._pointerInput = function (p, s) {
  43550. var evt = p.event;
  43551. if (engine.isInVRExclusivePointerMode) {
  43552. return;
  43553. }
  43554. if (!_this.touchEnabled && evt.pointerType === "touch") {
  43555. return;
  43556. }
  43557. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  43558. return;
  43559. }
  43560. var srcElement = (evt.srcElement || evt.target);
  43561. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  43562. try {
  43563. srcElement.setPointerCapture(evt.pointerId);
  43564. }
  43565. catch (e) {
  43566. //Nothing to do with the error. Execution will continue.
  43567. }
  43568. _this.previousPosition = {
  43569. x: evt.clientX,
  43570. y: evt.clientY
  43571. };
  43572. if (!noPreventDefault) {
  43573. evt.preventDefault();
  43574. element.focus();
  43575. }
  43576. }
  43577. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  43578. try {
  43579. srcElement.releasePointerCapture(evt.pointerId);
  43580. }
  43581. catch (e) {
  43582. //Nothing to do with the error.
  43583. }
  43584. _this.previousPosition = null;
  43585. if (!noPreventDefault) {
  43586. evt.preventDefault();
  43587. }
  43588. }
  43589. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  43590. if (!_this.previousPosition || engine.isPointerLock) {
  43591. return;
  43592. }
  43593. var offsetX = evt.clientX - _this.previousPosition.x;
  43594. var offsetY = evt.clientY - _this.previousPosition.y;
  43595. if (_this.camera.getScene().useRightHandedSystem) {
  43596. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  43597. }
  43598. else {
  43599. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  43600. }
  43601. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  43602. _this.previousPosition = {
  43603. x: evt.clientX,
  43604. y: evt.clientY
  43605. };
  43606. if (!noPreventDefault) {
  43607. evt.preventDefault();
  43608. }
  43609. }
  43610. };
  43611. }
  43612. this._onMouseMove = function (evt) {
  43613. if (!engine.isPointerLock) {
  43614. return;
  43615. }
  43616. if (engine.isInVRExclusivePointerMode) {
  43617. return;
  43618. }
  43619. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  43620. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  43621. if (_this.camera.getScene().useRightHandedSystem) {
  43622. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  43623. }
  43624. else {
  43625. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  43626. }
  43627. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  43628. _this.previousPosition = null;
  43629. if (!noPreventDefault) {
  43630. evt.preventDefault();
  43631. }
  43632. };
  43633. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  43634. element.addEventListener("mousemove", this._onMouseMove, false);
  43635. };
  43636. FreeCameraMouseInput.prototype.detachControl = function (element) {
  43637. if (this._observer && element) {
  43638. this.camera.getScene().onPointerObservable.remove(this._observer);
  43639. if (this._onMouseMove) {
  43640. element.removeEventListener("mousemove", this._onMouseMove);
  43641. }
  43642. this._observer = null;
  43643. this._onMouseMove = null;
  43644. this.previousPosition = null;
  43645. }
  43646. };
  43647. FreeCameraMouseInput.prototype.getClassName = function () {
  43648. return "FreeCameraMouseInput";
  43649. };
  43650. FreeCameraMouseInput.prototype.getSimpleName = function () {
  43651. return "mouse";
  43652. };
  43653. __decorate([
  43654. BABYLON.serialize()
  43655. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  43656. __decorate([
  43657. BABYLON.serialize()
  43658. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  43659. return FreeCameraMouseInput;
  43660. }());
  43661. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  43662. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  43663. })(BABYLON || (BABYLON = {}));
  43664. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  43665. var BABYLON;
  43666. (function (BABYLON) {
  43667. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  43668. function FreeCameraKeyboardMoveInput() {
  43669. this._keys = new Array();
  43670. this.keysUp = [38];
  43671. this.keysDown = [40];
  43672. this.keysLeft = [37];
  43673. this.keysRight = [39];
  43674. }
  43675. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  43676. var _this = this;
  43677. if (this._onCanvasBlurObserver) {
  43678. return;
  43679. }
  43680. this._scene = this.camera.getScene();
  43681. this._engine = this._scene.getEngine();
  43682. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  43683. _this._keys = [];
  43684. });
  43685. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  43686. var evt = info.event;
  43687. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  43688. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  43689. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  43690. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  43691. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  43692. var index = _this._keys.indexOf(evt.keyCode);
  43693. if (index === -1) {
  43694. _this._keys.push(evt.keyCode);
  43695. }
  43696. if (!noPreventDefault) {
  43697. evt.preventDefault();
  43698. }
  43699. }
  43700. }
  43701. else {
  43702. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  43703. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  43704. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  43705. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  43706. var index = _this._keys.indexOf(evt.keyCode);
  43707. if (index >= 0) {
  43708. _this._keys.splice(index, 1);
  43709. }
  43710. if (!noPreventDefault) {
  43711. evt.preventDefault();
  43712. }
  43713. }
  43714. }
  43715. });
  43716. };
  43717. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  43718. if (this._scene) {
  43719. if (this._onKeyboardObserver) {
  43720. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  43721. }
  43722. if (this._onCanvasBlurObserver) {
  43723. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  43724. }
  43725. this._onKeyboardObserver = null;
  43726. this._onCanvasBlurObserver = null;
  43727. }
  43728. this._keys = [];
  43729. };
  43730. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  43731. if (this._onKeyboardObserver) {
  43732. var camera = this.camera;
  43733. // Keyboard
  43734. for (var index = 0; index < this._keys.length; index++) {
  43735. var keyCode = this._keys[index];
  43736. var speed = camera._computeLocalCameraSpeed();
  43737. if (this.keysLeft.indexOf(keyCode) !== -1) {
  43738. camera._localDirection.copyFromFloats(-speed, 0, 0);
  43739. }
  43740. else if (this.keysUp.indexOf(keyCode) !== -1) {
  43741. camera._localDirection.copyFromFloats(0, 0, speed);
  43742. }
  43743. else if (this.keysRight.indexOf(keyCode) !== -1) {
  43744. camera._localDirection.copyFromFloats(speed, 0, 0);
  43745. }
  43746. else if (this.keysDown.indexOf(keyCode) !== -1) {
  43747. camera._localDirection.copyFromFloats(0, 0, -speed);
  43748. }
  43749. if (camera.getScene().useRightHandedSystem) {
  43750. camera._localDirection.z *= -1;
  43751. }
  43752. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  43753. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  43754. camera.cameraDirection.addInPlace(camera._transformedDirection);
  43755. }
  43756. }
  43757. };
  43758. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  43759. return "FreeCameraKeyboardMoveInput";
  43760. };
  43761. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  43762. this._keys = [];
  43763. };
  43764. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  43765. return "keyboard";
  43766. };
  43767. __decorate([
  43768. BABYLON.serialize()
  43769. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  43770. __decorate([
  43771. BABYLON.serialize()
  43772. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  43773. __decorate([
  43774. BABYLON.serialize()
  43775. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  43776. __decorate([
  43777. BABYLON.serialize()
  43778. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  43779. return FreeCameraKeyboardMoveInput;
  43780. }());
  43781. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  43782. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  43783. })(BABYLON || (BABYLON = {}));
  43784. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  43785. var BABYLON;
  43786. (function (BABYLON) {
  43787. var FreeCameraInputsManager = /** @class */ (function (_super) {
  43788. __extends(FreeCameraInputsManager, _super);
  43789. function FreeCameraInputsManager(camera) {
  43790. return _super.call(this, camera) || this;
  43791. }
  43792. FreeCameraInputsManager.prototype.addKeyboard = function () {
  43793. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  43794. return this;
  43795. };
  43796. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  43797. if (touchEnabled === void 0) { touchEnabled = true; }
  43798. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  43799. return this;
  43800. };
  43801. FreeCameraInputsManager.prototype.addGamepad = function () {
  43802. this.add(new BABYLON.FreeCameraGamepadInput());
  43803. return this;
  43804. };
  43805. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  43806. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  43807. return this;
  43808. };
  43809. FreeCameraInputsManager.prototype.addTouch = function () {
  43810. this.add(new BABYLON.FreeCameraTouchInput());
  43811. return this;
  43812. };
  43813. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  43814. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  43815. return this;
  43816. };
  43817. return FreeCameraInputsManager;
  43818. }(BABYLON.CameraInputsManager));
  43819. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  43820. })(BABYLON || (BABYLON = {}));
  43821. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  43822. var BABYLON;
  43823. (function (BABYLON) {
  43824. var FreeCamera = /** @class */ (function (_super) {
  43825. __extends(FreeCamera, _super);
  43826. function FreeCamera(name, position, scene) {
  43827. var _this = _super.call(this, name, position, scene) || this;
  43828. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  43829. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  43830. _this.checkCollisions = false;
  43831. _this.applyGravity = false;
  43832. _this._needMoveForGravity = false;
  43833. _this._oldPosition = BABYLON.Vector3.Zero();
  43834. _this._diffPosition = BABYLON.Vector3.Zero();
  43835. _this._newPosition = BABYLON.Vector3.Zero();
  43836. // Collisions
  43837. _this._collisionMask = -1;
  43838. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  43839. if (collidedMesh === void 0) { collidedMesh = null; }
  43840. //TODO move this to the collision coordinator!
  43841. if (_this.getScene().workerCollisions)
  43842. newPosition.multiplyInPlace(_this._collider._radius);
  43843. var updatePosition = function (newPos) {
  43844. _this._newPosition.copyFrom(newPos);
  43845. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  43846. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  43847. _this.position.addInPlace(_this._diffPosition);
  43848. if (_this.onCollide && collidedMesh) {
  43849. _this.onCollide(collidedMesh);
  43850. }
  43851. }
  43852. };
  43853. updatePosition(newPosition);
  43854. };
  43855. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  43856. _this.inputs.addKeyboard().addMouse();
  43857. return _this;
  43858. }
  43859. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  43860. //-- begin properties for backward compatibility for inputs
  43861. /**
  43862. * Gets the input sensibility for a mouse input. (default is 2000.0)
  43863. * Higher values reduce sensitivity.
  43864. */
  43865. get: function () {
  43866. var mouse = this.inputs.attached["mouse"];
  43867. if (mouse)
  43868. return mouse.angularSensibility;
  43869. return 0;
  43870. },
  43871. /**
  43872. * Sets the input sensibility for a mouse input. (default is 2000.0)
  43873. * Higher values reduce sensitivity.
  43874. */
  43875. set: function (value) {
  43876. var mouse = this.inputs.attached["mouse"];
  43877. if (mouse)
  43878. mouse.angularSensibility = value;
  43879. },
  43880. enumerable: true,
  43881. configurable: true
  43882. });
  43883. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  43884. get: function () {
  43885. var keyboard = this.inputs.attached["keyboard"];
  43886. if (keyboard)
  43887. return keyboard.keysUp;
  43888. return [];
  43889. },
  43890. set: function (value) {
  43891. var keyboard = this.inputs.attached["keyboard"];
  43892. if (keyboard)
  43893. keyboard.keysUp = value;
  43894. },
  43895. enumerable: true,
  43896. configurable: true
  43897. });
  43898. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  43899. get: function () {
  43900. var keyboard = this.inputs.attached["keyboard"];
  43901. if (keyboard)
  43902. return keyboard.keysDown;
  43903. return [];
  43904. },
  43905. set: function (value) {
  43906. var keyboard = this.inputs.attached["keyboard"];
  43907. if (keyboard)
  43908. keyboard.keysDown = value;
  43909. },
  43910. enumerable: true,
  43911. configurable: true
  43912. });
  43913. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  43914. get: function () {
  43915. var keyboard = this.inputs.attached["keyboard"];
  43916. if (keyboard)
  43917. return keyboard.keysLeft;
  43918. return [];
  43919. },
  43920. set: function (value) {
  43921. var keyboard = this.inputs.attached["keyboard"];
  43922. if (keyboard)
  43923. keyboard.keysLeft = value;
  43924. },
  43925. enumerable: true,
  43926. configurable: true
  43927. });
  43928. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  43929. get: function () {
  43930. var keyboard = this.inputs.attached["keyboard"];
  43931. if (keyboard)
  43932. return keyboard.keysRight;
  43933. return [];
  43934. },
  43935. set: function (value) {
  43936. var keyboard = this.inputs.attached["keyboard"];
  43937. if (keyboard)
  43938. keyboard.keysRight = value;
  43939. },
  43940. enumerable: true,
  43941. configurable: true
  43942. });
  43943. // Controls
  43944. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  43945. this.inputs.attachElement(element, noPreventDefault);
  43946. };
  43947. FreeCamera.prototype.detachControl = function (element) {
  43948. this.inputs.detachElement(element);
  43949. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  43950. this.cameraRotation = new BABYLON.Vector2(0, 0);
  43951. };
  43952. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  43953. get: function () {
  43954. return this._collisionMask;
  43955. },
  43956. set: function (mask) {
  43957. this._collisionMask = !isNaN(mask) ? mask : -1;
  43958. },
  43959. enumerable: true,
  43960. configurable: true
  43961. });
  43962. FreeCamera.prototype._collideWithWorld = function (displacement) {
  43963. var globalPosition;
  43964. if (this.parent) {
  43965. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  43966. }
  43967. else {
  43968. globalPosition = this.position;
  43969. }
  43970. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  43971. this._oldPosition.addInPlace(this.ellipsoidOffset);
  43972. if (!this._collider) {
  43973. this._collider = new BABYLON.Collider();
  43974. }
  43975. this._collider._radius = this.ellipsoid;
  43976. this._collider.collisionMask = this._collisionMask;
  43977. //no need for clone, as long as gravity is not on.
  43978. var actualDisplacement = displacement;
  43979. //add gravity to the direction to prevent the dual-collision checking
  43980. if (this.applyGravity) {
  43981. //this prevents mending with cameraDirection, a global variable of the free camera class.
  43982. actualDisplacement = displacement.add(this.getScene().gravity);
  43983. }
  43984. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  43985. };
  43986. FreeCamera.prototype._checkInputs = function () {
  43987. if (!this._localDirection) {
  43988. this._localDirection = BABYLON.Vector3.Zero();
  43989. this._transformedDirection = BABYLON.Vector3.Zero();
  43990. }
  43991. this.inputs.checkInputs();
  43992. _super.prototype._checkInputs.call(this);
  43993. };
  43994. FreeCamera.prototype._decideIfNeedsToMove = function () {
  43995. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  43996. };
  43997. FreeCamera.prototype._updatePosition = function () {
  43998. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  43999. this._collideWithWorld(this.cameraDirection);
  44000. }
  44001. else {
  44002. _super.prototype._updatePosition.call(this);
  44003. }
  44004. };
  44005. FreeCamera.prototype.dispose = function () {
  44006. this.inputs.clear();
  44007. _super.prototype.dispose.call(this);
  44008. };
  44009. FreeCamera.prototype.getClassName = function () {
  44010. return "FreeCamera";
  44011. };
  44012. __decorate([
  44013. BABYLON.serializeAsVector3()
  44014. ], FreeCamera.prototype, "ellipsoid", void 0);
  44015. __decorate([
  44016. BABYLON.serializeAsVector3()
  44017. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  44018. __decorate([
  44019. BABYLON.serialize()
  44020. ], FreeCamera.prototype, "checkCollisions", void 0);
  44021. __decorate([
  44022. BABYLON.serialize()
  44023. ], FreeCamera.prototype, "applyGravity", void 0);
  44024. return FreeCamera;
  44025. }(BABYLON.TargetCamera));
  44026. BABYLON.FreeCamera = FreeCamera;
  44027. })(BABYLON || (BABYLON = {}));
  44028. //# sourceMappingURL=babylon.freeCamera.js.map
  44029. var BABYLON;
  44030. (function (BABYLON) {
  44031. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  44032. function ArcRotateCameraKeyboardMoveInput() {
  44033. this._keys = new Array();
  44034. this.keysUp = [38];
  44035. this.keysDown = [40];
  44036. this.keysLeft = [37];
  44037. this.keysRight = [39];
  44038. this.keysReset = [220];
  44039. this.panningSensibility = 50.0;
  44040. this.zoomingSensibility = 25.0;
  44041. this.useAltToZoom = true;
  44042. }
  44043. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  44044. var _this = this;
  44045. if (this._onCanvasBlurObserver) {
  44046. return;
  44047. }
  44048. this._scene = this.camera.getScene();
  44049. this._engine = this._scene.getEngine();
  44050. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  44051. _this._keys = [];
  44052. });
  44053. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  44054. var evt = info.event;
  44055. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  44056. _this._ctrlPressed = evt.ctrlKey;
  44057. _this._altPressed = evt.altKey;
  44058. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  44059. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  44060. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  44061. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  44062. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  44063. var index = _this._keys.indexOf(evt.keyCode);
  44064. if (index === -1) {
  44065. _this._keys.push(evt.keyCode);
  44066. }
  44067. if (evt.preventDefault) {
  44068. if (!noPreventDefault) {
  44069. evt.preventDefault();
  44070. }
  44071. }
  44072. }
  44073. }
  44074. else {
  44075. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  44076. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  44077. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  44078. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  44079. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  44080. var index = _this._keys.indexOf(evt.keyCode);
  44081. if (index >= 0) {
  44082. _this._keys.splice(index, 1);
  44083. }
  44084. if (evt.preventDefault) {
  44085. if (!noPreventDefault) {
  44086. evt.preventDefault();
  44087. }
  44088. }
  44089. }
  44090. }
  44091. });
  44092. };
  44093. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  44094. if (this._scene) {
  44095. if (this._onKeyboardObserver) {
  44096. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  44097. }
  44098. if (this._onCanvasBlurObserver) {
  44099. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  44100. }
  44101. this._onKeyboardObserver = null;
  44102. this._onCanvasBlurObserver = null;
  44103. }
  44104. this._keys = [];
  44105. };
  44106. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  44107. if (this._onKeyboardObserver) {
  44108. var camera = this.camera;
  44109. for (var index = 0; index < this._keys.length; index++) {
  44110. var keyCode = this._keys[index];
  44111. if (this.keysLeft.indexOf(keyCode) !== -1) {
  44112. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  44113. camera.inertialPanningX -= 1 / this.panningSensibility;
  44114. }
  44115. else {
  44116. camera.inertialAlphaOffset -= 0.01;
  44117. }
  44118. }
  44119. else if (this.keysUp.indexOf(keyCode) !== -1) {
  44120. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  44121. camera.inertialPanningY += 1 / this.panningSensibility;
  44122. }
  44123. else if (this._altPressed && this.useAltToZoom) {
  44124. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  44125. }
  44126. else {
  44127. camera.inertialBetaOffset -= 0.01;
  44128. }
  44129. }
  44130. else if (this.keysRight.indexOf(keyCode) !== -1) {
  44131. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  44132. camera.inertialPanningX += 1 / this.panningSensibility;
  44133. }
  44134. else {
  44135. camera.inertialAlphaOffset += 0.01;
  44136. }
  44137. }
  44138. else if (this.keysDown.indexOf(keyCode) !== -1) {
  44139. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  44140. camera.inertialPanningY -= 1 / this.panningSensibility;
  44141. }
  44142. else if (this._altPressed && this.useAltToZoom) {
  44143. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  44144. }
  44145. else {
  44146. camera.inertialBetaOffset += 0.01;
  44147. }
  44148. }
  44149. else if (this.keysReset.indexOf(keyCode) !== -1) {
  44150. camera.restoreState();
  44151. }
  44152. }
  44153. }
  44154. };
  44155. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  44156. return "ArcRotateCameraKeyboardMoveInput";
  44157. };
  44158. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  44159. return "keyboard";
  44160. };
  44161. __decorate([
  44162. BABYLON.serialize()
  44163. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  44164. __decorate([
  44165. BABYLON.serialize()
  44166. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  44167. __decorate([
  44168. BABYLON.serialize()
  44169. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  44170. __decorate([
  44171. BABYLON.serialize()
  44172. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  44173. __decorate([
  44174. BABYLON.serialize()
  44175. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  44176. __decorate([
  44177. BABYLON.serialize()
  44178. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  44179. __decorate([
  44180. BABYLON.serialize()
  44181. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  44182. __decorate([
  44183. BABYLON.serialize()
  44184. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  44185. return ArcRotateCameraKeyboardMoveInput;
  44186. }());
  44187. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  44188. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  44189. })(BABYLON || (BABYLON = {}));
  44190. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  44191. var BABYLON;
  44192. (function (BABYLON) {
  44193. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  44194. function ArcRotateCameraMouseWheelInput() {
  44195. this.wheelPrecision = 3.0;
  44196. /**
  44197. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  44198. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  44199. */
  44200. this.wheelDeltaPercentage = 0;
  44201. }
  44202. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  44203. var _this = this;
  44204. this._wheel = function (p, s) {
  44205. //sanity check - this should be a PointerWheel event.
  44206. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  44207. return;
  44208. var event = p.event;
  44209. var delta = 0;
  44210. if (event.wheelDelta) {
  44211. delta = _this.wheelDeltaPercentage ? (event.wheelDelta * 0.01) * _this.camera.radius * _this.wheelDeltaPercentage : event.wheelDelta / (_this.wheelPrecision * 40);
  44212. }
  44213. else if (event.detail) {
  44214. delta = -event.detail / _this.wheelPrecision;
  44215. }
  44216. if (delta)
  44217. _this.camera.inertialRadiusOffset += delta;
  44218. if (event.preventDefault) {
  44219. if (!noPreventDefault) {
  44220. event.preventDefault();
  44221. }
  44222. }
  44223. };
  44224. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  44225. };
  44226. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  44227. if (this._observer && element) {
  44228. this.camera.getScene().onPointerObservable.remove(this._observer);
  44229. this._observer = null;
  44230. this._wheel = null;
  44231. }
  44232. };
  44233. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  44234. return "ArcRotateCameraMouseWheelInput";
  44235. };
  44236. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  44237. return "mousewheel";
  44238. };
  44239. __decorate([
  44240. BABYLON.serialize()
  44241. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  44242. __decorate([
  44243. BABYLON.serialize()
  44244. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  44245. return ArcRotateCameraMouseWheelInput;
  44246. }());
  44247. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  44248. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  44249. })(BABYLON || (BABYLON = {}));
  44250. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  44251. var BABYLON;
  44252. (function (BABYLON) {
  44253. var ArcRotateCameraPointersInput = /** @class */ (function () {
  44254. function ArcRotateCameraPointersInput() {
  44255. this.buttons = [0, 1, 2];
  44256. this.angularSensibilityX = 1000.0;
  44257. this.angularSensibilityY = 1000.0;
  44258. this.pinchPrecision = 12.0;
  44259. /**
  44260. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  44261. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  44262. */
  44263. this.pinchDeltaPercentage = 0;
  44264. this.panningSensibility = 1000.0;
  44265. this.multiTouchPanning = true;
  44266. this.multiTouchPanAndZoom = true;
  44267. this._isPanClick = false;
  44268. this.pinchInwards = true;
  44269. }
  44270. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  44271. var _this = this;
  44272. var engine = this.camera.getEngine();
  44273. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  44274. var pointA = null;
  44275. var pointB = null;
  44276. var previousPinchSquaredDistance = 0;
  44277. var initialDistance = 0;
  44278. var twoFingerActivityCount = 0;
  44279. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  44280. this._pointerInput = function (p, s) {
  44281. var evt = p.event;
  44282. var isTouch = p.event.pointerType === "touch";
  44283. if (engine.isInVRExclusivePointerMode) {
  44284. return;
  44285. }
  44286. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  44287. return;
  44288. }
  44289. var srcElement = (evt.srcElement || evt.target);
  44290. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  44291. try {
  44292. srcElement.setPointerCapture(evt.pointerId);
  44293. }
  44294. catch (e) {
  44295. //Nothing to do with the error. Execution will continue.
  44296. }
  44297. // Manage panning with pan button click
  44298. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  44299. // manage pointers
  44300. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  44301. if (pointA === null) {
  44302. pointA = cacheSoloPointer;
  44303. }
  44304. else if (pointB === null) {
  44305. pointB = cacheSoloPointer;
  44306. }
  44307. if (!noPreventDefault) {
  44308. evt.preventDefault();
  44309. element.focus();
  44310. }
  44311. }
  44312. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  44313. _this.camera.restoreState();
  44314. }
  44315. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  44316. try {
  44317. srcElement.releasePointerCapture(evt.pointerId);
  44318. }
  44319. catch (e) {
  44320. //Nothing to do with the error.
  44321. }
  44322. cacheSoloPointer = null;
  44323. previousPinchSquaredDistance = 0;
  44324. previousMultiTouchPanPosition.isPaning = false;
  44325. previousMultiTouchPanPosition.isPinching = false;
  44326. twoFingerActivityCount = 0;
  44327. initialDistance = 0;
  44328. if (!isTouch) {
  44329. pointB = null; // Mouse and pen are mono pointer
  44330. }
  44331. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  44332. //but emptying completly pointers collection is required to fix a bug on iPhone :
  44333. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  44334. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  44335. if (engine.badOS) {
  44336. pointA = pointB = null;
  44337. }
  44338. else {
  44339. //only remove the impacted pointer in case of multitouch allowing on most
  44340. //platforms switching from rotate to zoom and pan seamlessly.
  44341. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  44342. pointA = pointB;
  44343. pointB = null;
  44344. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  44345. }
  44346. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  44347. pointB = null;
  44348. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  44349. }
  44350. else {
  44351. pointA = pointB = null;
  44352. }
  44353. }
  44354. if (!noPreventDefault) {
  44355. evt.preventDefault();
  44356. }
  44357. }
  44358. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  44359. if (!noPreventDefault) {
  44360. evt.preventDefault();
  44361. }
  44362. // One button down
  44363. if (pointA && pointB === null && cacheSoloPointer) {
  44364. if (_this.panningSensibility !== 0 &&
  44365. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  44366. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  44367. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  44368. }
  44369. else {
  44370. var offsetX = evt.clientX - cacheSoloPointer.x;
  44371. var offsetY = evt.clientY - cacheSoloPointer.y;
  44372. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  44373. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  44374. }
  44375. cacheSoloPointer.x = evt.clientX;
  44376. cacheSoloPointer.y = evt.clientY;
  44377. }
  44378. else if (pointA && pointB) {
  44379. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  44380. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  44381. ed.x = evt.clientX;
  44382. ed.y = evt.clientY;
  44383. var direction = _this.pinchInwards ? 1 : -1;
  44384. var distX = pointA.x - pointB.x;
  44385. var distY = pointA.y - pointB.y;
  44386. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  44387. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  44388. if (previousPinchSquaredDistance === 0) {
  44389. initialDistance = pinchDistance;
  44390. previousPinchSquaredDistance = pinchSquaredDistance;
  44391. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  44392. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  44393. return;
  44394. }
  44395. if (_this.multiTouchPanAndZoom) {
  44396. if (_this.pinchDeltaPercentage) {
  44397. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  44398. }
  44399. else {
  44400. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  44401. (_this.pinchPrecision *
  44402. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  44403. direction);
  44404. }
  44405. if (_this.panningSensibility !== 0) {
  44406. var pointersCenterX = (pointA.x + pointB.x) / 2;
  44407. var pointersCenterY = (pointA.y + pointB.y) / 2;
  44408. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  44409. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  44410. previousMultiTouchPanPosition.x = pointersCenterX;
  44411. previousMultiTouchPanPosition.y = pointersCenterY;
  44412. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  44413. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  44414. }
  44415. }
  44416. else {
  44417. twoFingerActivityCount++;
  44418. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  44419. if (_this.pinchDeltaPercentage) {
  44420. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  44421. }
  44422. else {
  44423. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  44424. (_this.pinchPrecision *
  44425. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  44426. direction);
  44427. }
  44428. previousMultiTouchPanPosition.isPaning = false;
  44429. previousMultiTouchPanPosition.isPinching = true;
  44430. }
  44431. else {
  44432. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  44433. if (!previousMultiTouchPanPosition.isPaning) {
  44434. previousMultiTouchPanPosition.isPaning = true;
  44435. previousMultiTouchPanPosition.isPinching = false;
  44436. previousMultiTouchPanPosition.x = ed.x;
  44437. previousMultiTouchPanPosition.y = ed.y;
  44438. return;
  44439. }
  44440. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  44441. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  44442. }
  44443. }
  44444. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  44445. previousMultiTouchPanPosition.x = ed.x;
  44446. previousMultiTouchPanPosition.y = ed.y;
  44447. }
  44448. }
  44449. previousPinchSquaredDistance = pinchSquaredDistance;
  44450. }
  44451. }
  44452. };
  44453. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  44454. this._onContextMenu = function (evt) {
  44455. evt.preventDefault();
  44456. };
  44457. if (!this.camera._useCtrlForPanning) {
  44458. element.addEventListener("contextmenu", this._onContextMenu, false);
  44459. }
  44460. this._onLostFocus = function () {
  44461. //this._keys = [];
  44462. pointA = pointB = null;
  44463. previousPinchSquaredDistance = 0;
  44464. previousMultiTouchPanPosition.isPaning = false;
  44465. previousMultiTouchPanPosition.isPinching = false;
  44466. twoFingerActivityCount = 0;
  44467. cacheSoloPointer = null;
  44468. initialDistance = 0;
  44469. };
  44470. this._onMouseMove = function (evt) {
  44471. if (!engine.isPointerLock) {
  44472. return;
  44473. }
  44474. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  44475. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  44476. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  44477. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  44478. if (!noPreventDefault) {
  44479. evt.preventDefault();
  44480. }
  44481. };
  44482. this._onGestureStart = function (e) {
  44483. if (window.MSGesture === undefined) {
  44484. return;
  44485. }
  44486. if (!_this._MSGestureHandler) {
  44487. _this._MSGestureHandler = new MSGesture();
  44488. _this._MSGestureHandler.target = element;
  44489. }
  44490. _this._MSGestureHandler.addPointer(e.pointerId);
  44491. };
  44492. this._onGesture = function (e) {
  44493. _this.camera.radius *= e.scale;
  44494. if (e.preventDefault) {
  44495. if (!noPreventDefault) {
  44496. e.stopPropagation();
  44497. e.preventDefault();
  44498. }
  44499. }
  44500. };
  44501. element.addEventListener("mousemove", this._onMouseMove, false);
  44502. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  44503. element.addEventListener("MSGestureChange", this._onGesture, false);
  44504. BABYLON.Tools.RegisterTopRootEvents([
  44505. { name: "blur", handler: this._onLostFocus }
  44506. ]);
  44507. };
  44508. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  44509. if (this._onLostFocus) {
  44510. BABYLON.Tools.UnregisterTopRootEvents([
  44511. { name: "blur", handler: this._onLostFocus }
  44512. ]);
  44513. }
  44514. if (element && this._observer) {
  44515. this.camera.getScene().onPointerObservable.remove(this._observer);
  44516. this._observer = null;
  44517. if (this._onContextMenu) {
  44518. element.removeEventListener("contextmenu", this._onContextMenu);
  44519. }
  44520. if (this._onMouseMove) {
  44521. element.removeEventListener("mousemove", this._onMouseMove);
  44522. }
  44523. if (this._onGestureStart) {
  44524. element.removeEventListener("MSPointerDown", this._onGestureStart);
  44525. }
  44526. if (this._onGesture) {
  44527. element.removeEventListener("MSGestureChange", this._onGesture);
  44528. }
  44529. this._isPanClick = false;
  44530. this.pinchInwards = true;
  44531. this._onMouseMove = null;
  44532. this._onGestureStart = null;
  44533. this._onGesture = null;
  44534. this._MSGestureHandler = null;
  44535. this._onLostFocus = null;
  44536. this._onContextMenu = null;
  44537. }
  44538. };
  44539. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  44540. return "ArcRotateCameraPointersInput";
  44541. };
  44542. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  44543. return "pointers";
  44544. };
  44545. __decorate([
  44546. BABYLON.serialize()
  44547. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  44548. __decorate([
  44549. BABYLON.serialize()
  44550. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  44551. __decorate([
  44552. BABYLON.serialize()
  44553. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  44554. __decorate([
  44555. BABYLON.serialize()
  44556. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  44557. __decorate([
  44558. BABYLON.serialize()
  44559. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  44560. __decorate([
  44561. BABYLON.serialize()
  44562. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  44563. __decorate([
  44564. BABYLON.serialize()
  44565. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  44566. __decorate([
  44567. BABYLON.serialize()
  44568. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  44569. return ArcRotateCameraPointersInput;
  44570. }());
  44571. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  44572. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  44573. })(BABYLON || (BABYLON = {}));
  44574. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  44575. var BABYLON;
  44576. (function (BABYLON) {
  44577. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  44578. __extends(ArcRotateCameraInputsManager, _super);
  44579. function ArcRotateCameraInputsManager(camera) {
  44580. return _super.call(this, camera) || this;
  44581. }
  44582. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  44583. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  44584. return this;
  44585. };
  44586. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  44587. this.add(new BABYLON.ArcRotateCameraPointersInput());
  44588. return this;
  44589. };
  44590. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  44591. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  44592. return this;
  44593. };
  44594. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  44595. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  44596. return this;
  44597. };
  44598. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  44599. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  44600. return this;
  44601. };
  44602. return ArcRotateCameraInputsManager;
  44603. }(BABYLON.CameraInputsManager));
  44604. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  44605. })(BABYLON || (BABYLON = {}));
  44606. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  44607. var BABYLON;
  44608. (function (BABYLON) {
  44609. var ArcRotateCamera = /** @class */ (function (_super) {
  44610. __extends(ArcRotateCamera, _super);
  44611. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  44612. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  44613. _this.inertialAlphaOffset = 0;
  44614. _this.inertialBetaOffset = 0;
  44615. _this.inertialRadiusOffset = 0;
  44616. _this.lowerAlphaLimit = null;
  44617. _this.upperAlphaLimit = null;
  44618. _this.lowerBetaLimit = 0.01;
  44619. _this.upperBetaLimit = Math.PI;
  44620. _this.lowerRadiusLimit = null;
  44621. _this.upperRadiusLimit = null;
  44622. _this.inertialPanningX = 0;
  44623. _this.inertialPanningY = 0;
  44624. _this.pinchToPanMaxDistance = 20;
  44625. _this.panningDistanceLimit = null;
  44626. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  44627. _this.panningInertia = 0.9;
  44628. //-- end properties for backward compatibility for inputs
  44629. _this.zoomOnFactor = 1;
  44630. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  44631. _this.allowUpsideDown = true;
  44632. _this._viewMatrix = new BABYLON.Matrix();
  44633. // Panning
  44634. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  44635. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  44636. _this.checkCollisions = false;
  44637. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  44638. _this._previousPosition = BABYLON.Vector3.Zero();
  44639. _this._collisionVelocity = BABYLON.Vector3.Zero();
  44640. _this._newPosition = BABYLON.Vector3.Zero();
  44641. _this._computationVector = BABYLON.Vector3.Zero();
  44642. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  44643. if (collidedMesh === void 0) { collidedMesh = null; }
  44644. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  44645. newPosition.multiplyInPlace(_this._collider._radius);
  44646. }
  44647. if (!collidedMesh) {
  44648. _this._previousPosition.copyFrom(_this.position);
  44649. }
  44650. else {
  44651. _this.setPosition(newPosition);
  44652. if (_this.onCollide) {
  44653. _this.onCollide(collidedMesh);
  44654. }
  44655. }
  44656. // Recompute because of constraints
  44657. var cosa = Math.cos(_this.alpha);
  44658. var sina = Math.sin(_this.alpha);
  44659. var cosb = Math.cos(_this.beta);
  44660. var sinb = Math.sin(_this.beta);
  44661. if (sinb === 0) {
  44662. sinb = 0.0001;
  44663. }
  44664. var target = _this._getTargetPosition();
  44665. _this._computationVector.copyFromFloats(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb);
  44666. target.addToRef(_this._computationVector, _this._newPosition);
  44667. _this.position.copyFrom(_this._newPosition);
  44668. var up = _this.upVector;
  44669. if (_this.allowUpsideDown && _this.beta < 0) {
  44670. up = up.clone();
  44671. up = up.negate();
  44672. }
  44673. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  44674. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  44675. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  44676. _this._collisionTriggered = false;
  44677. };
  44678. _this._target = BABYLON.Vector3.Zero();
  44679. if (target) {
  44680. _this.setTarget(target);
  44681. }
  44682. _this.alpha = alpha;
  44683. _this.beta = beta;
  44684. _this.radius = radius;
  44685. _this.getViewMatrix();
  44686. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  44687. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  44688. return _this;
  44689. }
  44690. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  44691. get: function () {
  44692. return this._target;
  44693. },
  44694. set: function (value) {
  44695. this.setTarget(value);
  44696. },
  44697. enumerable: true,
  44698. configurable: true
  44699. });
  44700. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  44701. //-- begin properties for backward compatibility for inputs
  44702. get: function () {
  44703. var pointers = this.inputs.attached["pointers"];
  44704. if (pointers)
  44705. return pointers.angularSensibilityX;
  44706. return 0;
  44707. },
  44708. set: function (value) {
  44709. var pointers = this.inputs.attached["pointers"];
  44710. if (pointers) {
  44711. pointers.angularSensibilityX = value;
  44712. }
  44713. },
  44714. enumerable: true,
  44715. configurable: true
  44716. });
  44717. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  44718. get: function () {
  44719. var pointers = this.inputs.attached["pointers"];
  44720. if (pointers)
  44721. return pointers.angularSensibilityY;
  44722. return 0;
  44723. },
  44724. set: function (value) {
  44725. var pointers = this.inputs.attached["pointers"];
  44726. if (pointers) {
  44727. pointers.angularSensibilityY = value;
  44728. }
  44729. },
  44730. enumerable: true,
  44731. configurable: true
  44732. });
  44733. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  44734. get: function () {
  44735. var pointers = this.inputs.attached["pointers"];
  44736. if (pointers)
  44737. return pointers.pinchPrecision;
  44738. return 0;
  44739. },
  44740. set: function (value) {
  44741. var pointers = this.inputs.attached["pointers"];
  44742. if (pointers) {
  44743. pointers.pinchPrecision = value;
  44744. }
  44745. },
  44746. enumerable: true,
  44747. configurable: true
  44748. });
  44749. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  44750. get: function () {
  44751. var pointers = this.inputs.attached["pointers"];
  44752. if (pointers)
  44753. return pointers.pinchDeltaPercentage;
  44754. return 0;
  44755. },
  44756. set: function (value) {
  44757. var pointers = this.inputs.attached["pointers"];
  44758. if (pointers) {
  44759. pointers.pinchDeltaPercentage = value;
  44760. }
  44761. },
  44762. enumerable: true,
  44763. configurable: true
  44764. });
  44765. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  44766. get: function () {
  44767. var pointers = this.inputs.attached["pointers"];
  44768. if (pointers)
  44769. return pointers.panningSensibility;
  44770. return 0;
  44771. },
  44772. set: function (value) {
  44773. var pointers = this.inputs.attached["pointers"];
  44774. if (pointers) {
  44775. pointers.panningSensibility = value;
  44776. }
  44777. },
  44778. enumerable: true,
  44779. configurable: true
  44780. });
  44781. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  44782. get: function () {
  44783. var keyboard = this.inputs.attached["keyboard"];
  44784. if (keyboard)
  44785. return keyboard.keysUp;
  44786. return [];
  44787. },
  44788. set: function (value) {
  44789. var keyboard = this.inputs.attached["keyboard"];
  44790. if (keyboard)
  44791. keyboard.keysUp = value;
  44792. },
  44793. enumerable: true,
  44794. configurable: true
  44795. });
  44796. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  44797. get: function () {
  44798. var keyboard = this.inputs.attached["keyboard"];
  44799. if (keyboard)
  44800. return keyboard.keysDown;
  44801. return [];
  44802. },
  44803. set: function (value) {
  44804. var keyboard = this.inputs.attached["keyboard"];
  44805. if (keyboard)
  44806. keyboard.keysDown = value;
  44807. },
  44808. enumerable: true,
  44809. configurable: true
  44810. });
  44811. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  44812. get: function () {
  44813. var keyboard = this.inputs.attached["keyboard"];
  44814. if (keyboard)
  44815. return keyboard.keysLeft;
  44816. return [];
  44817. },
  44818. set: function (value) {
  44819. var keyboard = this.inputs.attached["keyboard"];
  44820. if (keyboard)
  44821. keyboard.keysLeft = value;
  44822. },
  44823. enumerable: true,
  44824. configurable: true
  44825. });
  44826. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  44827. get: function () {
  44828. var keyboard = this.inputs.attached["keyboard"];
  44829. if (keyboard)
  44830. return keyboard.keysRight;
  44831. return [];
  44832. },
  44833. set: function (value) {
  44834. var keyboard = this.inputs.attached["keyboard"];
  44835. if (keyboard)
  44836. keyboard.keysRight = value;
  44837. },
  44838. enumerable: true,
  44839. configurable: true
  44840. });
  44841. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  44842. get: function () {
  44843. var mousewheel = this.inputs.attached["mousewheel"];
  44844. if (mousewheel)
  44845. return mousewheel.wheelPrecision;
  44846. return 0;
  44847. },
  44848. set: function (value) {
  44849. var mousewheel = this.inputs.attached["mousewheel"];
  44850. if (mousewheel)
  44851. mousewheel.wheelPrecision = value;
  44852. },
  44853. enumerable: true,
  44854. configurable: true
  44855. });
  44856. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  44857. get: function () {
  44858. var mousewheel = this.inputs.attached["mousewheel"];
  44859. if (mousewheel)
  44860. return mousewheel.wheelDeltaPercentage;
  44861. return 0;
  44862. },
  44863. set: function (value) {
  44864. var mousewheel = this.inputs.attached["mousewheel"];
  44865. if (mousewheel)
  44866. mousewheel.wheelDeltaPercentage = value;
  44867. },
  44868. enumerable: true,
  44869. configurable: true
  44870. });
  44871. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  44872. get: function () {
  44873. return this._bouncingBehavior;
  44874. },
  44875. enumerable: true,
  44876. configurable: true
  44877. });
  44878. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  44879. get: function () {
  44880. return this._bouncingBehavior != null;
  44881. },
  44882. set: function (value) {
  44883. if (value === this.useBouncingBehavior) {
  44884. return;
  44885. }
  44886. if (value) {
  44887. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  44888. this.addBehavior(this._bouncingBehavior);
  44889. }
  44890. else if (this._bouncingBehavior) {
  44891. this.removeBehavior(this._bouncingBehavior);
  44892. this._bouncingBehavior = null;
  44893. }
  44894. },
  44895. enumerable: true,
  44896. configurable: true
  44897. });
  44898. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  44899. get: function () {
  44900. return this._framingBehavior;
  44901. },
  44902. enumerable: true,
  44903. configurable: true
  44904. });
  44905. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  44906. get: function () {
  44907. return this._framingBehavior != null;
  44908. },
  44909. set: function (value) {
  44910. if (value === this.useFramingBehavior) {
  44911. return;
  44912. }
  44913. if (value) {
  44914. this._framingBehavior = new BABYLON.FramingBehavior();
  44915. this.addBehavior(this._framingBehavior);
  44916. }
  44917. else if (this._framingBehavior) {
  44918. this.removeBehavior(this._framingBehavior);
  44919. this._framingBehavior = null;
  44920. }
  44921. },
  44922. enumerable: true,
  44923. configurable: true
  44924. });
  44925. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  44926. get: function () {
  44927. return this._autoRotationBehavior;
  44928. },
  44929. enumerable: true,
  44930. configurable: true
  44931. });
  44932. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  44933. get: function () {
  44934. return this._autoRotationBehavior != null;
  44935. },
  44936. set: function (value) {
  44937. if (value === this.useAutoRotationBehavior) {
  44938. return;
  44939. }
  44940. if (value) {
  44941. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  44942. this.addBehavior(this._autoRotationBehavior);
  44943. }
  44944. else if (this._autoRotationBehavior) {
  44945. this.removeBehavior(this._autoRotationBehavior);
  44946. this._autoRotationBehavior = null;
  44947. }
  44948. },
  44949. enumerable: true,
  44950. configurable: true
  44951. });
  44952. // Cache
  44953. ArcRotateCamera.prototype._initCache = function () {
  44954. _super.prototype._initCache.call(this);
  44955. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  44956. this._cache.alpha = undefined;
  44957. this._cache.beta = undefined;
  44958. this._cache.radius = undefined;
  44959. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  44960. };
  44961. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  44962. if (!ignoreParentClass) {
  44963. _super.prototype._updateCache.call(this);
  44964. }
  44965. this._cache._target.copyFrom(this._getTargetPosition());
  44966. this._cache.alpha = this.alpha;
  44967. this._cache.beta = this.beta;
  44968. this._cache.radius = this.radius;
  44969. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  44970. };
  44971. ArcRotateCamera.prototype._getTargetPosition = function () {
  44972. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  44973. var pos = this._targetHost.getAbsolutePosition();
  44974. if (this._targetBoundingCenter) {
  44975. pos.addToRef(this._targetBoundingCenter, this._target);
  44976. }
  44977. else {
  44978. this._target.copyFrom(pos);
  44979. }
  44980. }
  44981. var lockedTargetPosition = this._getLockedTargetPosition();
  44982. if (lockedTargetPosition) {
  44983. return lockedTargetPosition;
  44984. }
  44985. return this._target;
  44986. };
  44987. ArcRotateCamera.prototype.storeState = function () {
  44988. this._storedAlpha = this.alpha;
  44989. this._storedBeta = this.beta;
  44990. this._storedRadius = this.radius;
  44991. this._storedTarget = this._getTargetPosition().clone();
  44992. return _super.prototype.storeState.call(this);
  44993. };
  44994. /**
  44995. * Restored camera state. You must call storeState() first
  44996. */
  44997. ArcRotateCamera.prototype._restoreStateValues = function () {
  44998. if (!_super.prototype._restoreStateValues.call(this)) {
  44999. return false;
  45000. }
  45001. this.alpha = this._storedAlpha;
  45002. this.beta = this._storedBeta;
  45003. this.radius = this._storedRadius;
  45004. this.setTarget(this._storedTarget.clone());
  45005. this.inertialAlphaOffset = 0;
  45006. this.inertialBetaOffset = 0;
  45007. this.inertialRadiusOffset = 0;
  45008. this.inertialPanningX = 0;
  45009. this.inertialPanningY = 0;
  45010. return true;
  45011. };
  45012. // Synchronized
  45013. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  45014. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  45015. return false;
  45016. return this._cache._target.equals(this._getTargetPosition())
  45017. && this._cache.alpha === this.alpha
  45018. && this._cache.beta === this.beta
  45019. && this._cache.radius === this.radius
  45020. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  45021. };
  45022. // Methods
  45023. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  45024. var _this = this;
  45025. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  45026. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  45027. this._useCtrlForPanning = useCtrlForPanning;
  45028. this._panningMouseButton = panningMouseButton;
  45029. this.inputs.attachElement(element, noPreventDefault);
  45030. this._reset = function () {
  45031. _this.inertialAlphaOffset = 0;
  45032. _this.inertialBetaOffset = 0;
  45033. _this.inertialRadiusOffset = 0;
  45034. _this.inertialPanningX = 0;
  45035. _this.inertialPanningY = 0;
  45036. };
  45037. };
  45038. ArcRotateCamera.prototype.detachControl = function (element) {
  45039. this.inputs.detachElement(element);
  45040. if (this._reset) {
  45041. this._reset();
  45042. }
  45043. };
  45044. ArcRotateCamera.prototype._checkInputs = function () {
  45045. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  45046. if (this._collisionTriggered) {
  45047. return;
  45048. }
  45049. this.inputs.checkInputs();
  45050. // Inertia
  45051. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  45052. if (this.getScene().useRightHandedSystem) {
  45053. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  45054. }
  45055. else {
  45056. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  45057. }
  45058. this.beta += this.inertialBetaOffset;
  45059. this.radius -= this.inertialRadiusOffset;
  45060. this.inertialAlphaOffset *= this.inertia;
  45061. this.inertialBetaOffset *= this.inertia;
  45062. this.inertialRadiusOffset *= this.inertia;
  45063. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  45064. this.inertialAlphaOffset = 0;
  45065. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  45066. this.inertialBetaOffset = 0;
  45067. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  45068. this.inertialRadiusOffset = 0;
  45069. }
  45070. // Panning inertia
  45071. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  45072. if (!this._localDirection) {
  45073. this._localDirection = BABYLON.Vector3.Zero();
  45074. this._transformedDirection = BABYLON.Vector3.Zero();
  45075. }
  45076. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  45077. this._localDirection.multiplyInPlace(this.panningAxis);
  45078. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  45079. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  45080. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  45081. if (!this.panningAxis.y) {
  45082. this._transformedDirection.y = 0;
  45083. }
  45084. if (!this._targetHost) {
  45085. if (this.panningDistanceLimit) {
  45086. this._transformedDirection.addInPlace(this._target);
  45087. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  45088. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  45089. this._target.copyFrom(this._transformedDirection);
  45090. }
  45091. }
  45092. else {
  45093. this._target.addInPlace(this._transformedDirection);
  45094. }
  45095. }
  45096. this.inertialPanningX *= this.panningInertia;
  45097. this.inertialPanningY *= this.panningInertia;
  45098. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  45099. this.inertialPanningX = 0;
  45100. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  45101. this.inertialPanningY = 0;
  45102. }
  45103. // Limits
  45104. this._checkLimits();
  45105. _super.prototype._checkInputs.call(this);
  45106. };
  45107. ArcRotateCamera.prototype._checkLimits = function () {
  45108. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  45109. if (this.allowUpsideDown && this.beta > Math.PI) {
  45110. this.beta = this.beta - (2 * Math.PI);
  45111. }
  45112. }
  45113. else {
  45114. if (this.beta < this.lowerBetaLimit) {
  45115. this.beta = this.lowerBetaLimit;
  45116. }
  45117. }
  45118. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  45119. if (this.allowUpsideDown && this.beta < -Math.PI) {
  45120. this.beta = this.beta + (2 * Math.PI);
  45121. }
  45122. }
  45123. else {
  45124. if (this.beta > this.upperBetaLimit) {
  45125. this.beta = this.upperBetaLimit;
  45126. }
  45127. }
  45128. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  45129. this.alpha = this.lowerAlphaLimit;
  45130. }
  45131. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  45132. this.alpha = this.upperAlphaLimit;
  45133. }
  45134. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  45135. this.radius = this.lowerRadiusLimit;
  45136. }
  45137. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  45138. this.radius = this.upperRadiusLimit;
  45139. }
  45140. };
  45141. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  45142. this.position.subtractToRef(this._getTargetPosition(), this._computationVector);
  45143. this.radius = this._computationVector.length();
  45144. if (this.radius === 0) {
  45145. this.radius = 0.0001; // Just to avoid division by zero
  45146. }
  45147. // Alpha
  45148. this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2)));
  45149. if (this._computationVector.z < 0) {
  45150. this.alpha = 2 * Math.PI - this.alpha;
  45151. }
  45152. // Beta
  45153. this.beta = Math.acos(this._computationVector.y / this.radius);
  45154. this._checkLimits();
  45155. };
  45156. ArcRotateCamera.prototype.setPosition = function (position) {
  45157. if (this.position.equals(position)) {
  45158. return;
  45159. }
  45160. this.position.copyFrom(position);
  45161. this.rebuildAnglesAndRadius();
  45162. };
  45163. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  45164. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  45165. if (allowSamePosition === void 0) { allowSamePosition = false; }
  45166. if (target.getBoundingInfo) {
  45167. if (toBoundingCenter) {
  45168. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  45169. }
  45170. else {
  45171. this._targetBoundingCenter = null;
  45172. }
  45173. this._targetHost = target;
  45174. this._target = this._getTargetPosition();
  45175. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  45176. }
  45177. else {
  45178. var newTarget = target;
  45179. var currentTarget = this._getTargetPosition();
  45180. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  45181. return;
  45182. }
  45183. this._targetHost = null;
  45184. this._target = newTarget;
  45185. this._targetBoundingCenter = null;
  45186. this.onMeshTargetChangedObservable.notifyObservers(null);
  45187. }
  45188. this.rebuildAnglesAndRadius();
  45189. };
  45190. ArcRotateCamera.prototype._getViewMatrix = function () {
  45191. // Compute
  45192. var cosa = Math.cos(this.alpha);
  45193. var sina = Math.sin(this.alpha);
  45194. var cosb = Math.cos(this.beta);
  45195. var sinb = Math.sin(this.beta);
  45196. if (sinb === 0) {
  45197. sinb = 0.0001;
  45198. }
  45199. var target = this._getTargetPosition();
  45200. this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);
  45201. target.addToRef(this._computationVector, this._newPosition);
  45202. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  45203. if (!this._collider) {
  45204. this._collider = new BABYLON.Collider();
  45205. }
  45206. this._collider._radius = this.collisionRadius;
  45207. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  45208. this._collisionTriggered = true;
  45209. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  45210. }
  45211. else {
  45212. this.position.copyFrom(this._newPosition);
  45213. var up = this.upVector;
  45214. if (this.allowUpsideDown && sinb < 0) {
  45215. up = up.clone();
  45216. up = up.negate();
  45217. }
  45218. if (this.getScene().useRightHandedSystem) {
  45219. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  45220. }
  45221. else {
  45222. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  45223. }
  45224. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  45225. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  45226. }
  45227. this._currentTarget = target;
  45228. return this._viewMatrix;
  45229. };
  45230. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  45231. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  45232. meshes = meshes || this.getScene().meshes;
  45233. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  45234. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  45235. this.radius = distance * this.zoomOnFactor;
  45236. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  45237. };
  45238. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  45239. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  45240. var meshesOrMinMaxVector;
  45241. var distance;
  45242. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  45243. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  45244. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  45245. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  45246. }
  45247. else {
  45248. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  45249. meshesOrMinMaxVector = minMaxVectorAndDistance;
  45250. distance = minMaxVectorAndDistance.distance;
  45251. }
  45252. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  45253. if (!doNotUpdateMaxZ) {
  45254. this.maxZ = distance * 2;
  45255. }
  45256. };
  45257. /**
  45258. * @override
  45259. * Override Camera.createRigCamera
  45260. */
  45261. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  45262. var alphaShift = 0;
  45263. switch (this.cameraRigMode) {
  45264. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  45265. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  45266. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  45267. case BABYLON.Camera.RIG_MODE_VR:
  45268. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  45269. break;
  45270. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  45271. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  45272. break;
  45273. }
  45274. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  45275. rigCam._cameraRigParams = {};
  45276. return rigCam;
  45277. };
  45278. /**
  45279. * @override
  45280. * Override Camera._updateRigCameras
  45281. */
  45282. ArcRotateCamera.prototype._updateRigCameras = function () {
  45283. var camLeft = this._rigCameras[0];
  45284. var camRight = this._rigCameras[1];
  45285. camLeft.beta = camRight.beta = this.beta;
  45286. camLeft.radius = camRight.radius = this.radius;
  45287. switch (this.cameraRigMode) {
  45288. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  45289. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  45290. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  45291. case BABYLON.Camera.RIG_MODE_VR:
  45292. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  45293. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  45294. break;
  45295. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  45296. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  45297. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  45298. break;
  45299. }
  45300. _super.prototype._updateRigCameras.call(this);
  45301. };
  45302. ArcRotateCamera.prototype.dispose = function () {
  45303. this.inputs.clear();
  45304. _super.prototype.dispose.call(this);
  45305. };
  45306. ArcRotateCamera.prototype.getClassName = function () {
  45307. return "ArcRotateCamera";
  45308. };
  45309. __decorate([
  45310. BABYLON.serialize()
  45311. ], ArcRotateCamera.prototype, "alpha", void 0);
  45312. __decorate([
  45313. BABYLON.serialize()
  45314. ], ArcRotateCamera.prototype, "beta", void 0);
  45315. __decorate([
  45316. BABYLON.serialize()
  45317. ], ArcRotateCamera.prototype, "radius", void 0);
  45318. __decorate([
  45319. BABYLON.serializeAsVector3("target")
  45320. ], ArcRotateCamera.prototype, "_target", void 0);
  45321. __decorate([
  45322. BABYLON.serialize()
  45323. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  45324. __decorate([
  45325. BABYLON.serialize()
  45326. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  45327. __decorate([
  45328. BABYLON.serialize()
  45329. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  45330. __decorate([
  45331. BABYLON.serialize()
  45332. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  45333. __decorate([
  45334. BABYLON.serialize()
  45335. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  45336. __decorate([
  45337. BABYLON.serialize()
  45338. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  45339. __decorate([
  45340. BABYLON.serialize()
  45341. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  45342. __decorate([
  45343. BABYLON.serialize()
  45344. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  45345. __decorate([
  45346. BABYLON.serialize()
  45347. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  45348. __decorate([
  45349. BABYLON.serialize()
  45350. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  45351. __decorate([
  45352. BABYLON.serialize()
  45353. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  45354. __decorate([
  45355. BABYLON.serialize()
  45356. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  45357. __decorate([
  45358. BABYLON.serialize()
  45359. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  45360. __decorate([
  45361. BABYLON.serializeAsVector3()
  45362. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  45363. __decorate([
  45364. BABYLON.serialize()
  45365. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  45366. __decorate([
  45367. BABYLON.serialize()
  45368. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  45369. __decorate([
  45370. BABYLON.serialize()
  45371. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  45372. return ArcRotateCamera;
  45373. }(BABYLON.TargetCamera));
  45374. BABYLON.ArcRotateCamera = ArcRotateCamera;
  45375. })(BABYLON || (BABYLON = {}));
  45376. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  45377. var BABYLON;
  45378. (function (BABYLON) {
  45379. /**
  45380. * The HemisphericLight simulates the ambient environment light,
  45381. * so the passed direction is the light reflection direction, not the incoming direction.
  45382. */
  45383. var HemisphericLight = /** @class */ (function (_super) {
  45384. __extends(HemisphericLight, _super);
  45385. /**
  45386. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  45387. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  45388. * The HemisphericLight can't cast shadows.
  45389. * Documentation : http://doc.babylonjs.com/tutorials/lights
  45390. * @param name The friendly name of the light
  45391. * @param direction The direction of the light reflection
  45392. * @param scene The scene the light belongs to
  45393. */
  45394. function HemisphericLight(name, direction, scene) {
  45395. var _this = _super.call(this, name, scene) || this;
  45396. /**
  45397. * The groundColor is the light in the opposite direction to the one specified during creation.
  45398. * You can think of the diffuse and specular light as coming from the centre of the object in the given direction and the groundColor light in the opposite direction.
  45399. */
  45400. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  45401. _this.direction = direction || BABYLON.Vector3.Up();
  45402. return _this;
  45403. }
  45404. HemisphericLight.prototype._buildUniformLayout = function () {
  45405. this._uniformBuffer.addUniform("vLightData", 4);
  45406. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  45407. this._uniformBuffer.addUniform("vLightSpecular", 3);
  45408. this._uniformBuffer.addUniform("vLightGround", 3);
  45409. this._uniformBuffer.addUniform("shadowsInfo", 3);
  45410. this._uniformBuffer.addUniform("depthValues", 2);
  45411. this._uniformBuffer.create();
  45412. };
  45413. /**
  45414. * Returns the string "HemisphericLight".
  45415. * @return The class name
  45416. */
  45417. HemisphericLight.prototype.getClassName = function () {
  45418. return "HemisphericLight";
  45419. };
  45420. /**
  45421. * Sets the HemisphericLight direction towards the passed target (Vector3).
  45422. * Returns the updated direction.
  45423. * @param target The target the direction should point to
  45424. * @return The computed direction
  45425. */
  45426. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  45427. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  45428. return this.direction;
  45429. };
  45430. /**
  45431. * Returns the shadow generator associated to the light.
  45432. * @returns Always null for hemispheric lights because it does not support shadows.
  45433. */
  45434. HemisphericLight.prototype.getShadowGenerator = function () {
  45435. return null;
  45436. };
  45437. /**
  45438. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  45439. * @param effect The effect to update
  45440. * @param lightIndex The index of the light in the effect to update
  45441. * @returns The hemispheric light
  45442. */
  45443. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  45444. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  45445. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  45446. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  45447. return this;
  45448. };
  45449. /**
  45450. * @ignore internal use only.
  45451. */
  45452. HemisphericLight.prototype._getWorldMatrix = function () {
  45453. if (!this._worldMatrix) {
  45454. this._worldMatrix = BABYLON.Matrix.Identity();
  45455. }
  45456. return this._worldMatrix;
  45457. };
  45458. /**
  45459. * Returns the integer 3.
  45460. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  45461. */
  45462. HemisphericLight.prototype.getTypeID = function () {
  45463. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  45464. };
  45465. __decorate([
  45466. BABYLON.serializeAsColor3()
  45467. ], HemisphericLight.prototype, "groundColor", void 0);
  45468. __decorate([
  45469. BABYLON.serializeAsVector3()
  45470. ], HemisphericLight.prototype, "direction", void 0);
  45471. return HemisphericLight;
  45472. }(BABYLON.Light));
  45473. BABYLON.HemisphericLight = HemisphericLight;
  45474. })(BABYLON || (BABYLON = {}));
  45475. //# sourceMappingURL=babylon.hemisphericLight.js.map
  45476. var BABYLON;
  45477. (function (BABYLON) {
  45478. /**
  45479. * Base implementation of @see IShadowLight
  45480. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  45481. */
  45482. var ShadowLight = /** @class */ (function (_super) {
  45483. __extends(ShadowLight, _super);
  45484. function ShadowLight() {
  45485. var _this = _super !== null && _super.apply(this, arguments) || this;
  45486. _this._needProjectionMatrixCompute = true;
  45487. return _this;
  45488. }
  45489. ShadowLight.prototype._setPosition = function (value) {
  45490. this._position = value;
  45491. };
  45492. Object.defineProperty(ShadowLight.prototype, "position", {
  45493. /**
  45494. * Sets the position the shadow will be casted from. Also use as the light position for both
  45495. * point and spot lights.
  45496. */
  45497. get: function () {
  45498. return this._position;
  45499. },
  45500. /**
  45501. * Sets the position the shadow will be casted from. Also use as the light position for both
  45502. * point and spot lights.
  45503. */
  45504. set: function (value) {
  45505. this._setPosition(value);
  45506. },
  45507. enumerable: true,
  45508. configurable: true
  45509. });
  45510. ShadowLight.prototype._setDirection = function (value) {
  45511. this._direction = value;
  45512. };
  45513. Object.defineProperty(ShadowLight.prototype, "direction", {
  45514. /**
  45515. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  45516. * Also use as the light direction on spot and directional lights.
  45517. */
  45518. get: function () {
  45519. return this._direction;
  45520. },
  45521. /**
  45522. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  45523. * Also use as the light direction on spot and directional lights.
  45524. */
  45525. set: function (value) {
  45526. this._setDirection(value);
  45527. },
  45528. enumerable: true,
  45529. configurable: true
  45530. });
  45531. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  45532. /**
  45533. * Gets the shadow projection clipping minimum z value.
  45534. */
  45535. get: function () {
  45536. return this._shadowMinZ;
  45537. },
  45538. /**
  45539. * Sets the shadow projection clipping minimum z value.
  45540. */
  45541. set: function (value) {
  45542. this._shadowMinZ = value;
  45543. this.forceProjectionMatrixCompute();
  45544. },
  45545. enumerable: true,
  45546. configurable: true
  45547. });
  45548. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  45549. /**
  45550. * Sets the shadow projection clipping maximum z value.
  45551. */
  45552. get: function () {
  45553. return this._shadowMaxZ;
  45554. },
  45555. /**
  45556. * Gets the shadow projection clipping maximum z value.
  45557. */
  45558. set: function (value) {
  45559. this._shadowMaxZ = value;
  45560. this.forceProjectionMatrixCompute();
  45561. },
  45562. enumerable: true,
  45563. configurable: true
  45564. });
  45565. /**
  45566. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  45567. * @returns true if the information has been computed, false if it does not need to (no parenting)
  45568. */
  45569. ShadowLight.prototype.computeTransformedInformation = function () {
  45570. if (this.parent && this.parent.getWorldMatrix) {
  45571. if (!this.transformedPosition) {
  45572. this.transformedPosition = BABYLON.Vector3.Zero();
  45573. }
  45574. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  45575. // In case the direction is present.
  45576. if (this.direction) {
  45577. if (!this.transformedDirection) {
  45578. this.transformedDirection = BABYLON.Vector3.Zero();
  45579. }
  45580. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  45581. }
  45582. return true;
  45583. }
  45584. return false;
  45585. };
  45586. /**
  45587. * Return the depth scale used for the shadow map.
  45588. * @returns the depth scale.
  45589. */
  45590. ShadowLight.prototype.getDepthScale = function () {
  45591. return 50.0;
  45592. };
  45593. /**
  45594. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  45595. * @param faceIndex The index of the face we are computed the direction to generate shadow
  45596. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  45597. */
  45598. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  45599. return this.transformedDirection ? this.transformedDirection : this.direction;
  45600. };
  45601. /**
  45602. * Returns the ShadowLight absolute position in the World.
  45603. * @returns the position vector in world space
  45604. */
  45605. ShadowLight.prototype.getAbsolutePosition = function () {
  45606. return this.transformedPosition ? this.transformedPosition : this.position;
  45607. };
  45608. /**
  45609. * Sets the ShadowLight direction toward the passed target.
  45610. * @param target The point tot target in local space
  45611. * @returns the updated ShadowLight direction
  45612. */
  45613. ShadowLight.prototype.setDirectionToTarget = function (target) {
  45614. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  45615. return this.direction;
  45616. };
  45617. /**
  45618. * Returns the light rotation in euler definition.
  45619. * @returns the x y z rotation in local space.
  45620. */
  45621. ShadowLight.prototype.getRotation = function () {
  45622. this.direction.normalize();
  45623. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  45624. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  45625. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  45626. };
  45627. /**
  45628. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  45629. * @returns true if a cube texture needs to be use
  45630. */
  45631. ShadowLight.prototype.needCube = function () {
  45632. return false;
  45633. };
  45634. /**
  45635. * Detects if the projection matrix requires to be recomputed this frame.
  45636. * @returns true if it requires to be recomputed otherwise, false.
  45637. */
  45638. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  45639. return this._needProjectionMatrixCompute;
  45640. };
  45641. /**
  45642. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  45643. */
  45644. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  45645. this._needProjectionMatrixCompute = true;
  45646. };
  45647. /**
  45648. * Get the world matrix of the sahdow lights.
  45649. * @ignore Internal Use Only
  45650. */
  45651. ShadowLight.prototype._getWorldMatrix = function () {
  45652. if (!this._worldMatrix) {
  45653. this._worldMatrix = BABYLON.Matrix.Identity();
  45654. }
  45655. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  45656. return this._worldMatrix;
  45657. };
  45658. /**
  45659. * Gets the minZ used for shadow according to both the scene and the light.
  45660. * @param activeCamera The camera we are returning the min for
  45661. * @returns the depth min z
  45662. */
  45663. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  45664. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  45665. };
  45666. /**
  45667. * Gets the maxZ used for shadow according to both the scene and the light.
  45668. * @param activeCamera The camera we are returning the max for
  45669. * @returns the depth max z
  45670. */
  45671. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  45672. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  45673. };
  45674. /**
  45675. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  45676. * @param matrix The materix to updated with the projection information
  45677. * @param viewMatrix The transform matrix of the light
  45678. * @param renderList The list of mesh to render in the map
  45679. * @returns The current light
  45680. */
  45681. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  45682. if (this.customProjectionMatrixBuilder) {
  45683. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  45684. }
  45685. else {
  45686. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  45687. }
  45688. return this;
  45689. };
  45690. __decorate([
  45691. BABYLON.serializeAsVector3()
  45692. ], ShadowLight.prototype, "position", null);
  45693. __decorate([
  45694. BABYLON.serializeAsVector3()
  45695. ], ShadowLight.prototype, "direction", null);
  45696. __decorate([
  45697. BABYLON.serialize()
  45698. ], ShadowLight.prototype, "shadowMinZ", null);
  45699. __decorate([
  45700. BABYLON.serialize()
  45701. ], ShadowLight.prototype, "shadowMaxZ", null);
  45702. return ShadowLight;
  45703. }(BABYLON.Light));
  45704. BABYLON.ShadowLight = ShadowLight;
  45705. })(BABYLON || (BABYLON = {}));
  45706. //# sourceMappingURL=babylon.shadowLight.js.map
  45707. var BABYLON;
  45708. (function (BABYLON) {
  45709. /**
  45710. * A point light is a light defined by an unique point in world space.
  45711. * The light is emitted in every direction from this point.
  45712. * A good example of a point light is a standard light bulb.
  45713. * Documentation: https://doc.babylonjs.com/babylon101/lights
  45714. */
  45715. var PointLight = /** @class */ (function (_super) {
  45716. __extends(PointLight, _super);
  45717. /**
  45718. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  45719. * A PointLight emits the light in every direction.
  45720. * It can cast shadows.
  45721. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  45722. * ```javascript
  45723. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  45724. * ```
  45725. * Documentation : http://doc.babylonjs.com/tutorials/lights
  45726. * @param name The light friendly name
  45727. * @param position The position of the point light in the scene
  45728. * @param scene The scene the lights belongs to
  45729. */
  45730. function PointLight(name, position, scene) {
  45731. var _this = _super.call(this, name, scene) || this;
  45732. _this._shadowAngle = Math.PI / 2;
  45733. _this.position = position;
  45734. return _this;
  45735. }
  45736. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  45737. /**
  45738. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  45739. * This specifies what angle the shadow will use to be created.
  45740. *
  45741. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  45742. */
  45743. get: function () {
  45744. return this._shadowAngle;
  45745. },
  45746. /**
  45747. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  45748. * This specifies what angle the shadow will use to be created.
  45749. *
  45750. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  45751. */
  45752. set: function (value) {
  45753. this._shadowAngle = value;
  45754. this.forceProjectionMatrixCompute();
  45755. },
  45756. enumerable: true,
  45757. configurable: true
  45758. });
  45759. Object.defineProperty(PointLight.prototype, "direction", {
  45760. /**
  45761. * Gets the direction if it has been set.
  45762. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  45763. */
  45764. get: function () {
  45765. return this._direction;
  45766. },
  45767. /**
  45768. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  45769. */
  45770. set: function (value) {
  45771. var previousNeedCube = this.needCube();
  45772. this._direction = value;
  45773. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  45774. this._shadowGenerator.recreateShadowMap();
  45775. }
  45776. },
  45777. enumerable: true,
  45778. configurable: true
  45779. });
  45780. /**
  45781. * Returns the string "PointLight"
  45782. * @returns the class name
  45783. */
  45784. PointLight.prototype.getClassName = function () {
  45785. return "PointLight";
  45786. };
  45787. /**
  45788. * Returns the integer 0.
  45789. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  45790. */
  45791. PointLight.prototype.getTypeID = function () {
  45792. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  45793. };
  45794. /**
  45795. * Specifies wether or not the shadowmap should be a cube texture.
  45796. * @returns true if the shadowmap needs to be a cube texture.
  45797. */
  45798. PointLight.prototype.needCube = function () {
  45799. return !this.direction;
  45800. };
  45801. /**
  45802. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  45803. * @param faceIndex The index of the face we are computed the direction to generate shadow
  45804. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  45805. */
  45806. PointLight.prototype.getShadowDirection = function (faceIndex) {
  45807. if (this.direction) {
  45808. return _super.prototype.getShadowDirection.call(this, faceIndex);
  45809. }
  45810. else {
  45811. switch (faceIndex) {
  45812. case 0:
  45813. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  45814. case 1:
  45815. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  45816. case 2:
  45817. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  45818. case 3:
  45819. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  45820. case 4:
  45821. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  45822. case 5:
  45823. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  45824. }
  45825. }
  45826. return BABYLON.Vector3.Zero();
  45827. };
  45828. /**
  45829. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  45830. * - fov = PI / 2
  45831. * - aspect ratio : 1.0
  45832. * - z-near and far equal to the active camera minZ and maxZ.
  45833. * Returns the PointLight.
  45834. */
  45835. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  45836. var activeCamera = this.getScene().activeCamera;
  45837. if (!activeCamera) {
  45838. return;
  45839. }
  45840. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  45841. };
  45842. PointLight.prototype._buildUniformLayout = function () {
  45843. this._uniformBuffer.addUniform("vLightData", 4);
  45844. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  45845. this._uniformBuffer.addUniform("vLightSpecular", 3);
  45846. this._uniformBuffer.addUniform("shadowsInfo", 3);
  45847. this._uniformBuffer.addUniform("depthValues", 2);
  45848. this._uniformBuffer.create();
  45849. };
  45850. /**
  45851. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  45852. * @param effect The effect to update
  45853. * @param lightIndex The index of the light in the effect to update
  45854. * @returns The point light
  45855. */
  45856. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  45857. if (this.computeTransformedInformation()) {
  45858. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  45859. return this;
  45860. }
  45861. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  45862. return this;
  45863. };
  45864. __decorate([
  45865. BABYLON.serialize()
  45866. ], PointLight.prototype, "shadowAngle", null);
  45867. return PointLight;
  45868. }(BABYLON.ShadowLight));
  45869. BABYLON.PointLight = PointLight;
  45870. })(BABYLON || (BABYLON = {}));
  45871. //# sourceMappingURL=babylon.pointLight.js.map
  45872. var BABYLON;
  45873. (function (BABYLON) {
  45874. /**
  45875. * A directional light is defined by a direction (what a surprise!).
  45876. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  45877. * An example of a directional light is when a distance planet is lit by the apparently parallel lines of light from its sun. Light in a downward direction will light the top of an object.
  45878. * Documentation: https://doc.babylonjs.com/babylon101/lights
  45879. */
  45880. var DirectionalLight = /** @class */ (function (_super) {
  45881. __extends(DirectionalLight, _super);
  45882. /**
  45883. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  45884. * The directional light is emitted from everywhere in the given direction.
  45885. * It can cast shawdows.
  45886. * Documentation : http://doc.babylonjs.com/tutorials/lights
  45887. * @param name The friendly name of the light
  45888. * @param direction The direction of the light
  45889. * @param scene The scene the light belongs to
  45890. */
  45891. function DirectionalLight(name, direction, scene) {
  45892. var _this = _super.call(this, name, scene) || this;
  45893. _this._shadowFrustumSize = 0;
  45894. _this._shadowOrthoScale = 0.5;
  45895. /**
  45896. * Automatically compute the projection matrix to best fit (including all the casters)
  45897. * on each frame.
  45898. */
  45899. _this.autoUpdateExtends = true;
  45900. // Cache
  45901. _this._orthoLeft = Number.MAX_VALUE;
  45902. _this._orthoRight = Number.MIN_VALUE;
  45903. _this._orthoTop = Number.MIN_VALUE;
  45904. _this._orthoBottom = Number.MAX_VALUE;
  45905. _this.position = direction.scale(-1.0);
  45906. _this.direction = direction;
  45907. return _this;
  45908. }
  45909. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  45910. /**
  45911. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  45912. */
  45913. get: function () {
  45914. return this._shadowFrustumSize;
  45915. },
  45916. /**
  45917. * Specifies a fix frustum size for the shadow generation.
  45918. */
  45919. set: function (value) {
  45920. this._shadowFrustumSize = value;
  45921. this.forceProjectionMatrixCompute();
  45922. },
  45923. enumerable: true,
  45924. configurable: true
  45925. });
  45926. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  45927. /**
  45928. * Gets the shadow projection scale against the optimal computed one.
  45929. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  45930. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  45931. */
  45932. get: function () {
  45933. return this._shadowOrthoScale;
  45934. },
  45935. /**
  45936. * Sets the shadow projection scale against the optimal computed one.
  45937. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  45938. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  45939. */
  45940. set: function (value) {
  45941. this._shadowOrthoScale = value;
  45942. this.forceProjectionMatrixCompute();
  45943. },
  45944. enumerable: true,
  45945. configurable: true
  45946. });
  45947. /**
  45948. * Returns the string "DirectionalLight".
  45949. * @return The class name
  45950. */
  45951. DirectionalLight.prototype.getClassName = function () {
  45952. return "DirectionalLight";
  45953. };
  45954. /**
  45955. * Returns the integer 1.
  45956. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  45957. */
  45958. DirectionalLight.prototype.getTypeID = function () {
  45959. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  45960. };
  45961. /**
  45962. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  45963. * Returns the DirectionalLight Shadow projection matrix.
  45964. */
  45965. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  45966. if (this.shadowFrustumSize > 0) {
  45967. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  45968. }
  45969. else {
  45970. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  45971. }
  45972. };
  45973. /**
  45974. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  45975. * Returns the DirectionalLight Shadow projection matrix.
  45976. */
  45977. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  45978. var activeCamera = this.getScene().activeCamera;
  45979. if (!activeCamera) {
  45980. return;
  45981. }
  45982. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  45983. };
  45984. /**
  45985. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  45986. * Returns the DirectionalLight Shadow projection matrix.
  45987. */
  45988. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  45989. var activeCamera = this.getScene().activeCamera;
  45990. if (!activeCamera) {
  45991. return;
  45992. }
  45993. // Check extends
  45994. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  45995. var tempVector3 = BABYLON.Vector3.Zero();
  45996. this._orthoLeft = Number.MAX_VALUE;
  45997. this._orthoRight = Number.MIN_VALUE;
  45998. this._orthoTop = Number.MIN_VALUE;
  45999. this._orthoBottom = Number.MAX_VALUE;
  46000. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  46001. var mesh = renderList[meshIndex];
  46002. if (!mesh) {
  46003. continue;
  46004. }
  46005. var boundingInfo = mesh.getBoundingInfo();
  46006. var boundingBox = boundingInfo.boundingBox;
  46007. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  46008. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  46009. if (tempVector3.x < this._orthoLeft)
  46010. this._orthoLeft = tempVector3.x;
  46011. if (tempVector3.y < this._orthoBottom)
  46012. this._orthoBottom = tempVector3.y;
  46013. if (tempVector3.x > this._orthoRight)
  46014. this._orthoRight = tempVector3.x;
  46015. if (tempVector3.y > this._orthoTop)
  46016. this._orthoTop = tempVector3.y;
  46017. }
  46018. }
  46019. }
  46020. var xOffset = this._orthoRight - this._orthoLeft;
  46021. var yOffset = this._orthoTop - this._orthoBottom;
  46022. BABYLON.Matrix.OrthoOffCenterLHToRef(this._orthoLeft - xOffset * this.shadowOrthoScale, this._orthoRight + xOffset * this.shadowOrthoScale, this._orthoBottom - yOffset * this.shadowOrthoScale, this._orthoTop + yOffset * this.shadowOrthoScale, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  46023. };
  46024. DirectionalLight.prototype._buildUniformLayout = function () {
  46025. this._uniformBuffer.addUniform("vLightData", 4);
  46026. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  46027. this._uniformBuffer.addUniform("vLightSpecular", 3);
  46028. this._uniformBuffer.addUniform("shadowsInfo", 3);
  46029. this._uniformBuffer.addUniform("depthValues", 2);
  46030. this._uniformBuffer.create();
  46031. };
  46032. /**
  46033. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  46034. * @param effect The effect to update
  46035. * @param lightIndex The index of the light in the effect to update
  46036. * @returns The directional light
  46037. */
  46038. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  46039. if (this.computeTransformedInformation()) {
  46040. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  46041. return this;
  46042. }
  46043. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  46044. return this;
  46045. };
  46046. /**
  46047. * Gets the minZ used for shadow according to both the scene and the light.
  46048. *
  46049. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  46050. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  46051. * @param activeCamera The camera we are returning the min for
  46052. * @returns the depth min z
  46053. */
  46054. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  46055. return 1;
  46056. };
  46057. /**
  46058. * Gets the maxZ used for shadow according to both the scene and the light.
  46059. *
  46060. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  46061. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  46062. * @param activeCamera The camera we are returning the max for
  46063. * @returns the depth max z
  46064. */
  46065. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  46066. return 1;
  46067. };
  46068. __decorate([
  46069. BABYLON.serialize()
  46070. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  46071. __decorate([
  46072. BABYLON.serialize()
  46073. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  46074. __decorate([
  46075. BABYLON.serialize()
  46076. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  46077. return DirectionalLight;
  46078. }(BABYLON.ShadowLight));
  46079. BABYLON.DirectionalLight = DirectionalLight;
  46080. })(BABYLON || (BABYLON = {}));
  46081. //# sourceMappingURL=babylon.directionalLight.js.map
  46082. var BABYLON;
  46083. (function (BABYLON) {
  46084. /**
  46085. * A spot light is defined by a position, a direction, an angle, and an exponent.
  46086. * These values define a cone of light starting from the position, emitting toward the direction.
  46087. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  46088. * and the exponent defines the speed of the decay of the light with distance (reach).
  46089. * Documentation: https://doc.babylonjs.com/babylon101/lights
  46090. */
  46091. var SpotLight = /** @class */ (function (_super) {
  46092. __extends(SpotLight, _super);
  46093. /**
  46094. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  46095. * It can cast shadows.
  46096. * Documentation : http://doc.babylonjs.com/tutorials/lights
  46097. * @param name The light friendly name
  46098. * @param position The position of the spot light in the scene
  46099. * @param direction The direction of the light in the scene
  46100. * @param angle The cone angle of the light in Radians
  46101. * @param exponent The light decay speed with the distance from the emission spot
  46102. * @param scene The scene the lights belongs to
  46103. */
  46104. function SpotLight(name, position, direction, angle, exponent, scene) {
  46105. var _this = _super.call(this, name, scene) || this;
  46106. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  46107. _this._projectionTextureLightNear = 1e-6;
  46108. _this._projectionTextureLightFar = 1000.0;
  46109. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  46110. _this._projectionTextureViewLightDirty = true;
  46111. _this._projectionTextureProjectionLightDirty = true;
  46112. _this._projectionTextureDirty = true;
  46113. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  46114. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  46115. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  46116. _this._projectionTextureScalingMatrix = BABYLON.Matrix.FromValues(0.5, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.5, 0.5, 0.5, 1.0);
  46117. _this.position = position;
  46118. _this.direction = direction;
  46119. _this.angle = angle;
  46120. _this.exponent = exponent;
  46121. return _this;
  46122. }
  46123. Object.defineProperty(SpotLight.prototype, "angle", {
  46124. /**
  46125. * Gets the cone angle of the spot light in Radians.
  46126. */
  46127. get: function () {
  46128. return this._angle;
  46129. },
  46130. /**
  46131. * Sets the cone angle of the spot light in Radians.
  46132. */
  46133. set: function (value) {
  46134. this._angle = value;
  46135. this._projectionTextureProjectionLightDirty = true;
  46136. this.forceProjectionMatrixCompute();
  46137. },
  46138. enumerable: true,
  46139. configurable: true
  46140. });
  46141. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  46142. /**
  46143. * Allows scaling the angle of the light for shadow generation only.
  46144. */
  46145. get: function () {
  46146. return this._shadowAngleScale;
  46147. },
  46148. /**
  46149. * Allows scaling the angle of the light for shadow generation only.
  46150. */
  46151. set: function (value) {
  46152. this._shadowAngleScale = value;
  46153. this.forceProjectionMatrixCompute();
  46154. },
  46155. enumerable: true,
  46156. configurable: true
  46157. });
  46158. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  46159. /**
  46160. * Allows reading the projecton texture
  46161. */
  46162. get: function () {
  46163. return this._projectionTextureMatrix;
  46164. },
  46165. enumerable: true,
  46166. configurable: true
  46167. });
  46168. ;
  46169. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  46170. /**
  46171. * Gets the near clip of the Spotlight for texture projection.
  46172. */
  46173. get: function () {
  46174. return this._projectionTextureLightNear;
  46175. },
  46176. /**
  46177. * Sets the near clip of the Spotlight for texture projection.
  46178. */
  46179. set: function (value) {
  46180. this._projectionTextureLightNear = value;
  46181. this._projectionTextureProjectionLightDirty = true;
  46182. },
  46183. enumerable: true,
  46184. configurable: true
  46185. });
  46186. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  46187. /**
  46188. * Gets the far clip of the Spotlight for texture projection.
  46189. */
  46190. get: function () {
  46191. return this._projectionTextureLightFar;
  46192. },
  46193. /**
  46194. * Sets the far clip of the Spotlight for texture projection.
  46195. */
  46196. set: function (value) {
  46197. this._projectionTextureLightFar = value;
  46198. this._projectionTextureProjectionLightDirty = true;
  46199. },
  46200. enumerable: true,
  46201. configurable: true
  46202. });
  46203. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  46204. /**
  46205. * Gets the Up vector of the Spotlight for texture projection.
  46206. */
  46207. get: function () {
  46208. return this._projectionTextureUpDirection;
  46209. },
  46210. /**
  46211. * Sets the Up vector of the Spotlight for texture projection.
  46212. */
  46213. set: function (value) {
  46214. this._projectionTextureUpDirection = value;
  46215. this._projectionTextureProjectionLightDirty = true;
  46216. },
  46217. enumerable: true,
  46218. configurable: true
  46219. });
  46220. ;
  46221. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  46222. /**
  46223. * Gets the projection texture of the light.
  46224. */
  46225. get: function () {
  46226. return this._projectionTexture;
  46227. },
  46228. /**
  46229. * Sets the projection texture of the light.
  46230. */
  46231. set: function (value) {
  46232. this._projectionTexture = value;
  46233. this._projectionTextureDirty = true;
  46234. },
  46235. enumerable: true,
  46236. configurable: true
  46237. });
  46238. /**
  46239. * Returns the string "SpotLight".
  46240. * @returns the class name
  46241. */
  46242. SpotLight.prototype.getClassName = function () {
  46243. return "SpotLight";
  46244. };
  46245. /**
  46246. * Returns the integer 2.
  46247. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  46248. */
  46249. SpotLight.prototype.getTypeID = function () {
  46250. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  46251. };
  46252. /**
  46253. * Overrides the direction setter to recompute the projection texture view light Matrix.
  46254. */
  46255. SpotLight.prototype._setDirection = function (value) {
  46256. _super.prototype._setDirection.call(this, value);
  46257. this._projectionTextureViewLightDirty = true;
  46258. };
  46259. /**
  46260. * Overrides the position setter to recompute the projection texture view light Matrix.
  46261. */
  46262. SpotLight.prototype._setPosition = function (value) {
  46263. _super.prototype._setPosition.call(this, value);
  46264. this._projectionTextureViewLightDirty = true;
  46265. };
  46266. /**
  46267. * Sets the passed matrix "matrix" as perspective projection matrix for the shadows and the passed view matrix with the fov equal to the SpotLight angle and and aspect ratio of 1.0.
  46268. * Returns the SpotLight.
  46269. */
  46270. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  46271. var activeCamera = this.getScene().activeCamera;
  46272. if (!activeCamera) {
  46273. return;
  46274. }
  46275. this._shadowAngleScale = this._shadowAngleScale || 1;
  46276. var angle = this._shadowAngleScale * this._angle;
  46277. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  46278. };
  46279. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  46280. this._projectionTextureViewLightDirty = false;
  46281. this._projectionTextureDirty = true;
  46282. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  46283. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  46284. };
  46285. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  46286. this._projectionTextureProjectionLightDirty = false;
  46287. this._projectionTextureDirty = true;
  46288. var light_far = this.projectionTextureLightFar;
  46289. var light_near = this.projectionTextureLightNear;
  46290. var P = light_far / (light_far - light_near);
  46291. var Q = -P * light_near;
  46292. var S = 1.0 / Math.tan(this._angle / 2.0);
  46293. var A = 1.0;
  46294. BABYLON.Matrix.FromValuesToRef(S / A, 0.0, 0.0, 0.0, 0.0, S, 0.0, 0.0, 0.0, 0.0, P, 1.0, 0.0, 0.0, Q, 0.0, this._projectionTextureProjectionLightMatrix);
  46295. };
  46296. /**
  46297. * Main function for light texture projection matrix computing.
  46298. */
  46299. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  46300. this._projectionTextureDirty = false;
  46301. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  46302. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  46303. };
  46304. SpotLight.prototype._buildUniformLayout = function () {
  46305. this._uniformBuffer.addUniform("vLightData", 4);
  46306. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  46307. this._uniformBuffer.addUniform("vLightSpecular", 3);
  46308. this._uniformBuffer.addUniform("vLightDirection", 3);
  46309. this._uniformBuffer.addUniform("shadowsInfo", 3);
  46310. this._uniformBuffer.addUniform("depthValues", 2);
  46311. this._uniformBuffer.create();
  46312. };
  46313. /**
  46314. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  46315. * @param effect The effect to update
  46316. * @param lightIndex The index of the light in the effect to update
  46317. * @returns The spot light
  46318. */
  46319. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  46320. var normalizeDirection;
  46321. if (this.computeTransformedInformation()) {
  46322. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  46323. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  46324. }
  46325. else {
  46326. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  46327. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  46328. }
  46329. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  46330. if (this.projectionTexture && this.projectionTexture.isReady()) {
  46331. if (this._projectionTextureViewLightDirty) {
  46332. this._computeProjectionTextureViewLightMatrix();
  46333. }
  46334. if (this._projectionTextureProjectionLightDirty) {
  46335. this._computeProjectionTextureProjectionLightMatrix();
  46336. }
  46337. if (this._projectionTextureDirty) {
  46338. this._computeProjectionTextureMatrix();
  46339. }
  46340. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  46341. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  46342. }
  46343. return this;
  46344. };
  46345. /**
  46346. * Disposes the light and the associated resources.
  46347. */
  46348. SpotLight.prototype.dispose = function () {
  46349. _super.prototype.dispose.call(this);
  46350. if (this._projectionTexture) {
  46351. this._projectionTexture.dispose();
  46352. }
  46353. };
  46354. __decorate([
  46355. BABYLON.serialize()
  46356. ], SpotLight.prototype, "angle", null);
  46357. __decorate([
  46358. BABYLON.serialize()
  46359. ], SpotLight.prototype, "shadowAngleScale", null);
  46360. __decorate([
  46361. BABYLON.serialize()
  46362. ], SpotLight.prototype, "exponent", void 0);
  46363. __decorate([
  46364. BABYLON.serialize()
  46365. ], SpotLight.prototype, "projectionTextureLightNear", null);
  46366. __decorate([
  46367. BABYLON.serialize()
  46368. ], SpotLight.prototype, "projectionTextureLightFar", null);
  46369. __decorate([
  46370. BABYLON.serialize()
  46371. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  46372. __decorate([
  46373. BABYLON.serializeAsTexture("projectedLightTexture")
  46374. ], SpotLight.prototype, "_projectionTexture", void 0);
  46375. return SpotLight;
  46376. }(BABYLON.ShadowLight));
  46377. BABYLON.SpotLight = SpotLight;
  46378. })(BABYLON || (BABYLON = {}));
  46379. //# sourceMappingURL=babylon.spotLight.js.map
  46380. var BABYLON;
  46381. (function (BABYLON) {
  46382. /**
  46383. * Class used to override all child animations of a given target
  46384. */
  46385. var AnimationPropertiesOverride = /** @class */ (function () {
  46386. function AnimationPropertiesOverride() {
  46387. /**
  46388. * Gets or sets a value indicating if animation blending must be used
  46389. */
  46390. this.enableBlending = false;
  46391. /**
  46392. * Gets or sets the blending speed to use when enableBlending is true
  46393. */
  46394. this.blendingSpeed = 0.01;
  46395. /**
  46396. * Gets or sets the default loop mode to use
  46397. */
  46398. this.loopMode = BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE;
  46399. }
  46400. return AnimationPropertiesOverride;
  46401. }());
  46402. BABYLON.AnimationPropertiesOverride = AnimationPropertiesOverride;
  46403. })(BABYLON || (BABYLON = {}));
  46404. //# sourceMappingURL=babylon.animationPropertiesOverride.js.map
  46405. var BABYLON;
  46406. (function (BABYLON) {
  46407. var AnimationRange = /** @class */ (function () {
  46408. function AnimationRange(name, from, to) {
  46409. this.name = name;
  46410. this.from = from;
  46411. this.to = to;
  46412. }
  46413. AnimationRange.prototype.clone = function () {
  46414. return new AnimationRange(this.name, this.from, this.to);
  46415. };
  46416. return AnimationRange;
  46417. }());
  46418. BABYLON.AnimationRange = AnimationRange;
  46419. /**
  46420. * Composed of a frame, and an action function
  46421. */
  46422. var AnimationEvent = /** @class */ (function () {
  46423. function AnimationEvent(frame, action, onlyOnce) {
  46424. this.frame = frame;
  46425. this.action = action;
  46426. this.onlyOnce = onlyOnce;
  46427. this.isDone = false;
  46428. }
  46429. return AnimationEvent;
  46430. }());
  46431. BABYLON.AnimationEvent = AnimationEvent;
  46432. var PathCursor = /** @class */ (function () {
  46433. function PathCursor(path) {
  46434. this.path = path;
  46435. this._onchange = new Array();
  46436. this.value = 0;
  46437. this.animations = new Array();
  46438. }
  46439. PathCursor.prototype.getPoint = function () {
  46440. var point = this.path.getPointAtLengthPosition(this.value);
  46441. return new BABYLON.Vector3(point.x, 0, point.y);
  46442. };
  46443. PathCursor.prototype.moveAhead = function (step) {
  46444. if (step === void 0) { step = 0.002; }
  46445. this.move(step);
  46446. return this;
  46447. };
  46448. PathCursor.prototype.moveBack = function (step) {
  46449. if (step === void 0) { step = 0.002; }
  46450. this.move(-step);
  46451. return this;
  46452. };
  46453. PathCursor.prototype.move = function (step) {
  46454. if (Math.abs(step) > 1) {
  46455. throw "step size should be less than 1.";
  46456. }
  46457. this.value += step;
  46458. this.ensureLimits();
  46459. this.raiseOnChange();
  46460. return this;
  46461. };
  46462. PathCursor.prototype.ensureLimits = function () {
  46463. while (this.value > 1) {
  46464. this.value -= 1;
  46465. }
  46466. while (this.value < 0) {
  46467. this.value += 1;
  46468. }
  46469. return this;
  46470. };
  46471. // used by animation engine
  46472. PathCursor.prototype.raiseOnChange = function () {
  46473. var _this = this;
  46474. this._onchange.forEach(function (f) { return f(_this); });
  46475. return this;
  46476. };
  46477. PathCursor.prototype.onchange = function (f) {
  46478. this._onchange.push(f);
  46479. return this;
  46480. };
  46481. return PathCursor;
  46482. }());
  46483. BABYLON.PathCursor = PathCursor;
  46484. var AnimationKeyInterpolation;
  46485. (function (AnimationKeyInterpolation) {
  46486. /**
  46487. * Do not interpolate between keys and use the start key value only. Tangents are ignored.
  46488. */
  46489. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  46490. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  46491. var Animation = /** @class */ (function () {
  46492. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  46493. this.name = name;
  46494. this.targetProperty = targetProperty;
  46495. this.framePerSecond = framePerSecond;
  46496. this.dataType = dataType;
  46497. this.loopMode = loopMode;
  46498. this.enableBlending = enableBlending;
  46499. this._runtimeAnimations = new Array();
  46500. // The set of event that will be linked to this animation
  46501. this._events = new Array();
  46502. this.blendingSpeed = 0.01;
  46503. this._ranges = {};
  46504. this.targetPropertyPath = targetProperty.split(".");
  46505. this.dataType = dataType;
  46506. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  46507. }
  46508. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  46509. var dataType = undefined;
  46510. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  46511. dataType = Animation.ANIMATIONTYPE_FLOAT;
  46512. }
  46513. else if (from instanceof BABYLON.Quaternion) {
  46514. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  46515. }
  46516. else if (from instanceof BABYLON.Vector3) {
  46517. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  46518. }
  46519. else if (from instanceof BABYLON.Vector2) {
  46520. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  46521. }
  46522. else if (from instanceof BABYLON.Color3) {
  46523. dataType = Animation.ANIMATIONTYPE_COLOR3;
  46524. }
  46525. else if (from instanceof BABYLON.Size) {
  46526. dataType = Animation.ANIMATIONTYPE_SIZE;
  46527. }
  46528. if (dataType == undefined) {
  46529. return null;
  46530. }
  46531. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  46532. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  46533. animation.setKeys(keys);
  46534. if (easingFunction !== undefined) {
  46535. animation.setEasingFunction(easingFunction);
  46536. }
  46537. return animation;
  46538. };
  46539. /**
  46540. * Sets up an animation.
  46541. * @param property the property to animate
  46542. * @param animationType the animation type to apply
  46543. * @param easingFunction the easing function used in the animation
  46544. * @returns The created animation
  46545. */
  46546. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  46547. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  46548. animation.setEasingFunction(easingFunction);
  46549. return animation;
  46550. };
  46551. /**
  46552. * Create and start an animation on a node
  46553. * @param {string} name defines the name of the global animation that will be run on all nodes
  46554. * @param {BABYLON.Node} node defines the root node where the animation will take place
  46555. * @param {string} targetProperty defines property to animate
  46556. * @param {number} framePerSecond defines the number of frame per second yo use
  46557. * @param {number} totalFrame defines the number of frames in total
  46558. * @param {any} from defines the initial value
  46559. * @param {any} to defines the final value
  46560. * @param {number} loopMode defines which loop mode you want to use (off by default)
  46561. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  46562. * @param onAnimationEnd defines the callback to call when animation end
  46563. * @returns the animatable created for this animation
  46564. */
  46565. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  46566. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  46567. if (!animation) {
  46568. return null;
  46569. }
  46570. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  46571. };
  46572. /**
  46573. * Create and start an animation on a node and its descendants
  46574. * @param {string} name defines the name of the global animation that will be run on all nodes
  46575. * @param {BABYLON.Node} node defines the root node where the animation will take place
  46576. * @param {boolean} directDescendantsOnly if true only direct descendants will be used, if false direct and also indirect (children of children, an so on in a recursive manner) descendants will be used.
  46577. * @param {string} targetProperty defines property to animate
  46578. * @param {number} framePerSecond defines the number of frame per second yo use
  46579. * @param {number} totalFrame defines the number of frames in total
  46580. * @param {any} from defines the initial value
  46581. * @param {any} to defines the final value
  46582. * @param {number} loopMode defines which loop mode you want to use (off by default)
  46583. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  46584. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  46585. * @returns the list of animatables created for all nodes
  46586. * @example https://www.babylonjs-playground.com/#MH0VLI
  46587. */
  46588. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  46589. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  46590. if (!animation) {
  46591. return null;
  46592. }
  46593. var scene = node.getScene();
  46594. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  46595. };
  46596. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  46597. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  46598. if (!animation) {
  46599. return null;
  46600. }
  46601. node.animations.push(animation);
  46602. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  46603. };
  46604. /**
  46605. * Transition property of the Camera to the target Value.
  46606. * @param property The property to transition
  46607. * @param targetValue The target Value of the property
  46608. * @param host The object where the property to animate belongs
  46609. * @param scene Scene used to run the animation
  46610. * @param frameRate Framerate (in frame/s) to use
  46611. * @param transition The transition type we want to use
  46612. * @param duration The duration of the animation, in milliseconds
  46613. * @param onAnimationEnd Call back trigger at the end of the animation.
  46614. */
  46615. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  46616. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  46617. if (duration <= 0) {
  46618. host[property] = targetValue;
  46619. if (onAnimationEnd) {
  46620. onAnimationEnd();
  46621. }
  46622. return null;
  46623. }
  46624. var endFrame = frameRate * (duration / 1000);
  46625. transition.setKeys([{
  46626. frame: 0,
  46627. value: host[property].clone ? host[property].clone() : host[property]
  46628. },
  46629. {
  46630. frame: endFrame,
  46631. value: targetValue
  46632. }]);
  46633. if (!host.animations) {
  46634. host.animations = [];
  46635. }
  46636. host.animations.push(transition);
  46637. var animation = scene.beginAnimation(host, 0, endFrame, false);
  46638. animation.onAnimationEnd = onAnimationEnd;
  46639. return animation;
  46640. };
  46641. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  46642. /**
  46643. * Return the array of runtime animations currently using this animation
  46644. */
  46645. get: function () {
  46646. return this._runtimeAnimations;
  46647. },
  46648. enumerable: true,
  46649. configurable: true
  46650. });
  46651. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  46652. get: function () {
  46653. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  46654. var runtimeAnimation = _a[_i];
  46655. if (!runtimeAnimation.isStopped) {
  46656. return true;
  46657. }
  46658. }
  46659. return false;
  46660. },
  46661. enumerable: true,
  46662. configurable: true
  46663. });
  46664. // Methods
  46665. /**
  46666. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  46667. */
  46668. Animation.prototype.toString = function (fullDetails) {
  46669. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  46670. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  46671. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  46672. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  46673. if (fullDetails) {
  46674. ret += ", Ranges: {";
  46675. var first = true;
  46676. for (var name in this._ranges) {
  46677. if (first) {
  46678. ret += ", ";
  46679. first = false;
  46680. }
  46681. ret += name;
  46682. }
  46683. ret += "}";
  46684. }
  46685. return ret;
  46686. };
  46687. /**
  46688. * Add an event to this animation.
  46689. */
  46690. Animation.prototype.addEvent = function (event) {
  46691. this._events.push(event);
  46692. };
  46693. /**
  46694. * Remove all events found at the given frame
  46695. * @param frame
  46696. */
  46697. Animation.prototype.removeEvents = function (frame) {
  46698. for (var index = 0; index < this._events.length; index++) {
  46699. if (this._events[index].frame === frame) {
  46700. this._events.splice(index, 1);
  46701. index--;
  46702. }
  46703. }
  46704. };
  46705. Animation.prototype.getEvents = function () {
  46706. return this._events;
  46707. };
  46708. Animation.prototype.createRange = function (name, from, to) {
  46709. // check name not already in use; could happen for bones after serialized
  46710. if (!this._ranges[name]) {
  46711. this._ranges[name] = new AnimationRange(name, from, to);
  46712. }
  46713. };
  46714. Animation.prototype.deleteRange = function (name, deleteFrames) {
  46715. if (deleteFrames === void 0) { deleteFrames = true; }
  46716. var range = this._ranges[name];
  46717. if (!range) {
  46718. return;
  46719. }
  46720. if (deleteFrames) {
  46721. var from = range.from;
  46722. var to = range.to;
  46723. // this loop MUST go high to low for multiple splices to work
  46724. for (var key = this._keys.length - 1; key >= 0; key--) {
  46725. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  46726. this._keys.splice(key, 1);
  46727. }
  46728. }
  46729. }
  46730. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  46731. };
  46732. Animation.prototype.getRange = function (name) {
  46733. return this._ranges[name];
  46734. };
  46735. Animation.prototype.getKeys = function () {
  46736. return this._keys;
  46737. };
  46738. Animation.prototype.getHighestFrame = function () {
  46739. var ret = 0;
  46740. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  46741. if (ret < this._keys[key].frame) {
  46742. ret = this._keys[key].frame;
  46743. }
  46744. }
  46745. return ret;
  46746. };
  46747. Animation.prototype.getEasingFunction = function () {
  46748. return this._easingFunction;
  46749. };
  46750. Animation.prototype.setEasingFunction = function (easingFunction) {
  46751. this._easingFunction = easingFunction;
  46752. };
  46753. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  46754. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  46755. };
  46756. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  46757. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  46758. };
  46759. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  46760. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  46761. };
  46762. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  46763. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  46764. };
  46765. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  46766. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  46767. };
  46768. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  46769. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  46770. };
  46771. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  46772. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  46773. };
  46774. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  46775. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  46776. };
  46777. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  46778. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  46779. };
  46780. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  46781. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  46782. };
  46783. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  46784. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  46785. };
  46786. Animation.prototype.clone = function () {
  46787. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  46788. clone.enableBlending = this.enableBlending;
  46789. clone.blendingSpeed = this.blendingSpeed;
  46790. if (this._keys) {
  46791. clone.setKeys(this._keys);
  46792. }
  46793. if (this._ranges) {
  46794. clone._ranges = {};
  46795. for (var name in this._ranges) {
  46796. var range = this._ranges[name];
  46797. if (!range) {
  46798. continue;
  46799. }
  46800. clone._ranges[name] = range.clone();
  46801. }
  46802. }
  46803. return clone;
  46804. };
  46805. Animation.prototype.setKeys = function (values) {
  46806. this._keys = values.slice(0);
  46807. };
  46808. Animation.prototype.serialize = function () {
  46809. var serializationObject = {};
  46810. serializationObject.name = this.name;
  46811. serializationObject.property = this.targetProperty;
  46812. serializationObject.framePerSecond = this.framePerSecond;
  46813. serializationObject.dataType = this.dataType;
  46814. serializationObject.loopBehavior = this.loopMode;
  46815. serializationObject.enableBlending = this.enableBlending;
  46816. serializationObject.blendingSpeed = this.blendingSpeed;
  46817. var dataType = this.dataType;
  46818. serializationObject.keys = [];
  46819. var keys = this.getKeys();
  46820. for (var index = 0; index < keys.length; index++) {
  46821. var animationKey = keys[index];
  46822. var key = {};
  46823. key.frame = animationKey.frame;
  46824. switch (dataType) {
  46825. case Animation.ANIMATIONTYPE_FLOAT:
  46826. key.values = [animationKey.value];
  46827. break;
  46828. case Animation.ANIMATIONTYPE_QUATERNION:
  46829. case Animation.ANIMATIONTYPE_MATRIX:
  46830. case Animation.ANIMATIONTYPE_VECTOR3:
  46831. case Animation.ANIMATIONTYPE_COLOR3:
  46832. key.values = animationKey.value.asArray();
  46833. break;
  46834. }
  46835. serializationObject.keys.push(key);
  46836. }
  46837. serializationObject.ranges = [];
  46838. for (var name in this._ranges) {
  46839. var source = this._ranges[name];
  46840. if (!source) {
  46841. continue;
  46842. }
  46843. var range = {};
  46844. range.name = name;
  46845. range.from = source.from;
  46846. range.to = source.to;
  46847. serializationObject.ranges.push(range);
  46848. }
  46849. return serializationObject;
  46850. };
  46851. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  46852. get: function () {
  46853. return Animation._ANIMATIONTYPE_FLOAT;
  46854. },
  46855. enumerable: true,
  46856. configurable: true
  46857. });
  46858. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  46859. get: function () {
  46860. return Animation._ANIMATIONTYPE_VECTOR3;
  46861. },
  46862. enumerable: true,
  46863. configurable: true
  46864. });
  46865. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  46866. get: function () {
  46867. return Animation._ANIMATIONTYPE_VECTOR2;
  46868. },
  46869. enumerable: true,
  46870. configurable: true
  46871. });
  46872. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  46873. get: function () {
  46874. return Animation._ANIMATIONTYPE_SIZE;
  46875. },
  46876. enumerable: true,
  46877. configurable: true
  46878. });
  46879. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  46880. get: function () {
  46881. return Animation._ANIMATIONTYPE_QUATERNION;
  46882. },
  46883. enumerable: true,
  46884. configurable: true
  46885. });
  46886. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  46887. get: function () {
  46888. return Animation._ANIMATIONTYPE_MATRIX;
  46889. },
  46890. enumerable: true,
  46891. configurable: true
  46892. });
  46893. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  46894. get: function () {
  46895. return Animation._ANIMATIONTYPE_COLOR3;
  46896. },
  46897. enumerable: true,
  46898. configurable: true
  46899. });
  46900. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  46901. get: function () {
  46902. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  46903. },
  46904. enumerable: true,
  46905. configurable: true
  46906. });
  46907. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  46908. get: function () {
  46909. return Animation._ANIMATIONLOOPMODE_CYCLE;
  46910. },
  46911. enumerable: true,
  46912. configurable: true
  46913. });
  46914. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  46915. get: function () {
  46916. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  46917. },
  46918. enumerable: true,
  46919. configurable: true
  46920. });
  46921. Animation.Parse = function (parsedAnimation) {
  46922. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  46923. var dataType = parsedAnimation.dataType;
  46924. var keys = [];
  46925. var data;
  46926. var index;
  46927. if (parsedAnimation.enableBlending) {
  46928. animation.enableBlending = parsedAnimation.enableBlending;
  46929. }
  46930. if (parsedAnimation.blendingSpeed) {
  46931. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  46932. }
  46933. for (index = 0; index < parsedAnimation.keys.length; index++) {
  46934. var key = parsedAnimation.keys[index];
  46935. var inTangent;
  46936. var outTangent;
  46937. switch (dataType) {
  46938. case Animation.ANIMATIONTYPE_FLOAT:
  46939. data = key.values[0];
  46940. if (key.values.length >= 1) {
  46941. inTangent = key.values[1];
  46942. }
  46943. if (key.values.length >= 2) {
  46944. outTangent = key.values[2];
  46945. }
  46946. break;
  46947. case Animation.ANIMATIONTYPE_QUATERNION:
  46948. data = BABYLON.Quaternion.FromArray(key.values);
  46949. if (key.values.length >= 8) {
  46950. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  46951. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  46952. inTangent = _inTangent;
  46953. }
  46954. }
  46955. if (key.values.length >= 12) {
  46956. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  46957. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  46958. outTangent = _outTangent;
  46959. }
  46960. }
  46961. break;
  46962. case Animation.ANIMATIONTYPE_MATRIX:
  46963. data = BABYLON.Matrix.FromArray(key.values);
  46964. break;
  46965. case Animation.ANIMATIONTYPE_COLOR3:
  46966. data = BABYLON.Color3.FromArray(key.values);
  46967. break;
  46968. case Animation.ANIMATIONTYPE_VECTOR3:
  46969. default:
  46970. data = BABYLON.Vector3.FromArray(key.values);
  46971. break;
  46972. }
  46973. var keyData = {};
  46974. keyData.frame = key.frame;
  46975. keyData.value = data;
  46976. if (inTangent != undefined) {
  46977. keyData.inTangent = inTangent;
  46978. }
  46979. if (outTangent != undefined) {
  46980. keyData.outTangent = outTangent;
  46981. }
  46982. keys.push(keyData);
  46983. }
  46984. animation.setKeys(keys);
  46985. if (parsedAnimation.ranges) {
  46986. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  46987. data = parsedAnimation.ranges[index];
  46988. animation.createRange(data.name, data.from, data.to);
  46989. }
  46990. }
  46991. return animation;
  46992. };
  46993. Animation.AppendSerializedAnimations = function (source, destination) {
  46994. if (source.animations) {
  46995. destination.animations = [];
  46996. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  46997. var animation = source.animations[animationIndex];
  46998. destination.animations.push(animation.serialize());
  46999. }
  47000. }
  47001. };
  47002. Animation.AllowMatricesInterpolation = false;
  47003. // Statics
  47004. Animation._ANIMATIONTYPE_FLOAT = 0;
  47005. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  47006. Animation._ANIMATIONTYPE_QUATERNION = 2;
  47007. Animation._ANIMATIONTYPE_MATRIX = 3;
  47008. Animation._ANIMATIONTYPE_COLOR3 = 4;
  47009. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  47010. Animation._ANIMATIONTYPE_SIZE = 6;
  47011. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  47012. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  47013. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  47014. return Animation;
  47015. }());
  47016. BABYLON.Animation = Animation;
  47017. })(BABYLON || (BABYLON = {}));
  47018. //# sourceMappingURL=babylon.animation.js.map
  47019. var BABYLON;
  47020. (function (BABYLON) {
  47021. /**
  47022. * This class defines the direct association between an animation and a target
  47023. */
  47024. var TargetedAnimation = /** @class */ (function () {
  47025. function TargetedAnimation() {
  47026. }
  47027. return TargetedAnimation;
  47028. }());
  47029. BABYLON.TargetedAnimation = TargetedAnimation;
  47030. /**
  47031. * Use this class to create coordinated animations on multiple targets
  47032. */
  47033. var AnimationGroup = /** @class */ (function () {
  47034. function AnimationGroup(name, scene) {
  47035. if (scene === void 0) { scene = null; }
  47036. this.name = name;
  47037. this._targetedAnimations = new Array();
  47038. this._animatables = new Array();
  47039. this._from = Number.MAX_VALUE;
  47040. this._to = -Number.MAX_VALUE;
  47041. this._speedRatio = 1;
  47042. this.onAnimationEndObservable = new BABYLON.Observable();
  47043. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  47044. this._scene.animationGroups.push(this);
  47045. }
  47046. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  47047. /**
  47048. * Define if the animations are started
  47049. */
  47050. get: function () {
  47051. return this._isStarted;
  47052. },
  47053. enumerable: true,
  47054. configurable: true
  47055. });
  47056. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  47057. /**
  47058. * Gets or sets the speed ratio to use for all animations
  47059. */
  47060. get: function () {
  47061. return this._speedRatio;
  47062. },
  47063. /**
  47064. * Gets or sets the speed ratio to use for all animations
  47065. */
  47066. set: function (value) {
  47067. if (this._speedRatio === value) {
  47068. return;
  47069. }
  47070. this._speedRatio = value;
  47071. for (var index = 0; index < this._animatables.length; index++) {
  47072. var animatable = this._animatables[index];
  47073. animatable.speedRatio = this._speedRatio;
  47074. }
  47075. },
  47076. enumerable: true,
  47077. configurable: true
  47078. });
  47079. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  47080. /**
  47081. * Gets the targeted animations for this animation group
  47082. */
  47083. get: function () {
  47084. return this._targetedAnimations;
  47085. },
  47086. enumerable: true,
  47087. configurable: true
  47088. });
  47089. Object.defineProperty(AnimationGroup.prototype, "animatables", {
  47090. /**
  47091. * returning the list of animatables controlled by this animation group.
  47092. */
  47093. get: function () {
  47094. return this._animatables;
  47095. },
  47096. enumerable: true,
  47097. configurable: true
  47098. });
  47099. /**
  47100. * Add an animation (with its target) in the group
  47101. * @param animation defines the animation we want to add
  47102. * @param target defines the target of the animation
  47103. * @returns the {BABYLON.TargetedAnimation} object
  47104. */
  47105. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  47106. var targetedAnimation = {
  47107. animation: animation,
  47108. target: target
  47109. };
  47110. var keys = animation.getKeys();
  47111. if (this._from > keys[0].frame) {
  47112. this._from = keys[0].frame;
  47113. }
  47114. if (this._to < keys[keys.length - 1].frame) {
  47115. this._to = keys[keys.length - 1].frame;
  47116. }
  47117. this._targetedAnimations.push(targetedAnimation);
  47118. return targetedAnimation;
  47119. };
  47120. /**
  47121. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  47122. * It can add constant keys at begin or end
  47123. * @param beginFrame defines the new begin frame for all animations. It can't be bigger than the smallest begin frame of all animations
  47124. * @param endFrame defines the new end frame for all animations. It can't be smaller than the largest end frame of all animations
  47125. */
  47126. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  47127. if (beginFrame === void 0) { beginFrame = -Number.MAX_VALUE; }
  47128. if (endFrame === void 0) { endFrame = Number.MAX_VALUE; }
  47129. beginFrame = Math.max(beginFrame, this._from);
  47130. endFrame = Math.min(endFrame, this._to);
  47131. for (var index = 0; index < this._targetedAnimations.length; index++) {
  47132. var targetedAnimation = this._targetedAnimations[index];
  47133. var keys = targetedAnimation.animation.getKeys();
  47134. var startKey = keys[0];
  47135. var endKey = keys[keys.length - 1];
  47136. if (startKey.frame > beginFrame) {
  47137. var newKey = {
  47138. frame: beginFrame,
  47139. value: startKey.value,
  47140. inTangent: startKey.inTangent,
  47141. outTangent: startKey.outTangent,
  47142. interpolation: startKey.interpolation
  47143. };
  47144. keys.splice(0, 0, newKey);
  47145. }
  47146. if (endKey.frame < endFrame) {
  47147. var newKey = {
  47148. frame: endFrame,
  47149. value: endKey.value,
  47150. inTangent: endKey.outTangent,
  47151. outTangent: endKey.outTangent,
  47152. interpolation: endKey.interpolation
  47153. };
  47154. keys.push(newKey);
  47155. }
  47156. }
  47157. return this;
  47158. };
  47159. /**
  47160. * Start all animations on given targets
  47161. * @param loop defines if animations must loop
  47162. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  47163. */
  47164. AnimationGroup.prototype.start = function (loop, speedRatio) {
  47165. var _this = this;
  47166. if (loop === void 0) { loop = false; }
  47167. if (speedRatio === void 0) { speedRatio = 1; }
  47168. if (this._isStarted || this._targetedAnimations.length === 0) {
  47169. return this;
  47170. }
  47171. var _loop_1 = function () {
  47172. var targetedAnimation = this_1._targetedAnimations[index];
  47173. this_1._animatables.push(this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], this_1._from, this_1._to, loop, speedRatio, function () {
  47174. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  47175. }));
  47176. };
  47177. var this_1 = this;
  47178. for (var index = 0; index < this._targetedAnimations.length; index++) {
  47179. _loop_1();
  47180. }
  47181. this._speedRatio = speedRatio;
  47182. this._isStarted = true;
  47183. return this;
  47184. };
  47185. /**
  47186. * Pause all animations
  47187. */
  47188. AnimationGroup.prototype.pause = function () {
  47189. if (!this._isStarted) {
  47190. return this;
  47191. }
  47192. for (var index = 0; index < this._animatables.length; index++) {
  47193. var animatable = this._animatables[index];
  47194. animatable.pause();
  47195. }
  47196. return this;
  47197. };
  47198. /**
  47199. * Play all animations to initial state
  47200. * This function will start() the animations if they were not started or will restart() them if they were paused
  47201. * @param loop defines if animations must loop
  47202. */
  47203. AnimationGroup.prototype.play = function (loop) {
  47204. if (this.isStarted) {
  47205. if (loop !== undefined) {
  47206. for (var index = 0; index < this._animatables.length; index++) {
  47207. var animatable = this._animatables[index];
  47208. animatable.loopAnimation = loop;
  47209. }
  47210. }
  47211. this.restart();
  47212. }
  47213. else {
  47214. this.start(loop, this._speedRatio);
  47215. }
  47216. return this;
  47217. };
  47218. /**
  47219. * Reset all animations to initial state
  47220. */
  47221. AnimationGroup.prototype.reset = function () {
  47222. if (!this._isStarted) {
  47223. return this;
  47224. }
  47225. for (var index = 0; index < this._animatables.length; index++) {
  47226. var animatable = this._animatables[index];
  47227. animatable.reset();
  47228. }
  47229. return this;
  47230. };
  47231. /**
  47232. * Restart animations from key 0
  47233. */
  47234. AnimationGroup.prototype.restart = function () {
  47235. if (!this._isStarted) {
  47236. return this;
  47237. }
  47238. for (var index = 0; index < this._animatables.length; index++) {
  47239. var animatable = this._animatables[index];
  47240. animatable.restart();
  47241. }
  47242. return this;
  47243. };
  47244. /**
  47245. * Stop all animations
  47246. */
  47247. AnimationGroup.prototype.stop = function () {
  47248. if (!this._isStarted) {
  47249. return this;
  47250. }
  47251. for (var index = 0; index < this._animatables.length; index++) {
  47252. var animatable = this._animatables[index];
  47253. animatable.stop();
  47254. }
  47255. this._isStarted = false;
  47256. return this;
  47257. };
  47258. /**
  47259. * Goes to a specific frame in this animation group
  47260. *
  47261. * @param frame the frame number to go to
  47262. * @return the animationGroup
  47263. */
  47264. AnimationGroup.prototype.goToFrame = function (frame) {
  47265. if (!this._isStarted) {
  47266. return this;
  47267. }
  47268. for (var index = 0; index < this._animatables.length; index++) {
  47269. var animatable = this._animatables[index];
  47270. animatable.goToFrame(frame);
  47271. }
  47272. return this;
  47273. };
  47274. /**
  47275. * Dispose all associated resources
  47276. */
  47277. AnimationGroup.prototype.dispose = function () {
  47278. this._targetedAnimations = [];
  47279. this._animatables = [];
  47280. var index = this._scene.animationGroups.indexOf(this);
  47281. if (index > -1) {
  47282. this._scene.animationGroups.splice(index, 1);
  47283. }
  47284. };
  47285. return AnimationGroup;
  47286. }());
  47287. BABYLON.AnimationGroup = AnimationGroup;
  47288. })(BABYLON || (BABYLON = {}));
  47289. //# sourceMappingURL=babylon.animationGroup.js.map
  47290. var BABYLON;
  47291. (function (BABYLON) {
  47292. var RuntimeAnimation = /** @class */ (function () {
  47293. function RuntimeAnimation(target, animation) {
  47294. this._offsetsCache = {};
  47295. this._highLimitsCache = {};
  47296. this._stopped = false;
  47297. this._blendingFactor = 0;
  47298. this._ratioOffset = 0;
  47299. this._animation = animation;
  47300. this._target = target;
  47301. animation._runtimeAnimations.push(this);
  47302. }
  47303. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  47304. get: function () {
  47305. return this._animation;
  47306. },
  47307. enumerable: true,
  47308. configurable: true
  47309. });
  47310. RuntimeAnimation.prototype.reset = function () {
  47311. this._offsetsCache = {};
  47312. this._highLimitsCache = {};
  47313. this.currentFrame = 0;
  47314. this._blendingFactor = 0;
  47315. this._originalBlendValue = null;
  47316. };
  47317. RuntimeAnimation.prototype.isStopped = function () {
  47318. return this._stopped;
  47319. };
  47320. RuntimeAnimation.prototype.dispose = function () {
  47321. var index = this._animation.runtimeAnimations.indexOf(this);
  47322. if (index > -1) {
  47323. this._animation.runtimeAnimations.splice(index, 1);
  47324. }
  47325. };
  47326. RuntimeAnimation.prototype._getKeyValue = function (value) {
  47327. if (typeof value === "function") {
  47328. return value();
  47329. }
  47330. return value;
  47331. };
  47332. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  47333. if (loopMode === BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  47334. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  47335. }
  47336. this.currentFrame = currentFrame;
  47337. var keys = this._animation.getKeys();
  47338. // Try to get a hash to find the right key
  47339. var startKeyIndex = Math.max(0, Math.min(keys.length - 1, Math.floor(keys.length * (currentFrame - keys[0].frame) / (keys[keys.length - 1].frame - keys[0].frame)) - 1));
  47340. if (keys[startKeyIndex].frame >= currentFrame) {
  47341. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  47342. startKeyIndex--;
  47343. }
  47344. }
  47345. for (var key = startKeyIndex; key < keys.length; key++) {
  47346. var endKey = keys[key + 1];
  47347. if (endKey.frame >= currentFrame) {
  47348. var startKey = keys[key];
  47349. var startValue = this._getKeyValue(startKey.value);
  47350. if (startKey.interpolation === BABYLON.AnimationKeyInterpolation.STEP) {
  47351. return startValue;
  47352. }
  47353. var endValue = this._getKeyValue(endKey.value);
  47354. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  47355. var frameDelta = endKey.frame - startKey.frame;
  47356. // gradient : percent of currentFrame between the frame inf and the frame sup
  47357. var gradient = (currentFrame - startKey.frame) / frameDelta;
  47358. // check for easingFunction and correction of gradient
  47359. var easingFunction = this._animation.getEasingFunction();
  47360. if (easingFunction != null) {
  47361. gradient = easingFunction.ease(gradient);
  47362. }
  47363. switch (this._animation.dataType) {
  47364. // Float
  47365. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  47366. var floatValue = useTangent ? this._animation.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this._animation.floatInterpolateFunction(startValue, endValue, gradient);
  47367. switch (loopMode) {
  47368. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47369. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47370. return floatValue;
  47371. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47372. return offsetValue * repeatCount + floatValue;
  47373. }
  47374. break;
  47375. // Quaternion
  47376. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  47377. var quatValue = useTangent ? this._animation.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.quaternionInterpolateFunction(startValue, endValue, gradient);
  47378. switch (loopMode) {
  47379. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47380. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47381. return quatValue;
  47382. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47383. return quatValue.add(offsetValue.scale(repeatCount));
  47384. }
  47385. return quatValue;
  47386. // Vector3
  47387. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  47388. var vec3Value = useTangent ? this._animation.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector3InterpolateFunction(startValue, endValue, gradient);
  47389. switch (loopMode) {
  47390. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47391. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47392. return vec3Value;
  47393. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47394. return vec3Value.add(offsetValue.scale(repeatCount));
  47395. }
  47396. // Vector2
  47397. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  47398. var vec2Value = useTangent ? this._animation.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector2InterpolateFunction(startValue, endValue, gradient);
  47399. switch (loopMode) {
  47400. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47401. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47402. return vec2Value;
  47403. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47404. return vec2Value.add(offsetValue.scale(repeatCount));
  47405. }
  47406. // Size
  47407. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  47408. switch (loopMode) {
  47409. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47410. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47411. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient);
  47412. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47413. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  47414. }
  47415. // Color3
  47416. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  47417. switch (loopMode) {
  47418. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47419. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47420. return this._animation.color3InterpolateFunction(startValue, endValue, gradient);
  47421. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47422. return this._animation.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  47423. }
  47424. // Matrix
  47425. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  47426. switch (loopMode) {
  47427. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47428. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47429. if (BABYLON.Animation.AllowMatricesInterpolation) {
  47430. return this._animation.matrixInterpolateFunction(startValue, endValue, gradient);
  47431. }
  47432. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47433. return startValue;
  47434. }
  47435. default:
  47436. break;
  47437. }
  47438. break;
  47439. }
  47440. }
  47441. return this._getKeyValue(keys[keys.length - 1].value);
  47442. };
  47443. RuntimeAnimation.prototype.setValue = function (currentValue, blend) {
  47444. if (blend === void 0) { blend = false; }
  47445. // Set value
  47446. var path;
  47447. var destination;
  47448. var targetPropertyPath = this._animation.targetPropertyPath;
  47449. if (targetPropertyPath.length > 1) {
  47450. var property = this._target[targetPropertyPath[0]];
  47451. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  47452. property = property[targetPropertyPath[index]];
  47453. }
  47454. path = targetPropertyPath[targetPropertyPath.length - 1];
  47455. destination = property;
  47456. }
  47457. else {
  47458. path = targetPropertyPath[0];
  47459. destination = this._target;
  47460. }
  47461. // Blending
  47462. var enableBlending = this._target && this._target.animationPropertiesOverride ? this._target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
  47463. var blendingSpeed = this._target && this._target.animationPropertiesOverride ? this._target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
  47464. if (enableBlending && this._blendingFactor <= 1.0) {
  47465. if (!this._originalBlendValue) {
  47466. if (destination[path].clone) {
  47467. this._originalBlendValue = destination[path].clone();
  47468. }
  47469. else {
  47470. this._originalBlendValue = destination[path];
  47471. }
  47472. }
  47473. if (this._originalBlendValue.prototype) {
  47474. if (this._originalBlendValue.prototype.Lerp) {
  47475. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  47476. }
  47477. else {
  47478. destination[path] = currentValue;
  47479. }
  47480. }
  47481. else if (this._originalBlendValue.m) {
  47482. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  47483. }
  47484. else {
  47485. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  47486. }
  47487. this._blendingFactor += blendingSpeed;
  47488. }
  47489. else {
  47490. destination[path] = currentValue;
  47491. }
  47492. if (this._target.markAsDirty) {
  47493. this._target.markAsDirty(this._animation.targetProperty);
  47494. }
  47495. };
  47496. RuntimeAnimation.prototype._getCorrectLoopMode = function () {
  47497. if (this._target && this._target.animationPropertiesOverride) {
  47498. return this._target.animationPropertiesOverride.loopMode;
  47499. }
  47500. return this._animation.loopMode;
  47501. };
  47502. RuntimeAnimation.prototype.goToFrame = function (frame) {
  47503. var keys = this._animation.getKeys();
  47504. if (frame < keys[0].frame) {
  47505. frame = keys[0].frame;
  47506. }
  47507. else if (frame > keys[keys.length - 1].frame) {
  47508. frame = keys[keys.length - 1].frame;
  47509. }
  47510. var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());
  47511. this.setValue(currentValue);
  47512. };
  47513. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  47514. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  47515. this._ratioOffset = this._previousRatio - newRatio;
  47516. };
  47517. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  47518. if (blend === void 0) { blend = false; }
  47519. var targetPropertyPath = this._animation.targetPropertyPath;
  47520. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  47521. this._stopped = true;
  47522. return false;
  47523. }
  47524. var returnValue = true;
  47525. var keys = this._animation.getKeys();
  47526. // Adding a start key at frame 0 if missing
  47527. if (keys[0].frame !== 0) {
  47528. var newKey = { frame: 0, value: keys[0].value };
  47529. keys.splice(0, 0, newKey);
  47530. }
  47531. // Check limits
  47532. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  47533. from = keys[0].frame;
  47534. }
  47535. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  47536. to = keys[keys.length - 1].frame;
  47537. }
  47538. //to and from cannot be the same key
  47539. if (from === to) {
  47540. if (from > keys[0].frame) {
  47541. from--;
  47542. }
  47543. else if (to < keys[keys.length - 1].frame) {
  47544. to++;
  47545. }
  47546. }
  47547. // Compute ratio
  47548. var range = to - from;
  47549. var offsetValue;
  47550. // ratio represents the frame delta between from and to
  47551. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  47552. var highLimitValue = 0;
  47553. this._previousDelay = delay;
  47554. this._previousRatio = ratio;
  47555. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) {
  47556. returnValue = false;
  47557. highLimitValue = this._getKeyValue(keys[keys.length - 1].value);
  47558. }
  47559. else {
  47560. // Get max value if required
  47561. if (this._getCorrectLoopMode() !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  47562. var keyOffset = to.toString() + from.toString();
  47563. if (!this._offsetsCache[keyOffset]) {
  47564. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  47565. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  47566. switch (this._animation.dataType) {
  47567. // Float
  47568. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  47569. this._offsetsCache[keyOffset] = toValue - fromValue;
  47570. break;
  47571. // Quaternion
  47572. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  47573. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  47574. break;
  47575. // Vector3
  47576. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  47577. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  47578. // Vector2
  47579. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  47580. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  47581. // Size
  47582. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  47583. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  47584. // Color3
  47585. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  47586. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  47587. default:
  47588. break;
  47589. }
  47590. this._highLimitsCache[keyOffset] = toValue;
  47591. }
  47592. highLimitValue = this._highLimitsCache[keyOffset];
  47593. offsetValue = this._offsetsCache[keyOffset];
  47594. }
  47595. }
  47596. if (offsetValue === undefined) {
  47597. switch (this._animation.dataType) {
  47598. // Float
  47599. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  47600. offsetValue = 0;
  47601. break;
  47602. // Quaternion
  47603. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  47604. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  47605. break;
  47606. // Vector3
  47607. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  47608. offsetValue = BABYLON.Vector3.Zero();
  47609. break;
  47610. // Vector2
  47611. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  47612. offsetValue = BABYLON.Vector2.Zero();
  47613. break;
  47614. // Size
  47615. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  47616. offsetValue = BABYLON.Size.Zero();
  47617. break;
  47618. // Color3
  47619. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  47620. offsetValue = BABYLON.Color3.Black();
  47621. }
  47622. }
  47623. // Compute value
  47624. var repeatCount = (ratio / range) >> 0;
  47625. var currentFrame = returnValue ? from + ratio % range : to;
  47626. var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);
  47627. // Set value
  47628. this.setValue(currentValue);
  47629. // Check events
  47630. var events = this._animation.getEvents();
  47631. for (var index = 0; index < events.length; index++) {
  47632. // Make sure current frame has passed event frame and that event frame is within the current range
  47633. // Also, handle both forward and reverse animations
  47634. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  47635. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  47636. var event = events[index];
  47637. if (!event.isDone) {
  47638. // If event should be done only once, remove it.
  47639. if (event.onlyOnce) {
  47640. events.splice(index, 1);
  47641. index--;
  47642. }
  47643. event.isDone = true;
  47644. event.action();
  47645. } // Don't do anything if the event has already be done.
  47646. }
  47647. else if (events[index].isDone && !events[index].onlyOnce) {
  47648. // reset event, the animation is looping
  47649. events[index].isDone = false;
  47650. }
  47651. }
  47652. if (!returnValue) {
  47653. this._stopped = true;
  47654. }
  47655. return returnValue;
  47656. };
  47657. return RuntimeAnimation;
  47658. }());
  47659. BABYLON.RuntimeAnimation = RuntimeAnimation;
  47660. })(BABYLON || (BABYLON = {}));
  47661. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  47662. var BABYLON;
  47663. (function (BABYLON) {
  47664. var Animatable = /** @class */ (function () {
  47665. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  47666. if (fromFrame === void 0) { fromFrame = 0; }
  47667. if (toFrame === void 0) { toFrame = 100; }
  47668. if (loopAnimation === void 0) { loopAnimation = false; }
  47669. if (speedRatio === void 0) { speedRatio = 1.0; }
  47670. this.target = target;
  47671. this.fromFrame = fromFrame;
  47672. this.toFrame = toFrame;
  47673. this.loopAnimation = loopAnimation;
  47674. this.onAnimationEnd = onAnimationEnd;
  47675. this._localDelayOffset = null;
  47676. this._pausedDelay = null;
  47677. this._runtimeAnimations = new Array();
  47678. this._paused = false;
  47679. this._speedRatio = 1;
  47680. this.animationStarted = false;
  47681. if (animations) {
  47682. this.appendAnimations(target, animations);
  47683. }
  47684. this._speedRatio = speedRatio;
  47685. this._scene = scene;
  47686. scene._activeAnimatables.push(this);
  47687. }
  47688. Object.defineProperty(Animatable.prototype, "speedRatio", {
  47689. get: function () {
  47690. return this._speedRatio;
  47691. },
  47692. set: function (value) {
  47693. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  47694. var animation = this._runtimeAnimations[index];
  47695. animation._prepareForSpeedRatioChange(value);
  47696. }
  47697. this._speedRatio = value;
  47698. },
  47699. enumerable: true,
  47700. configurable: true
  47701. });
  47702. // Methods
  47703. Animatable.prototype.getAnimations = function () {
  47704. return this._runtimeAnimations;
  47705. };
  47706. Animatable.prototype.appendAnimations = function (target, animations) {
  47707. for (var index = 0; index < animations.length; index++) {
  47708. var animation = animations[index];
  47709. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation));
  47710. }
  47711. };
  47712. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  47713. var runtimeAnimations = this._runtimeAnimations;
  47714. for (var index = 0; index < runtimeAnimations.length; index++) {
  47715. if (runtimeAnimations[index].animation.targetProperty === property) {
  47716. return runtimeAnimations[index].animation;
  47717. }
  47718. }
  47719. return null;
  47720. };
  47721. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  47722. var runtimeAnimations = this._runtimeAnimations;
  47723. for (var index = 0; index < runtimeAnimations.length; index++) {
  47724. if (runtimeAnimations[index].animation.targetProperty === property) {
  47725. return runtimeAnimations[index];
  47726. }
  47727. }
  47728. return null;
  47729. };
  47730. Animatable.prototype.reset = function () {
  47731. var runtimeAnimations = this._runtimeAnimations;
  47732. for (var index = 0; index < runtimeAnimations.length; index++) {
  47733. runtimeAnimations[index].reset();
  47734. }
  47735. // Reset to original value
  47736. for (index = 0; index < runtimeAnimations.length; index++) {
  47737. var animation = runtimeAnimations[index];
  47738. animation.animate(0, this.fromFrame, this.toFrame, false, this._speedRatio);
  47739. }
  47740. this._localDelayOffset = null;
  47741. this._pausedDelay = null;
  47742. };
  47743. Animatable.prototype.enableBlending = function (blendingSpeed) {
  47744. var runtimeAnimations = this._runtimeAnimations;
  47745. for (var index = 0; index < runtimeAnimations.length; index++) {
  47746. runtimeAnimations[index].animation.enableBlending = true;
  47747. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  47748. }
  47749. };
  47750. Animatable.prototype.disableBlending = function () {
  47751. var runtimeAnimations = this._runtimeAnimations;
  47752. for (var index = 0; index < runtimeAnimations.length; index++) {
  47753. runtimeAnimations[index].animation.enableBlending = false;
  47754. }
  47755. };
  47756. Animatable.prototype.goToFrame = function (frame) {
  47757. var runtimeAnimations = this._runtimeAnimations;
  47758. if (runtimeAnimations[0]) {
  47759. var fps = runtimeAnimations[0].animation.framePerSecond;
  47760. var currentFrame = runtimeAnimations[0].currentFrame;
  47761. var adjustTime = frame - currentFrame;
  47762. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  47763. if (this._localDelayOffset === null) {
  47764. this._localDelayOffset = 0;
  47765. }
  47766. this._localDelayOffset -= delay;
  47767. }
  47768. for (var index = 0; index < runtimeAnimations.length; index++) {
  47769. runtimeAnimations[index].goToFrame(frame);
  47770. }
  47771. };
  47772. Animatable.prototype.pause = function () {
  47773. if (this._paused) {
  47774. return;
  47775. }
  47776. this._paused = true;
  47777. };
  47778. Animatable.prototype.restart = function () {
  47779. this._paused = false;
  47780. };
  47781. Animatable.prototype.stop = function (animationName) {
  47782. if (animationName) {
  47783. var idx = this._scene._activeAnimatables.indexOf(this);
  47784. if (idx > -1) {
  47785. var runtimeAnimations = this._runtimeAnimations;
  47786. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  47787. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  47788. continue;
  47789. }
  47790. runtimeAnimations[index].dispose();
  47791. runtimeAnimations.splice(index, 1);
  47792. }
  47793. if (runtimeAnimations.length == 0) {
  47794. this._scene._activeAnimatables.splice(idx, 1);
  47795. if (this.onAnimationEnd) {
  47796. this.onAnimationEnd();
  47797. }
  47798. }
  47799. }
  47800. }
  47801. else {
  47802. var index = this._scene._activeAnimatables.indexOf(this);
  47803. if (index > -1) {
  47804. this._scene._activeAnimatables.splice(index, 1);
  47805. var runtimeAnimations = this._runtimeAnimations;
  47806. for (var index = 0; index < runtimeAnimations.length; index++) {
  47807. runtimeAnimations[index].dispose();
  47808. }
  47809. if (this.onAnimationEnd) {
  47810. this.onAnimationEnd();
  47811. }
  47812. }
  47813. }
  47814. };
  47815. Animatable.prototype._animate = function (delay) {
  47816. if (this._paused) {
  47817. this.animationStarted = false;
  47818. if (this._pausedDelay === null) {
  47819. this._pausedDelay = delay;
  47820. }
  47821. return true;
  47822. }
  47823. if (this._localDelayOffset === null) {
  47824. this._localDelayOffset = delay;
  47825. this._pausedDelay = null;
  47826. }
  47827. else if (this._pausedDelay !== null) {
  47828. this._localDelayOffset += delay - this._pausedDelay;
  47829. this._pausedDelay = null;
  47830. }
  47831. // Animating
  47832. var running = false;
  47833. var runtimeAnimations = this._runtimeAnimations;
  47834. var index;
  47835. for (index = 0; index < runtimeAnimations.length; index++) {
  47836. var animation = runtimeAnimations[index];
  47837. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio);
  47838. running = running || isRunning;
  47839. }
  47840. this.animationStarted = running;
  47841. if (!running) {
  47842. // Remove from active animatables
  47843. index = this._scene._activeAnimatables.indexOf(this);
  47844. this._scene._activeAnimatables.splice(index, 1);
  47845. // Dispose all runtime animations
  47846. for (index = 0; index < runtimeAnimations.length; index++) {
  47847. runtimeAnimations[index].dispose();
  47848. }
  47849. }
  47850. if (!running && this.onAnimationEnd) {
  47851. this.onAnimationEnd();
  47852. this.onAnimationEnd = null;
  47853. }
  47854. return running;
  47855. };
  47856. return Animatable;
  47857. }());
  47858. BABYLON.Animatable = Animatable;
  47859. })(BABYLON || (BABYLON = {}));
  47860. //# sourceMappingURL=babylon.animatable.js.map
  47861. var BABYLON;
  47862. (function (BABYLON) {
  47863. var EasingFunction = /** @class */ (function () {
  47864. function EasingFunction() {
  47865. // Properties
  47866. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  47867. }
  47868. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  47869. get: function () {
  47870. return EasingFunction._EASINGMODE_EASEIN;
  47871. },
  47872. enumerable: true,
  47873. configurable: true
  47874. });
  47875. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  47876. get: function () {
  47877. return EasingFunction._EASINGMODE_EASEOUT;
  47878. },
  47879. enumerable: true,
  47880. configurable: true
  47881. });
  47882. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  47883. get: function () {
  47884. return EasingFunction._EASINGMODE_EASEINOUT;
  47885. },
  47886. enumerable: true,
  47887. configurable: true
  47888. });
  47889. EasingFunction.prototype.setEasingMode = function (easingMode) {
  47890. var n = Math.min(Math.max(easingMode, 0), 2);
  47891. this._easingMode = n;
  47892. };
  47893. EasingFunction.prototype.getEasingMode = function () {
  47894. return this._easingMode;
  47895. };
  47896. EasingFunction.prototype.easeInCore = function (gradient) {
  47897. throw new Error('You must implement this method');
  47898. };
  47899. EasingFunction.prototype.ease = function (gradient) {
  47900. switch (this._easingMode) {
  47901. case EasingFunction.EASINGMODE_EASEIN:
  47902. return this.easeInCore(gradient);
  47903. case EasingFunction.EASINGMODE_EASEOUT:
  47904. return (1 - this.easeInCore(1 - gradient));
  47905. }
  47906. if (gradient >= 0.5) {
  47907. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  47908. }
  47909. return (this.easeInCore(gradient * 2) * 0.5);
  47910. };
  47911. //Statics
  47912. EasingFunction._EASINGMODE_EASEIN = 0;
  47913. EasingFunction._EASINGMODE_EASEOUT = 1;
  47914. EasingFunction._EASINGMODE_EASEINOUT = 2;
  47915. return EasingFunction;
  47916. }());
  47917. BABYLON.EasingFunction = EasingFunction;
  47918. var CircleEase = /** @class */ (function (_super) {
  47919. __extends(CircleEase, _super);
  47920. function CircleEase() {
  47921. return _super !== null && _super.apply(this, arguments) || this;
  47922. }
  47923. CircleEase.prototype.easeInCore = function (gradient) {
  47924. gradient = Math.max(0, Math.min(1, gradient));
  47925. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  47926. };
  47927. return CircleEase;
  47928. }(EasingFunction));
  47929. BABYLON.CircleEase = CircleEase;
  47930. var BackEase = /** @class */ (function (_super) {
  47931. __extends(BackEase, _super);
  47932. function BackEase(amplitude) {
  47933. if (amplitude === void 0) { amplitude = 1; }
  47934. var _this = _super.call(this) || this;
  47935. _this.amplitude = amplitude;
  47936. return _this;
  47937. }
  47938. BackEase.prototype.easeInCore = function (gradient) {
  47939. var num = Math.max(0, this.amplitude);
  47940. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  47941. };
  47942. return BackEase;
  47943. }(EasingFunction));
  47944. BABYLON.BackEase = BackEase;
  47945. var BounceEase = /** @class */ (function (_super) {
  47946. __extends(BounceEase, _super);
  47947. function BounceEase(bounces, bounciness) {
  47948. if (bounces === void 0) { bounces = 3; }
  47949. if (bounciness === void 0) { bounciness = 2; }
  47950. var _this = _super.call(this) || this;
  47951. _this.bounces = bounces;
  47952. _this.bounciness = bounciness;
  47953. return _this;
  47954. }
  47955. BounceEase.prototype.easeInCore = function (gradient) {
  47956. var y = Math.max(0.0, this.bounces);
  47957. var bounciness = this.bounciness;
  47958. if (bounciness <= 1.0) {
  47959. bounciness = 1.001;
  47960. }
  47961. var num9 = Math.pow(bounciness, y);
  47962. var num5 = 1.0 - bounciness;
  47963. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  47964. var num15 = gradient * num4;
  47965. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  47966. var num3 = Math.floor(num65);
  47967. var num13 = num3 + 1.0;
  47968. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  47969. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  47970. var num7 = (num8 + num12) * 0.5;
  47971. var num6 = gradient - num7;
  47972. var num2 = num7 - num8;
  47973. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  47974. };
  47975. return BounceEase;
  47976. }(EasingFunction));
  47977. BABYLON.BounceEase = BounceEase;
  47978. var CubicEase = /** @class */ (function (_super) {
  47979. __extends(CubicEase, _super);
  47980. function CubicEase() {
  47981. return _super !== null && _super.apply(this, arguments) || this;
  47982. }
  47983. CubicEase.prototype.easeInCore = function (gradient) {
  47984. return (gradient * gradient * gradient);
  47985. };
  47986. return CubicEase;
  47987. }(EasingFunction));
  47988. BABYLON.CubicEase = CubicEase;
  47989. var ElasticEase = /** @class */ (function (_super) {
  47990. __extends(ElasticEase, _super);
  47991. function ElasticEase(oscillations, springiness) {
  47992. if (oscillations === void 0) { oscillations = 3; }
  47993. if (springiness === void 0) { springiness = 3; }
  47994. var _this = _super.call(this) || this;
  47995. _this.oscillations = oscillations;
  47996. _this.springiness = springiness;
  47997. return _this;
  47998. }
  47999. ElasticEase.prototype.easeInCore = function (gradient) {
  48000. var num2;
  48001. var num3 = Math.max(0.0, this.oscillations);
  48002. var num = Math.max(0.0, this.springiness);
  48003. if (num == 0) {
  48004. num2 = gradient;
  48005. }
  48006. else {
  48007. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  48008. }
  48009. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  48010. };
  48011. return ElasticEase;
  48012. }(EasingFunction));
  48013. BABYLON.ElasticEase = ElasticEase;
  48014. var ExponentialEase = /** @class */ (function (_super) {
  48015. __extends(ExponentialEase, _super);
  48016. function ExponentialEase(exponent) {
  48017. if (exponent === void 0) { exponent = 2; }
  48018. var _this = _super.call(this) || this;
  48019. _this.exponent = exponent;
  48020. return _this;
  48021. }
  48022. ExponentialEase.prototype.easeInCore = function (gradient) {
  48023. if (this.exponent <= 0) {
  48024. return gradient;
  48025. }
  48026. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  48027. };
  48028. return ExponentialEase;
  48029. }(EasingFunction));
  48030. BABYLON.ExponentialEase = ExponentialEase;
  48031. var PowerEase = /** @class */ (function (_super) {
  48032. __extends(PowerEase, _super);
  48033. function PowerEase(power) {
  48034. if (power === void 0) { power = 2; }
  48035. var _this = _super.call(this) || this;
  48036. _this.power = power;
  48037. return _this;
  48038. }
  48039. PowerEase.prototype.easeInCore = function (gradient) {
  48040. var y = Math.max(0.0, this.power);
  48041. return Math.pow(gradient, y);
  48042. };
  48043. return PowerEase;
  48044. }(EasingFunction));
  48045. BABYLON.PowerEase = PowerEase;
  48046. var QuadraticEase = /** @class */ (function (_super) {
  48047. __extends(QuadraticEase, _super);
  48048. function QuadraticEase() {
  48049. return _super !== null && _super.apply(this, arguments) || this;
  48050. }
  48051. QuadraticEase.prototype.easeInCore = function (gradient) {
  48052. return (gradient * gradient);
  48053. };
  48054. return QuadraticEase;
  48055. }(EasingFunction));
  48056. BABYLON.QuadraticEase = QuadraticEase;
  48057. var QuarticEase = /** @class */ (function (_super) {
  48058. __extends(QuarticEase, _super);
  48059. function QuarticEase() {
  48060. return _super !== null && _super.apply(this, arguments) || this;
  48061. }
  48062. QuarticEase.prototype.easeInCore = function (gradient) {
  48063. return (gradient * gradient * gradient * gradient);
  48064. };
  48065. return QuarticEase;
  48066. }(EasingFunction));
  48067. BABYLON.QuarticEase = QuarticEase;
  48068. var QuinticEase = /** @class */ (function (_super) {
  48069. __extends(QuinticEase, _super);
  48070. function QuinticEase() {
  48071. return _super !== null && _super.apply(this, arguments) || this;
  48072. }
  48073. QuinticEase.prototype.easeInCore = function (gradient) {
  48074. return (gradient * gradient * gradient * gradient * gradient);
  48075. };
  48076. return QuinticEase;
  48077. }(EasingFunction));
  48078. BABYLON.QuinticEase = QuinticEase;
  48079. var SineEase = /** @class */ (function (_super) {
  48080. __extends(SineEase, _super);
  48081. function SineEase() {
  48082. return _super !== null && _super.apply(this, arguments) || this;
  48083. }
  48084. SineEase.prototype.easeInCore = function (gradient) {
  48085. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  48086. };
  48087. return SineEase;
  48088. }(EasingFunction));
  48089. BABYLON.SineEase = SineEase;
  48090. var BezierCurveEase = /** @class */ (function (_super) {
  48091. __extends(BezierCurveEase, _super);
  48092. function BezierCurveEase(x1, y1, x2, y2) {
  48093. if (x1 === void 0) { x1 = 0; }
  48094. if (y1 === void 0) { y1 = 0; }
  48095. if (x2 === void 0) { x2 = 1; }
  48096. if (y2 === void 0) { y2 = 1; }
  48097. var _this = _super.call(this) || this;
  48098. _this.x1 = x1;
  48099. _this.y1 = y1;
  48100. _this.x2 = x2;
  48101. _this.y2 = y2;
  48102. return _this;
  48103. }
  48104. BezierCurveEase.prototype.easeInCore = function (gradient) {
  48105. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  48106. };
  48107. return BezierCurveEase;
  48108. }(EasingFunction));
  48109. BABYLON.BezierCurveEase = BezierCurveEase;
  48110. })(BABYLON || (BABYLON = {}));
  48111. //# sourceMappingURL=babylon.easing.js.map
  48112. var BABYLON;
  48113. (function (BABYLON) {
  48114. var Condition = /** @class */ (function () {
  48115. function Condition(actionManager) {
  48116. this._actionManager = actionManager;
  48117. }
  48118. Condition.prototype.isValid = function () {
  48119. return true;
  48120. };
  48121. Condition.prototype._getProperty = function (propertyPath) {
  48122. return this._actionManager._getProperty(propertyPath);
  48123. };
  48124. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  48125. return this._actionManager._getEffectiveTarget(target, propertyPath);
  48126. };
  48127. Condition.prototype.serialize = function () {
  48128. };
  48129. Condition.prototype._serialize = function (serializedCondition) {
  48130. return {
  48131. type: 2,
  48132. children: [],
  48133. name: serializedCondition.name,
  48134. properties: serializedCondition.properties
  48135. };
  48136. };
  48137. return Condition;
  48138. }());
  48139. BABYLON.Condition = Condition;
  48140. var ValueCondition = /** @class */ (function (_super) {
  48141. __extends(ValueCondition, _super);
  48142. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  48143. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  48144. var _this = _super.call(this, actionManager) || this;
  48145. _this.propertyPath = propertyPath;
  48146. _this.value = value;
  48147. _this.operator = operator;
  48148. _this._target = target;
  48149. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  48150. _this._property = _this._getProperty(_this.propertyPath);
  48151. return _this;
  48152. }
  48153. Object.defineProperty(ValueCondition, "IsEqual", {
  48154. get: function () {
  48155. return ValueCondition._IsEqual;
  48156. },
  48157. enumerable: true,
  48158. configurable: true
  48159. });
  48160. Object.defineProperty(ValueCondition, "IsDifferent", {
  48161. get: function () {
  48162. return ValueCondition._IsDifferent;
  48163. },
  48164. enumerable: true,
  48165. configurable: true
  48166. });
  48167. Object.defineProperty(ValueCondition, "IsGreater", {
  48168. get: function () {
  48169. return ValueCondition._IsGreater;
  48170. },
  48171. enumerable: true,
  48172. configurable: true
  48173. });
  48174. Object.defineProperty(ValueCondition, "IsLesser", {
  48175. get: function () {
  48176. return ValueCondition._IsLesser;
  48177. },
  48178. enumerable: true,
  48179. configurable: true
  48180. });
  48181. // Methods
  48182. ValueCondition.prototype.isValid = function () {
  48183. switch (this.operator) {
  48184. case ValueCondition.IsGreater:
  48185. return this._effectiveTarget[this._property] > this.value;
  48186. case ValueCondition.IsLesser:
  48187. return this._effectiveTarget[this._property] < this.value;
  48188. case ValueCondition.IsEqual:
  48189. case ValueCondition.IsDifferent:
  48190. var check;
  48191. if (this.value.equals) {
  48192. check = this.value.equals(this._effectiveTarget[this._property]);
  48193. }
  48194. else {
  48195. check = this.value === this._effectiveTarget[this._property];
  48196. }
  48197. return this.operator === ValueCondition.IsEqual ? check : !check;
  48198. }
  48199. return false;
  48200. };
  48201. ValueCondition.prototype.serialize = function () {
  48202. return this._serialize({
  48203. name: "ValueCondition",
  48204. properties: [
  48205. BABYLON.Action._GetTargetProperty(this._target),
  48206. { name: "propertyPath", value: this.propertyPath },
  48207. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  48208. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  48209. ]
  48210. });
  48211. };
  48212. ValueCondition.GetOperatorName = function (operator) {
  48213. switch (operator) {
  48214. case ValueCondition._IsEqual: return "IsEqual";
  48215. case ValueCondition._IsDifferent: return "IsDifferent";
  48216. case ValueCondition._IsGreater: return "IsGreater";
  48217. case ValueCondition._IsLesser: return "IsLesser";
  48218. default: return "";
  48219. }
  48220. };
  48221. // Statics
  48222. ValueCondition._IsEqual = 0;
  48223. ValueCondition._IsDifferent = 1;
  48224. ValueCondition._IsGreater = 2;
  48225. ValueCondition._IsLesser = 3;
  48226. return ValueCondition;
  48227. }(Condition));
  48228. BABYLON.ValueCondition = ValueCondition;
  48229. var PredicateCondition = /** @class */ (function (_super) {
  48230. __extends(PredicateCondition, _super);
  48231. function PredicateCondition(actionManager, predicate) {
  48232. var _this = _super.call(this, actionManager) || this;
  48233. _this.predicate = predicate;
  48234. return _this;
  48235. }
  48236. PredicateCondition.prototype.isValid = function () {
  48237. return this.predicate();
  48238. };
  48239. return PredicateCondition;
  48240. }(Condition));
  48241. BABYLON.PredicateCondition = PredicateCondition;
  48242. var StateCondition = /** @class */ (function (_super) {
  48243. __extends(StateCondition, _super);
  48244. function StateCondition(actionManager, target, value) {
  48245. var _this = _super.call(this, actionManager) || this;
  48246. _this.value = value;
  48247. _this._target = target;
  48248. return _this;
  48249. }
  48250. // Methods
  48251. StateCondition.prototype.isValid = function () {
  48252. return this._target.state === this.value;
  48253. };
  48254. StateCondition.prototype.serialize = function () {
  48255. return this._serialize({
  48256. name: "StateCondition",
  48257. properties: [
  48258. BABYLON.Action._GetTargetProperty(this._target),
  48259. { name: "value", value: this.value }
  48260. ]
  48261. });
  48262. };
  48263. return StateCondition;
  48264. }(Condition));
  48265. BABYLON.StateCondition = StateCondition;
  48266. })(BABYLON || (BABYLON = {}));
  48267. //# sourceMappingURL=babylon.condition.js.map
  48268. var BABYLON;
  48269. (function (BABYLON) {
  48270. var Action = /** @class */ (function () {
  48271. function Action(triggerOptions, condition) {
  48272. this.triggerOptions = triggerOptions;
  48273. this.onBeforeExecuteObservable = new BABYLON.Observable();
  48274. if (triggerOptions.parameter) {
  48275. this.trigger = triggerOptions.trigger;
  48276. this._triggerParameter = triggerOptions.parameter;
  48277. }
  48278. else {
  48279. this.trigger = triggerOptions;
  48280. }
  48281. this._nextActiveAction = this;
  48282. this._condition = condition;
  48283. }
  48284. // Methods
  48285. Action.prototype._prepare = function () {
  48286. };
  48287. Action.prototype.getTriggerParameter = function () {
  48288. return this._triggerParameter;
  48289. };
  48290. Action.prototype._executeCurrent = function (evt) {
  48291. if (this._nextActiveAction._condition) {
  48292. var condition = this._nextActiveAction._condition;
  48293. var currentRenderId = this._actionManager.getScene().getRenderId();
  48294. // We cache the current evaluation for the current frame
  48295. if (condition._evaluationId === currentRenderId) {
  48296. if (!condition._currentResult) {
  48297. return;
  48298. }
  48299. }
  48300. else {
  48301. condition._evaluationId = currentRenderId;
  48302. if (!condition.isValid()) {
  48303. condition._currentResult = false;
  48304. return;
  48305. }
  48306. condition._currentResult = true;
  48307. }
  48308. }
  48309. this.onBeforeExecuteObservable.notifyObservers(this);
  48310. this._nextActiveAction.execute(evt);
  48311. this.skipToNextActiveAction();
  48312. };
  48313. Action.prototype.execute = function (evt) {
  48314. };
  48315. Action.prototype.skipToNextActiveAction = function () {
  48316. if (this._nextActiveAction._child) {
  48317. if (!this._nextActiveAction._child._actionManager) {
  48318. this._nextActiveAction._child._actionManager = this._actionManager;
  48319. }
  48320. this._nextActiveAction = this._nextActiveAction._child;
  48321. }
  48322. else {
  48323. this._nextActiveAction = this;
  48324. }
  48325. };
  48326. Action.prototype.then = function (action) {
  48327. this._child = action;
  48328. action._actionManager = this._actionManager;
  48329. action._prepare();
  48330. return action;
  48331. };
  48332. Action.prototype._getProperty = function (propertyPath) {
  48333. return this._actionManager._getProperty(propertyPath);
  48334. };
  48335. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  48336. return this._actionManager._getEffectiveTarget(target, propertyPath);
  48337. };
  48338. Action.prototype.serialize = function (parent) {
  48339. };
  48340. // Called by BABYLON.Action objects in serialize(...). Internal use
  48341. Action.prototype._serialize = function (serializedAction, parent) {
  48342. var serializationObject = {
  48343. type: 1,
  48344. children: [],
  48345. name: serializedAction.name,
  48346. properties: serializedAction.properties || []
  48347. };
  48348. // Serialize child
  48349. if (this._child) {
  48350. this._child.serialize(serializationObject);
  48351. }
  48352. // Check if "this" has a condition
  48353. if (this._condition) {
  48354. var serializedCondition = this._condition.serialize();
  48355. serializedCondition.children.push(serializationObject);
  48356. if (parent) {
  48357. parent.children.push(serializedCondition);
  48358. }
  48359. return serializedCondition;
  48360. }
  48361. if (parent) {
  48362. parent.children.push(serializationObject);
  48363. }
  48364. return serializationObject;
  48365. };
  48366. Action._SerializeValueAsString = function (value) {
  48367. if (typeof value === "number") {
  48368. return value.toString();
  48369. }
  48370. if (typeof value === "boolean") {
  48371. return value ? "true" : "false";
  48372. }
  48373. if (value instanceof BABYLON.Vector2) {
  48374. return value.x + ", " + value.y;
  48375. }
  48376. if (value instanceof BABYLON.Vector3) {
  48377. return value.x + ", " + value.y + ", " + value.z;
  48378. }
  48379. if (value instanceof BABYLON.Color3) {
  48380. return value.r + ", " + value.g + ", " + value.b;
  48381. }
  48382. if (value instanceof BABYLON.Color4) {
  48383. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  48384. }
  48385. return value; // string
  48386. };
  48387. Action._GetTargetProperty = function (target) {
  48388. return {
  48389. name: "target",
  48390. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  48391. : target instanceof BABYLON.Light ? "LightProperties"
  48392. : target instanceof BABYLON.Camera ? "CameraProperties"
  48393. : "SceneProperties",
  48394. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  48395. };
  48396. };
  48397. return Action;
  48398. }());
  48399. BABYLON.Action = Action;
  48400. })(BABYLON || (BABYLON = {}));
  48401. //# sourceMappingURL=babylon.action.js.map
  48402. var BABYLON;
  48403. (function (BABYLON) {
  48404. /**
  48405. * ActionEvent is the event beint sent when an action is triggered.
  48406. */
  48407. var ActionEvent = /** @class */ (function () {
  48408. /**
  48409. * @param source The mesh or sprite that triggered the action.
  48410. * @param pointerX The X mouse cursor position at the time of the event
  48411. * @param pointerY The Y mouse cursor position at the time of the event
  48412. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  48413. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  48414. */
  48415. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  48416. this.source = source;
  48417. this.pointerX = pointerX;
  48418. this.pointerY = pointerY;
  48419. this.meshUnderPointer = meshUnderPointer;
  48420. this.sourceEvent = sourceEvent;
  48421. this.additionalData = additionalData;
  48422. }
  48423. /**
  48424. * Helper function to auto-create an ActionEvent from a source mesh.
  48425. * @param source The source mesh that triggered the event
  48426. * @param evt {Event} The original (browser) event
  48427. */
  48428. ActionEvent.CreateNew = function (source, evt, additionalData) {
  48429. var scene = source.getScene();
  48430. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  48431. };
  48432. /**
  48433. * Helper function to auto-create an ActionEvent from a source mesh.
  48434. * @param source The source sprite that triggered the event
  48435. * @param scene Scene associated with the sprite
  48436. * @param evt {Event} The original (browser) event
  48437. */
  48438. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  48439. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  48440. };
  48441. /**
  48442. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  48443. * @param scene the scene where the event occurred
  48444. * @param evt {Event} The original (browser) event
  48445. */
  48446. ActionEvent.CreateNewFromScene = function (scene, evt) {
  48447. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  48448. };
  48449. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  48450. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  48451. };
  48452. return ActionEvent;
  48453. }());
  48454. BABYLON.ActionEvent = ActionEvent;
  48455. /**
  48456. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  48457. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  48458. */
  48459. var ActionManager = /** @class */ (function () {
  48460. function ActionManager(scene) {
  48461. // Members
  48462. this.actions = new Array();
  48463. this.hoverCursor = '';
  48464. this._scene = scene;
  48465. scene._actionManagers.push(this);
  48466. }
  48467. Object.defineProperty(ActionManager, "NothingTrigger", {
  48468. get: function () {
  48469. return ActionManager._NothingTrigger;
  48470. },
  48471. enumerable: true,
  48472. configurable: true
  48473. });
  48474. Object.defineProperty(ActionManager, "OnPickTrigger", {
  48475. get: function () {
  48476. return ActionManager._OnPickTrigger;
  48477. },
  48478. enumerable: true,
  48479. configurable: true
  48480. });
  48481. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  48482. get: function () {
  48483. return ActionManager._OnLeftPickTrigger;
  48484. },
  48485. enumerable: true,
  48486. configurable: true
  48487. });
  48488. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  48489. get: function () {
  48490. return ActionManager._OnRightPickTrigger;
  48491. },
  48492. enumerable: true,
  48493. configurable: true
  48494. });
  48495. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  48496. get: function () {
  48497. return ActionManager._OnCenterPickTrigger;
  48498. },
  48499. enumerable: true,
  48500. configurable: true
  48501. });
  48502. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  48503. get: function () {
  48504. return ActionManager._OnPickDownTrigger;
  48505. },
  48506. enumerable: true,
  48507. configurable: true
  48508. });
  48509. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  48510. get: function () {
  48511. return ActionManager._OnDoublePickTrigger;
  48512. },
  48513. enumerable: true,
  48514. configurable: true
  48515. });
  48516. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  48517. get: function () {
  48518. return ActionManager._OnPickUpTrigger;
  48519. },
  48520. enumerable: true,
  48521. configurable: true
  48522. });
  48523. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  48524. /// This trigger will only be raised if you also declared a OnPickDown
  48525. get: function () {
  48526. return ActionManager._OnPickOutTrigger;
  48527. },
  48528. enumerable: true,
  48529. configurable: true
  48530. });
  48531. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  48532. get: function () {
  48533. return ActionManager._OnLongPressTrigger;
  48534. },
  48535. enumerable: true,
  48536. configurable: true
  48537. });
  48538. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  48539. get: function () {
  48540. return ActionManager._OnPointerOverTrigger;
  48541. },
  48542. enumerable: true,
  48543. configurable: true
  48544. });
  48545. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  48546. get: function () {
  48547. return ActionManager._OnPointerOutTrigger;
  48548. },
  48549. enumerable: true,
  48550. configurable: true
  48551. });
  48552. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  48553. get: function () {
  48554. return ActionManager._OnEveryFrameTrigger;
  48555. },
  48556. enumerable: true,
  48557. configurable: true
  48558. });
  48559. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  48560. get: function () {
  48561. return ActionManager._OnIntersectionEnterTrigger;
  48562. },
  48563. enumerable: true,
  48564. configurable: true
  48565. });
  48566. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  48567. get: function () {
  48568. return ActionManager._OnIntersectionExitTrigger;
  48569. },
  48570. enumerable: true,
  48571. configurable: true
  48572. });
  48573. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  48574. get: function () {
  48575. return ActionManager._OnKeyDownTrigger;
  48576. },
  48577. enumerable: true,
  48578. configurable: true
  48579. });
  48580. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  48581. get: function () {
  48582. return ActionManager._OnKeyUpTrigger;
  48583. },
  48584. enumerable: true,
  48585. configurable: true
  48586. });
  48587. // Methods
  48588. ActionManager.prototype.dispose = function () {
  48589. var index = this._scene._actionManagers.indexOf(this);
  48590. for (var i = 0; i < this.actions.length; i++) {
  48591. var action = this.actions[i];
  48592. ActionManager.Triggers[action.trigger]--;
  48593. if (ActionManager.Triggers[action.trigger] === 0) {
  48594. delete ActionManager.Triggers[action.trigger];
  48595. }
  48596. }
  48597. if (index > -1) {
  48598. this._scene._actionManagers.splice(index, 1);
  48599. }
  48600. };
  48601. ActionManager.prototype.getScene = function () {
  48602. return this._scene;
  48603. };
  48604. /**
  48605. * Does this action manager handles actions of any of the given triggers
  48606. * @param {number[]} triggers - the triggers to be tested
  48607. * @return {boolean} whether one (or more) of the triggers is handeled
  48608. */
  48609. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  48610. for (var index = 0; index < this.actions.length; index++) {
  48611. var action = this.actions[index];
  48612. if (triggers.indexOf(action.trigger) > -1) {
  48613. return true;
  48614. }
  48615. }
  48616. return false;
  48617. };
  48618. /**
  48619. * Does this action manager handles actions of a given trigger
  48620. * @param {number} trigger - the trigger to be tested
  48621. * @return {boolean} whether the trigger is handeled
  48622. */
  48623. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  48624. for (var index = 0; index < this.actions.length; index++) {
  48625. var action = this.actions[index];
  48626. if (action.trigger === trigger) {
  48627. return true;
  48628. }
  48629. }
  48630. return false;
  48631. };
  48632. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  48633. /**
  48634. * Does this action manager has pointer triggers
  48635. * @return {boolean} whether or not it has pointer triggers
  48636. */
  48637. get: function () {
  48638. for (var index = 0; index < this.actions.length; index++) {
  48639. var action = this.actions[index];
  48640. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  48641. return true;
  48642. }
  48643. }
  48644. return false;
  48645. },
  48646. enumerable: true,
  48647. configurable: true
  48648. });
  48649. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  48650. /**
  48651. * Does this action manager has pick triggers
  48652. * @return {boolean} whether or not it has pick triggers
  48653. */
  48654. get: function () {
  48655. for (var index = 0; index < this.actions.length; index++) {
  48656. var action = this.actions[index];
  48657. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  48658. return true;
  48659. }
  48660. }
  48661. return false;
  48662. },
  48663. enumerable: true,
  48664. configurable: true
  48665. });
  48666. Object.defineProperty(ActionManager, "HasTriggers", {
  48667. /**
  48668. * Does exist one action manager with at least one trigger
  48669. * @return {boolean} whether or not it exists one action manager with one trigger
  48670. **/
  48671. get: function () {
  48672. for (var t in ActionManager.Triggers) {
  48673. if (ActionManager.Triggers.hasOwnProperty(t)) {
  48674. return true;
  48675. }
  48676. }
  48677. return false;
  48678. },
  48679. enumerable: true,
  48680. configurable: true
  48681. });
  48682. Object.defineProperty(ActionManager, "HasPickTriggers", {
  48683. /**
  48684. * Does exist one action manager with at least one pick trigger
  48685. * @return {boolean} whether or not it exists one action manager with one pick trigger
  48686. **/
  48687. get: function () {
  48688. for (var t in ActionManager.Triggers) {
  48689. if (ActionManager.Triggers.hasOwnProperty(t)) {
  48690. var t_int = parseInt(t);
  48691. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  48692. return true;
  48693. }
  48694. }
  48695. }
  48696. return false;
  48697. },
  48698. enumerable: true,
  48699. configurable: true
  48700. });
  48701. /**
  48702. * Does exist one action manager that handles actions of a given trigger
  48703. * @param {number} trigger - the trigger to be tested
  48704. * @return {boolean} whether the trigger is handeled by at least one action manager
  48705. **/
  48706. ActionManager.HasSpecificTrigger = function (trigger) {
  48707. for (var t in ActionManager.Triggers) {
  48708. if (ActionManager.Triggers.hasOwnProperty(t)) {
  48709. var t_int = parseInt(t);
  48710. if (t_int === trigger) {
  48711. return true;
  48712. }
  48713. }
  48714. }
  48715. return false;
  48716. };
  48717. /**
  48718. * Registers an action to this action manager
  48719. * @param {BABYLON.Action} action - the action to be registered
  48720. * @return {BABYLON.Action} the action amended (prepared) after registration
  48721. */
  48722. ActionManager.prototype.registerAction = function (action) {
  48723. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  48724. if (this.getScene().actionManager !== this) {
  48725. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  48726. return null;
  48727. }
  48728. }
  48729. this.actions.push(action);
  48730. if (ActionManager.Triggers[action.trigger]) {
  48731. ActionManager.Triggers[action.trigger]++;
  48732. }
  48733. else {
  48734. ActionManager.Triggers[action.trigger] = 1;
  48735. }
  48736. action._actionManager = this;
  48737. action._prepare();
  48738. return action;
  48739. };
  48740. /**
  48741. * Unregisters an action to this action manager
  48742. * @param action The action to be unregistered
  48743. * @return whether the action has been unregistered
  48744. */
  48745. ActionManager.prototype.unregisterAction = function (action) {
  48746. var index = this.actions.indexOf(action);
  48747. if (index !== -1) {
  48748. this.actions.splice(index, 1);
  48749. ActionManager.Triggers[action.trigger] -= 1;
  48750. if (ActionManager.Triggers[action.trigger] === 0) {
  48751. delete ActionManager.Triggers[action.trigger];
  48752. }
  48753. delete action._actionManager;
  48754. return true;
  48755. }
  48756. return false;
  48757. };
  48758. /**
  48759. * Process a specific trigger
  48760. * @param {number} trigger - the trigger to process
  48761. * @param evt {BABYLON.ActionEvent} the event details to be processed
  48762. */
  48763. ActionManager.prototype.processTrigger = function (trigger, evt) {
  48764. for (var index = 0; index < this.actions.length; index++) {
  48765. var action = this.actions[index];
  48766. if (action.trigger === trigger) {
  48767. if (evt) {
  48768. if (trigger === ActionManager.OnKeyUpTrigger
  48769. || trigger === ActionManager.OnKeyDownTrigger) {
  48770. var parameter = action.getTriggerParameter();
  48771. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  48772. if (!parameter.toLowerCase) {
  48773. continue;
  48774. }
  48775. var lowerCase = parameter.toLowerCase();
  48776. if (lowerCase !== evt.sourceEvent.key) {
  48777. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  48778. var actualkey = String.fromCharCode(unicode).toLowerCase();
  48779. if (actualkey !== lowerCase) {
  48780. continue;
  48781. }
  48782. }
  48783. }
  48784. }
  48785. }
  48786. action._executeCurrent(evt);
  48787. }
  48788. }
  48789. };
  48790. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  48791. var properties = propertyPath.split(".");
  48792. for (var index = 0; index < properties.length - 1; index++) {
  48793. target = target[properties[index]];
  48794. }
  48795. return target;
  48796. };
  48797. ActionManager.prototype._getProperty = function (propertyPath) {
  48798. var properties = propertyPath.split(".");
  48799. return properties[properties.length - 1];
  48800. };
  48801. ActionManager.prototype.serialize = function (name) {
  48802. var root = {
  48803. children: new Array(),
  48804. name: name,
  48805. type: 3,
  48806. properties: new Array() // Empty for root but required
  48807. };
  48808. for (var i = 0; i < this.actions.length; i++) {
  48809. var triggerObject = {
  48810. type: 0,
  48811. children: new Array(),
  48812. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  48813. properties: new Array()
  48814. };
  48815. var triggerOptions = this.actions[i].triggerOptions;
  48816. if (triggerOptions && typeof triggerOptions !== "number") {
  48817. if (triggerOptions.parameter instanceof BABYLON.Node) {
  48818. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  48819. }
  48820. else {
  48821. var parameter = {};
  48822. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  48823. if (triggerOptions.parameter.mesh) {
  48824. parameter._meshId = triggerOptions.parameter.mesh.id;
  48825. }
  48826. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  48827. }
  48828. }
  48829. // Serialize child action, recursively
  48830. this.actions[i].serialize(triggerObject);
  48831. // Add serialized trigger
  48832. root.children.push(triggerObject);
  48833. }
  48834. return root;
  48835. };
  48836. ActionManager.Parse = function (parsedActions, object, scene) {
  48837. var actionManager = new ActionManager(scene);
  48838. if (object === null)
  48839. scene.actionManager = actionManager;
  48840. else
  48841. object.actionManager = actionManager;
  48842. // instanciate a new object
  48843. var instanciate = function (name, params) {
  48844. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  48845. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  48846. newInstance.constructor.apply(newInstance, params);
  48847. return newInstance;
  48848. };
  48849. var parseParameter = function (name, value, target, propertyPath) {
  48850. if (propertyPath === null) {
  48851. // String, boolean or float
  48852. var floatValue = parseFloat(value);
  48853. if (value === "true" || value === "false")
  48854. return value === "true";
  48855. else
  48856. return isNaN(floatValue) ? value : floatValue;
  48857. }
  48858. var effectiveTarget = propertyPath.split(".");
  48859. var values = value.split(",");
  48860. // Get effective Target
  48861. for (var i = 0; i < effectiveTarget.length; i++) {
  48862. target = target[effectiveTarget[i]];
  48863. }
  48864. // Return appropriate value with its type
  48865. if (typeof (target) === "boolean")
  48866. return values[0] === "true";
  48867. if (typeof (target) === "string")
  48868. return values[0];
  48869. // Parameters with multiple values such as Vector3 etc.
  48870. var split = new Array();
  48871. for (var i = 0; i < values.length; i++)
  48872. split.push(parseFloat(values[i]));
  48873. if (target instanceof BABYLON.Vector3)
  48874. return BABYLON.Vector3.FromArray(split);
  48875. if (target instanceof BABYLON.Vector4)
  48876. return BABYLON.Vector4.FromArray(split);
  48877. if (target instanceof BABYLON.Color3)
  48878. return BABYLON.Color3.FromArray(split);
  48879. if (target instanceof BABYLON.Color4)
  48880. return BABYLON.Color4.FromArray(split);
  48881. return parseFloat(values[0]);
  48882. };
  48883. // traverse graph per trigger
  48884. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  48885. if (combineArray === void 0) { combineArray = null; }
  48886. if (parsedAction.detached)
  48887. return;
  48888. var parameters = new Array();
  48889. var target = null;
  48890. var propertyPath = null;
  48891. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  48892. // Parameters
  48893. if (parsedAction.type === 2)
  48894. parameters.push(actionManager);
  48895. else
  48896. parameters.push(trigger);
  48897. if (combine) {
  48898. var actions = new Array();
  48899. for (var j = 0; j < parsedAction.combine.length; j++) {
  48900. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  48901. }
  48902. parameters.push(actions);
  48903. }
  48904. else {
  48905. for (var i = 0; i < parsedAction.properties.length; i++) {
  48906. var value = parsedAction.properties[i].value;
  48907. var name = parsedAction.properties[i].name;
  48908. var targetType = parsedAction.properties[i].targetType;
  48909. if (name === "target")
  48910. if (targetType !== null && targetType === "SceneProperties")
  48911. value = target = scene;
  48912. else
  48913. value = target = scene.getNodeByName(value);
  48914. else if (name === "parent")
  48915. value = scene.getNodeByName(value);
  48916. else if (name === "sound")
  48917. value = scene.getSoundByName(value);
  48918. else if (name !== "propertyPath") {
  48919. if (parsedAction.type === 2 && name === "operator")
  48920. value = BABYLON.ValueCondition[value];
  48921. else
  48922. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  48923. }
  48924. else {
  48925. propertyPath = value;
  48926. }
  48927. parameters.push(value);
  48928. }
  48929. }
  48930. if (combineArray === null) {
  48931. parameters.push(condition);
  48932. }
  48933. else {
  48934. parameters.push(null);
  48935. }
  48936. // If interpolate value action
  48937. if (parsedAction.name === "InterpolateValueAction") {
  48938. var param = parameters[parameters.length - 2];
  48939. parameters[parameters.length - 1] = param;
  48940. parameters[parameters.length - 2] = condition;
  48941. }
  48942. // Action or condition(s) and not CombineAction
  48943. var newAction = instanciate(parsedAction.name, parameters);
  48944. if (newAction instanceof BABYLON.Condition && condition !== null) {
  48945. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  48946. if (action)
  48947. action.then(nothing);
  48948. else
  48949. actionManager.registerAction(nothing);
  48950. action = nothing;
  48951. }
  48952. if (combineArray === null) {
  48953. if (newAction instanceof BABYLON.Condition) {
  48954. condition = newAction;
  48955. newAction = action;
  48956. }
  48957. else {
  48958. condition = null;
  48959. if (action)
  48960. action.then(newAction);
  48961. else
  48962. actionManager.registerAction(newAction);
  48963. }
  48964. }
  48965. else {
  48966. combineArray.push(newAction);
  48967. }
  48968. for (var i = 0; i < parsedAction.children.length; i++)
  48969. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  48970. };
  48971. // triggers
  48972. for (var i = 0; i < parsedActions.children.length; i++) {
  48973. var triggerParams;
  48974. var trigger = parsedActions.children[i];
  48975. if (trigger.properties.length > 0) {
  48976. var param = trigger.properties[0].value;
  48977. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  48978. if (value._meshId) {
  48979. value.mesh = scene.getMeshByID(value._meshId);
  48980. }
  48981. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  48982. }
  48983. else
  48984. triggerParams = ActionManager[trigger.name];
  48985. for (var j = 0; j < trigger.children.length; j++) {
  48986. if (!trigger.detached)
  48987. traverse(trigger.children[j], triggerParams, null, null);
  48988. }
  48989. }
  48990. };
  48991. ActionManager.GetTriggerName = function (trigger) {
  48992. switch (trigger) {
  48993. case 0: return "NothingTrigger";
  48994. case 1: return "OnPickTrigger";
  48995. case 2: return "OnLeftPickTrigger";
  48996. case 3: return "OnRightPickTrigger";
  48997. case 4: return "OnCenterPickTrigger";
  48998. case 5: return "OnPickDownTrigger";
  48999. case 6: return "OnPickUpTrigger";
  49000. case 7: return "OnLongPressTrigger";
  49001. case 8: return "OnPointerOverTrigger";
  49002. case 9: return "OnPointerOutTrigger";
  49003. case 10: return "OnEveryFrameTrigger";
  49004. case 11: return "OnIntersectionEnterTrigger";
  49005. case 12: return "OnIntersectionExitTrigger";
  49006. case 13: return "OnKeyDownTrigger";
  49007. case 14: return "OnKeyUpTrigger";
  49008. case 15: return "OnPickOutTrigger";
  49009. default: return "";
  49010. }
  49011. };
  49012. // Statics
  49013. ActionManager._NothingTrigger = 0;
  49014. ActionManager._OnPickTrigger = 1;
  49015. ActionManager._OnLeftPickTrigger = 2;
  49016. ActionManager._OnRightPickTrigger = 3;
  49017. ActionManager._OnCenterPickTrigger = 4;
  49018. ActionManager._OnPickDownTrigger = 5;
  49019. ActionManager._OnDoublePickTrigger = 6;
  49020. ActionManager._OnPickUpTrigger = 7;
  49021. ActionManager._OnLongPressTrigger = 8;
  49022. ActionManager._OnPointerOverTrigger = 9;
  49023. ActionManager._OnPointerOutTrigger = 10;
  49024. ActionManager._OnEveryFrameTrigger = 11;
  49025. ActionManager._OnIntersectionEnterTrigger = 12;
  49026. ActionManager._OnIntersectionExitTrigger = 13;
  49027. ActionManager._OnKeyDownTrigger = 14;
  49028. ActionManager._OnKeyUpTrigger = 15;
  49029. ActionManager._OnPickOutTrigger = 16;
  49030. ActionManager.Triggers = {};
  49031. return ActionManager;
  49032. }());
  49033. BABYLON.ActionManager = ActionManager;
  49034. })(BABYLON || (BABYLON = {}));
  49035. //# sourceMappingURL=babylon.actionManager.js.map
  49036. var BABYLON;
  49037. (function (BABYLON) {
  49038. var InterpolateValueAction = /** @class */ (function (_super) {
  49039. __extends(InterpolateValueAction, _super);
  49040. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  49041. if (duration === void 0) { duration = 1000; }
  49042. var _this = _super.call(this, triggerOptions, condition) || this;
  49043. _this.propertyPath = propertyPath;
  49044. _this.value = value;
  49045. _this.duration = duration;
  49046. _this.stopOtherAnimations = stopOtherAnimations;
  49047. _this.onInterpolationDone = onInterpolationDone;
  49048. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  49049. _this._target = _this._effectiveTarget = target;
  49050. return _this;
  49051. }
  49052. InterpolateValueAction.prototype._prepare = function () {
  49053. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  49054. this._property = this._getProperty(this.propertyPath);
  49055. };
  49056. InterpolateValueAction.prototype.execute = function () {
  49057. var _this = this;
  49058. var scene = this._actionManager.getScene();
  49059. var keys = [
  49060. {
  49061. frame: 0,
  49062. value: this._effectiveTarget[this._property]
  49063. }, {
  49064. frame: 100,
  49065. value: this.value
  49066. }
  49067. ];
  49068. var dataType;
  49069. if (typeof this.value === "number") {
  49070. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  49071. }
  49072. else if (this.value instanceof BABYLON.Color3) {
  49073. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  49074. }
  49075. else if (this.value instanceof BABYLON.Vector3) {
  49076. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  49077. }
  49078. else if (this.value instanceof BABYLON.Matrix) {
  49079. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  49080. }
  49081. else if (this.value instanceof BABYLON.Quaternion) {
  49082. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  49083. }
  49084. else {
  49085. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  49086. return;
  49087. }
  49088. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  49089. animation.setKeys(keys);
  49090. if (this.stopOtherAnimations) {
  49091. scene.stopAnimation(this._effectiveTarget);
  49092. }
  49093. var wrapper = function () {
  49094. _this.onInterpolationDoneObservable.notifyObservers(_this);
  49095. if (_this.onInterpolationDone) {
  49096. _this.onInterpolationDone();
  49097. }
  49098. };
  49099. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  49100. };
  49101. InterpolateValueAction.prototype.serialize = function (parent) {
  49102. return _super.prototype._serialize.call(this, {
  49103. name: "InterpolateValueAction",
  49104. properties: [
  49105. BABYLON.Action._GetTargetProperty(this._target),
  49106. { name: "propertyPath", value: this.propertyPath },
  49107. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  49108. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  49109. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  49110. ]
  49111. }, parent);
  49112. };
  49113. return InterpolateValueAction;
  49114. }(BABYLON.Action));
  49115. BABYLON.InterpolateValueAction = InterpolateValueAction;
  49116. })(BABYLON || (BABYLON = {}));
  49117. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  49118. var BABYLON;
  49119. (function (BABYLON) {
  49120. var SwitchBooleanAction = /** @class */ (function (_super) {
  49121. __extends(SwitchBooleanAction, _super);
  49122. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  49123. var _this = _super.call(this, triggerOptions, condition) || this;
  49124. _this.propertyPath = propertyPath;
  49125. _this._target = _this._effectiveTarget = target;
  49126. return _this;
  49127. }
  49128. SwitchBooleanAction.prototype._prepare = function () {
  49129. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  49130. this._property = this._getProperty(this.propertyPath);
  49131. };
  49132. SwitchBooleanAction.prototype.execute = function () {
  49133. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  49134. };
  49135. SwitchBooleanAction.prototype.serialize = function (parent) {
  49136. return _super.prototype._serialize.call(this, {
  49137. name: "SwitchBooleanAction",
  49138. properties: [
  49139. BABYLON.Action._GetTargetProperty(this._target),
  49140. { name: "propertyPath", value: this.propertyPath }
  49141. ]
  49142. }, parent);
  49143. };
  49144. return SwitchBooleanAction;
  49145. }(BABYLON.Action));
  49146. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  49147. var SetStateAction = /** @class */ (function (_super) {
  49148. __extends(SetStateAction, _super);
  49149. function SetStateAction(triggerOptions, target, value, condition) {
  49150. var _this = _super.call(this, triggerOptions, condition) || this;
  49151. _this.value = value;
  49152. _this._target = target;
  49153. return _this;
  49154. }
  49155. SetStateAction.prototype.execute = function () {
  49156. this._target.state = this.value;
  49157. };
  49158. SetStateAction.prototype.serialize = function (parent) {
  49159. return _super.prototype._serialize.call(this, {
  49160. name: "SetStateAction",
  49161. properties: [
  49162. BABYLON.Action._GetTargetProperty(this._target),
  49163. { name: "value", value: this.value }
  49164. ]
  49165. }, parent);
  49166. };
  49167. return SetStateAction;
  49168. }(BABYLON.Action));
  49169. BABYLON.SetStateAction = SetStateAction;
  49170. var SetValueAction = /** @class */ (function (_super) {
  49171. __extends(SetValueAction, _super);
  49172. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  49173. var _this = _super.call(this, triggerOptions, condition) || this;
  49174. _this.propertyPath = propertyPath;
  49175. _this.value = value;
  49176. _this._target = _this._effectiveTarget = target;
  49177. return _this;
  49178. }
  49179. SetValueAction.prototype._prepare = function () {
  49180. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  49181. this._property = this._getProperty(this.propertyPath);
  49182. };
  49183. SetValueAction.prototype.execute = function () {
  49184. this._effectiveTarget[this._property] = this.value;
  49185. if (this._target.markAsDirty) {
  49186. this._target.markAsDirty(this._property);
  49187. }
  49188. };
  49189. SetValueAction.prototype.serialize = function (parent) {
  49190. return _super.prototype._serialize.call(this, {
  49191. name: "SetValueAction",
  49192. properties: [
  49193. BABYLON.Action._GetTargetProperty(this._target),
  49194. { name: "propertyPath", value: this.propertyPath },
  49195. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  49196. ]
  49197. }, parent);
  49198. };
  49199. return SetValueAction;
  49200. }(BABYLON.Action));
  49201. BABYLON.SetValueAction = SetValueAction;
  49202. var IncrementValueAction = /** @class */ (function (_super) {
  49203. __extends(IncrementValueAction, _super);
  49204. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  49205. var _this = _super.call(this, triggerOptions, condition) || this;
  49206. _this.propertyPath = propertyPath;
  49207. _this.value = value;
  49208. _this._target = _this._effectiveTarget = target;
  49209. return _this;
  49210. }
  49211. IncrementValueAction.prototype._prepare = function () {
  49212. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  49213. this._property = this._getProperty(this.propertyPath);
  49214. if (typeof this._effectiveTarget[this._property] !== "number") {
  49215. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  49216. }
  49217. };
  49218. IncrementValueAction.prototype.execute = function () {
  49219. this._effectiveTarget[this._property] += this.value;
  49220. if (this._target.markAsDirty) {
  49221. this._target.markAsDirty(this._property);
  49222. }
  49223. };
  49224. IncrementValueAction.prototype.serialize = function (parent) {
  49225. return _super.prototype._serialize.call(this, {
  49226. name: "IncrementValueAction",
  49227. properties: [
  49228. BABYLON.Action._GetTargetProperty(this._target),
  49229. { name: "propertyPath", value: this.propertyPath },
  49230. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  49231. ]
  49232. }, parent);
  49233. };
  49234. return IncrementValueAction;
  49235. }(BABYLON.Action));
  49236. BABYLON.IncrementValueAction = IncrementValueAction;
  49237. var PlayAnimationAction = /** @class */ (function (_super) {
  49238. __extends(PlayAnimationAction, _super);
  49239. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  49240. var _this = _super.call(this, triggerOptions, condition) || this;
  49241. _this.from = from;
  49242. _this.to = to;
  49243. _this.loop = loop;
  49244. _this._target = target;
  49245. return _this;
  49246. }
  49247. PlayAnimationAction.prototype._prepare = function () {
  49248. };
  49249. PlayAnimationAction.prototype.execute = function () {
  49250. var scene = this._actionManager.getScene();
  49251. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  49252. };
  49253. PlayAnimationAction.prototype.serialize = function (parent) {
  49254. return _super.prototype._serialize.call(this, {
  49255. name: "PlayAnimationAction",
  49256. properties: [
  49257. BABYLON.Action._GetTargetProperty(this._target),
  49258. { name: "from", value: String(this.from) },
  49259. { name: "to", value: String(this.to) },
  49260. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  49261. ]
  49262. }, parent);
  49263. };
  49264. return PlayAnimationAction;
  49265. }(BABYLON.Action));
  49266. BABYLON.PlayAnimationAction = PlayAnimationAction;
  49267. var StopAnimationAction = /** @class */ (function (_super) {
  49268. __extends(StopAnimationAction, _super);
  49269. function StopAnimationAction(triggerOptions, target, condition) {
  49270. var _this = _super.call(this, triggerOptions, condition) || this;
  49271. _this._target = target;
  49272. return _this;
  49273. }
  49274. StopAnimationAction.prototype._prepare = function () {
  49275. };
  49276. StopAnimationAction.prototype.execute = function () {
  49277. var scene = this._actionManager.getScene();
  49278. scene.stopAnimation(this._target);
  49279. };
  49280. StopAnimationAction.prototype.serialize = function (parent) {
  49281. return _super.prototype._serialize.call(this, {
  49282. name: "StopAnimationAction",
  49283. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  49284. }, parent);
  49285. };
  49286. return StopAnimationAction;
  49287. }(BABYLON.Action));
  49288. BABYLON.StopAnimationAction = StopAnimationAction;
  49289. var DoNothingAction = /** @class */ (function (_super) {
  49290. __extends(DoNothingAction, _super);
  49291. function DoNothingAction(triggerOptions, condition) {
  49292. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  49293. return _super.call(this, triggerOptions, condition) || this;
  49294. }
  49295. DoNothingAction.prototype.execute = function () {
  49296. };
  49297. DoNothingAction.prototype.serialize = function (parent) {
  49298. return _super.prototype._serialize.call(this, {
  49299. name: "DoNothingAction",
  49300. properties: []
  49301. }, parent);
  49302. };
  49303. return DoNothingAction;
  49304. }(BABYLON.Action));
  49305. BABYLON.DoNothingAction = DoNothingAction;
  49306. var CombineAction = /** @class */ (function (_super) {
  49307. __extends(CombineAction, _super);
  49308. function CombineAction(triggerOptions, children, condition) {
  49309. var _this = _super.call(this, triggerOptions, condition) || this;
  49310. _this.children = children;
  49311. return _this;
  49312. }
  49313. CombineAction.prototype._prepare = function () {
  49314. for (var index = 0; index < this.children.length; index++) {
  49315. this.children[index]._actionManager = this._actionManager;
  49316. this.children[index]._prepare();
  49317. }
  49318. };
  49319. CombineAction.prototype.execute = function (evt) {
  49320. for (var index = 0; index < this.children.length; index++) {
  49321. this.children[index].execute(evt);
  49322. }
  49323. };
  49324. CombineAction.prototype.serialize = function (parent) {
  49325. var serializationObject = _super.prototype._serialize.call(this, {
  49326. name: "CombineAction",
  49327. properties: [],
  49328. combine: []
  49329. }, parent);
  49330. for (var i = 0; i < this.children.length; i++) {
  49331. serializationObject.combine.push(this.children[i].serialize(null));
  49332. }
  49333. return serializationObject;
  49334. };
  49335. return CombineAction;
  49336. }(BABYLON.Action));
  49337. BABYLON.CombineAction = CombineAction;
  49338. var ExecuteCodeAction = /** @class */ (function (_super) {
  49339. __extends(ExecuteCodeAction, _super);
  49340. function ExecuteCodeAction(triggerOptions, func, condition) {
  49341. var _this = _super.call(this, triggerOptions, condition) || this;
  49342. _this.func = func;
  49343. return _this;
  49344. }
  49345. ExecuteCodeAction.prototype.execute = function (evt) {
  49346. this.func(evt);
  49347. };
  49348. return ExecuteCodeAction;
  49349. }(BABYLON.Action));
  49350. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  49351. var SetParentAction = /** @class */ (function (_super) {
  49352. __extends(SetParentAction, _super);
  49353. function SetParentAction(triggerOptions, target, parent, condition) {
  49354. var _this = _super.call(this, triggerOptions, condition) || this;
  49355. _this._target = target;
  49356. _this._parent = parent;
  49357. return _this;
  49358. }
  49359. SetParentAction.prototype._prepare = function () {
  49360. };
  49361. SetParentAction.prototype.execute = function () {
  49362. if (this._target.parent === this._parent) {
  49363. return;
  49364. }
  49365. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  49366. invertParentWorldMatrix.invert();
  49367. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  49368. this._target.parent = this._parent;
  49369. };
  49370. SetParentAction.prototype.serialize = function (parent) {
  49371. return _super.prototype._serialize.call(this, {
  49372. name: "SetParentAction",
  49373. properties: [
  49374. BABYLON.Action._GetTargetProperty(this._target),
  49375. BABYLON.Action._GetTargetProperty(this._parent),
  49376. ]
  49377. }, parent);
  49378. };
  49379. return SetParentAction;
  49380. }(BABYLON.Action));
  49381. BABYLON.SetParentAction = SetParentAction;
  49382. var PlaySoundAction = /** @class */ (function (_super) {
  49383. __extends(PlaySoundAction, _super);
  49384. function PlaySoundAction(triggerOptions, sound, condition) {
  49385. var _this = _super.call(this, triggerOptions, condition) || this;
  49386. _this._sound = sound;
  49387. return _this;
  49388. }
  49389. PlaySoundAction.prototype._prepare = function () {
  49390. };
  49391. PlaySoundAction.prototype.execute = function () {
  49392. if (this._sound !== undefined)
  49393. this._sound.play();
  49394. };
  49395. PlaySoundAction.prototype.serialize = function (parent) {
  49396. return _super.prototype._serialize.call(this, {
  49397. name: "PlaySoundAction",
  49398. properties: [{ name: "sound", value: this._sound.name }]
  49399. }, parent);
  49400. };
  49401. return PlaySoundAction;
  49402. }(BABYLON.Action));
  49403. BABYLON.PlaySoundAction = PlaySoundAction;
  49404. var StopSoundAction = /** @class */ (function (_super) {
  49405. __extends(StopSoundAction, _super);
  49406. function StopSoundAction(triggerOptions, sound, condition) {
  49407. var _this = _super.call(this, triggerOptions, condition) || this;
  49408. _this._sound = sound;
  49409. return _this;
  49410. }
  49411. StopSoundAction.prototype._prepare = function () {
  49412. };
  49413. StopSoundAction.prototype.execute = function () {
  49414. if (this._sound !== undefined)
  49415. this._sound.stop();
  49416. };
  49417. StopSoundAction.prototype.serialize = function (parent) {
  49418. return _super.prototype._serialize.call(this, {
  49419. name: "StopSoundAction",
  49420. properties: [{ name: "sound", value: this._sound.name }]
  49421. }, parent);
  49422. };
  49423. return StopSoundAction;
  49424. }(BABYLON.Action));
  49425. BABYLON.StopSoundAction = StopSoundAction;
  49426. })(BABYLON || (BABYLON = {}));
  49427. //# sourceMappingURL=babylon.directActions.js.map
  49428. var BABYLON;
  49429. (function (BABYLON) {
  49430. var SpriteManager = /** @class */ (function () {
  49431. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  49432. if (epsilon === void 0) { epsilon = 0.01; }
  49433. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  49434. this.name = name;
  49435. this.sprites = new Array();
  49436. this.renderingGroupId = 0;
  49437. this.layerMask = 0x0FFFFFFF;
  49438. this.fogEnabled = true;
  49439. this.isPickable = false;
  49440. /**
  49441. * An event triggered when the manager is disposed.
  49442. * @type {BABYLON.Observable}
  49443. */
  49444. this.onDisposeObservable = new BABYLON.Observable();
  49445. this._vertexBuffers = {};
  49446. this._capacity = capacity;
  49447. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  49448. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  49449. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  49450. if (cellSize.width && cellSize.height) {
  49451. this.cellWidth = cellSize.width;
  49452. this.cellHeight = cellSize.height;
  49453. }
  49454. else if (cellSize !== undefined) {
  49455. this.cellWidth = cellSize;
  49456. this.cellHeight = cellSize;
  49457. }
  49458. else {
  49459. return;
  49460. }
  49461. this._epsilon = epsilon;
  49462. this._scene = scene;
  49463. this._scene.spriteManagers.push(this);
  49464. var indices = [];
  49465. var index = 0;
  49466. for (var count = 0; count < capacity; count++) {
  49467. indices.push(index);
  49468. indices.push(index + 1);
  49469. indices.push(index + 2);
  49470. indices.push(index);
  49471. indices.push(index + 2);
  49472. indices.push(index + 3);
  49473. index += 4;
  49474. }
  49475. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  49476. // VBO
  49477. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  49478. this._vertexData = new Float32Array(capacity * 16 * 4);
  49479. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  49480. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  49481. var options = this._buffer.createVertexBuffer("options", 4, 4);
  49482. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  49483. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  49484. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  49485. this._vertexBuffers["options"] = options;
  49486. this._vertexBuffers["cellInfo"] = cellInfo;
  49487. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  49488. // Effects
  49489. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  49490. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  49491. }
  49492. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  49493. set: function (callback) {
  49494. if (this._onDisposeObserver) {
  49495. this.onDisposeObservable.remove(this._onDisposeObserver);
  49496. }
  49497. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  49498. },
  49499. enumerable: true,
  49500. configurable: true
  49501. });
  49502. Object.defineProperty(SpriteManager.prototype, "texture", {
  49503. get: function () {
  49504. return this._spriteTexture;
  49505. },
  49506. set: function (value) {
  49507. this._spriteTexture = value;
  49508. },
  49509. enumerable: true,
  49510. configurable: true
  49511. });
  49512. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  49513. var arrayOffset = index * 16;
  49514. if (offsetX === 0)
  49515. offsetX = this._epsilon;
  49516. else if (offsetX === 1)
  49517. offsetX = 1 - this._epsilon;
  49518. if (offsetY === 0)
  49519. offsetY = this._epsilon;
  49520. else if (offsetY === 1)
  49521. offsetY = 1 - this._epsilon;
  49522. this._vertexData[arrayOffset] = sprite.position.x;
  49523. this._vertexData[arrayOffset + 1] = sprite.position.y;
  49524. this._vertexData[arrayOffset + 2] = sprite.position.z;
  49525. this._vertexData[arrayOffset + 3] = sprite.angle;
  49526. this._vertexData[arrayOffset + 4] = sprite.width;
  49527. this._vertexData[arrayOffset + 5] = sprite.height;
  49528. this._vertexData[arrayOffset + 6] = offsetX;
  49529. this._vertexData[arrayOffset + 7] = offsetY;
  49530. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  49531. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  49532. var offset = (sprite.cellIndex / rowSize) >> 0;
  49533. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  49534. this._vertexData[arrayOffset + 11] = offset;
  49535. // Color
  49536. this._vertexData[arrayOffset + 12] = sprite.color.r;
  49537. this._vertexData[arrayOffset + 13] = sprite.color.g;
  49538. this._vertexData[arrayOffset + 14] = sprite.color.b;
  49539. this._vertexData[arrayOffset + 15] = sprite.color.a;
  49540. };
  49541. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  49542. var count = Math.min(this._capacity, this.sprites.length);
  49543. var min = BABYLON.Vector3.Zero();
  49544. var max = BABYLON.Vector3.Zero();
  49545. var distance = Number.MAX_VALUE;
  49546. var currentSprite = null;
  49547. var cameraSpacePosition = BABYLON.Vector3.Zero();
  49548. var cameraView = camera.getViewMatrix();
  49549. for (var index = 0; index < count; index++) {
  49550. var sprite = this.sprites[index];
  49551. if (!sprite) {
  49552. continue;
  49553. }
  49554. if (predicate) {
  49555. if (!predicate(sprite)) {
  49556. continue;
  49557. }
  49558. }
  49559. else if (!sprite.isPickable) {
  49560. continue;
  49561. }
  49562. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  49563. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  49564. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  49565. if (ray.intersectsBoxMinMax(min, max)) {
  49566. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  49567. if (distance > currentDistance) {
  49568. distance = currentDistance;
  49569. currentSprite = sprite;
  49570. if (fastCheck) {
  49571. break;
  49572. }
  49573. }
  49574. }
  49575. }
  49576. if (currentSprite) {
  49577. var result = new BABYLON.PickingInfo();
  49578. result.hit = true;
  49579. result.pickedSprite = currentSprite;
  49580. result.distance = distance;
  49581. return result;
  49582. }
  49583. return null;
  49584. };
  49585. SpriteManager.prototype.render = function () {
  49586. // Check
  49587. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  49588. return;
  49589. var engine = this._scene.getEngine();
  49590. var baseSize = this._spriteTexture.getBaseSize();
  49591. // Sprites
  49592. var deltaTime = engine.getDeltaTime();
  49593. var max = Math.min(this._capacity, this.sprites.length);
  49594. var rowSize = baseSize.width / this.cellWidth;
  49595. var offset = 0;
  49596. for (var index = 0; index < max; index++) {
  49597. var sprite = this.sprites[index];
  49598. if (!sprite) {
  49599. continue;
  49600. }
  49601. sprite._animate(deltaTime);
  49602. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  49603. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  49604. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  49605. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  49606. }
  49607. this._buffer.update(this._vertexData);
  49608. // Render
  49609. var effect = this._effectBase;
  49610. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  49611. effect = this._effectFog;
  49612. }
  49613. engine.enableEffect(effect);
  49614. var viewMatrix = this._scene.getViewMatrix();
  49615. effect.setTexture("diffuseSampler", this._spriteTexture);
  49616. effect.setMatrix("view", viewMatrix);
  49617. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  49618. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  49619. // Fog
  49620. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  49621. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  49622. effect.setColor3("vFogColor", this._scene.fogColor);
  49623. }
  49624. // VBOs
  49625. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  49626. // Draw order
  49627. engine.setDepthFunctionToLessOrEqual();
  49628. effect.setBool("alphaTest", true);
  49629. engine.setColorWrite(false);
  49630. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  49631. engine.setColorWrite(true);
  49632. effect.setBool("alphaTest", false);
  49633. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  49634. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  49635. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  49636. };
  49637. SpriteManager.prototype.dispose = function () {
  49638. if (this._buffer) {
  49639. this._buffer.dispose();
  49640. this._buffer = null;
  49641. }
  49642. if (this._indexBuffer) {
  49643. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  49644. this._indexBuffer = null;
  49645. }
  49646. if (this._spriteTexture) {
  49647. this._spriteTexture.dispose();
  49648. this._spriteTexture = null;
  49649. }
  49650. // Remove from scene
  49651. var index = this._scene.spriteManagers.indexOf(this);
  49652. this._scene.spriteManagers.splice(index, 1);
  49653. // Callback
  49654. this.onDisposeObservable.notifyObservers(this);
  49655. this.onDisposeObservable.clear();
  49656. };
  49657. return SpriteManager;
  49658. }());
  49659. BABYLON.SpriteManager = SpriteManager;
  49660. })(BABYLON || (BABYLON = {}));
  49661. //# sourceMappingURL=babylon.spriteManager.js.map
  49662. var BABYLON;
  49663. (function (BABYLON) {
  49664. var Sprite = /** @class */ (function () {
  49665. function Sprite(name, manager) {
  49666. this.name = name;
  49667. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  49668. this.width = 1.0;
  49669. this.height = 1.0;
  49670. this.angle = 0;
  49671. this.cellIndex = 0;
  49672. this.invertU = 0;
  49673. this.invertV = 0;
  49674. this.animations = new Array();
  49675. this.isPickable = false;
  49676. this._animationStarted = false;
  49677. this._loopAnimation = false;
  49678. this._fromIndex = 0;
  49679. this._toIndex = 0;
  49680. this._delay = 0;
  49681. this._direction = 1;
  49682. this._time = 0;
  49683. this._manager = manager;
  49684. this._manager.sprites.push(this);
  49685. this.position = BABYLON.Vector3.Zero();
  49686. }
  49687. Object.defineProperty(Sprite.prototype, "size", {
  49688. get: function () {
  49689. return this.width;
  49690. },
  49691. set: function (value) {
  49692. this.width = value;
  49693. this.height = value;
  49694. },
  49695. enumerable: true,
  49696. configurable: true
  49697. });
  49698. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  49699. this._fromIndex = from;
  49700. this._toIndex = to;
  49701. this._loopAnimation = loop;
  49702. this._delay = delay;
  49703. this._animationStarted = true;
  49704. this._direction = from < to ? 1 : -1;
  49705. this.cellIndex = from;
  49706. this._time = 0;
  49707. this._onAnimationEnd = onAnimationEnd;
  49708. };
  49709. Sprite.prototype.stopAnimation = function () {
  49710. this._animationStarted = false;
  49711. };
  49712. Sprite.prototype._animate = function (deltaTime) {
  49713. if (!this._animationStarted)
  49714. return;
  49715. this._time += deltaTime;
  49716. if (this._time > this._delay) {
  49717. this._time = this._time % this._delay;
  49718. this.cellIndex += this._direction;
  49719. if (this.cellIndex > this._toIndex) {
  49720. if (this._loopAnimation) {
  49721. this.cellIndex = this._fromIndex;
  49722. }
  49723. else {
  49724. this.cellIndex = this._toIndex;
  49725. this._animationStarted = false;
  49726. if (this._onAnimationEnd) {
  49727. this._onAnimationEnd();
  49728. }
  49729. if (this.disposeWhenFinishedAnimating) {
  49730. this.dispose();
  49731. }
  49732. }
  49733. }
  49734. }
  49735. };
  49736. Sprite.prototype.dispose = function () {
  49737. for (var i = 0; i < this._manager.sprites.length; i++) {
  49738. if (this._manager.sprites[i] == this) {
  49739. this._manager.sprites.splice(i, 1);
  49740. }
  49741. }
  49742. };
  49743. return Sprite;
  49744. }());
  49745. BABYLON.Sprite = Sprite;
  49746. })(BABYLON || (BABYLON = {}));
  49747. //# sourceMappingURL=babylon.sprite.js.map
  49748. var BABYLON;
  49749. (function (BABYLON) {
  49750. var IntersectionInfo = /** @class */ (function () {
  49751. function IntersectionInfo(bu, bv, distance) {
  49752. this.bu = bu;
  49753. this.bv = bv;
  49754. this.distance = distance;
  49755. this.faceId = 0;
  49756. this.subMeshId = 0;
  49757. }
  49758. return IntersectionInfo;
  49759. }());
  49760. BABYLON.IntersectionInfo = IntersectionInfo;
  49761. var PickingInfo = /** @class */ (function () {
  49762. function PickingInfo() {
  49763. this.hit = false;
  49764. this.distance = 0;
  49765. this.pickedPoint = null;
  49766. this.pickedMesh = null;
  49767. this.bu = 0;
  49768. this.bv = 0;
  49769. this.faceId = -1;
  49770. this.subMeshId = 0;
  49771. this.pickedSprite = null;
  49772. }
  49773. // Methods
  49774. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  49775. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  49776. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  49777. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  49778. return null;
  49779. }
  49780. var indices = this.pickedMesh.getIndices();
  49781. if (!indices) {
  49782. return null;
  49783. }
  49784. var result;
  49785. if (useVerticesNormals) {
  49786. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  49787. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  49788. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  49789. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  49790. normal0 = normal0.scale(this.bu);
  49791. normal1 = normal1.scale(this.bv);
  49792. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  49793. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  49794. }
  49795. else {
  49796. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  49797. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  49798. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  49799. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  49800. var p1p2 = vertex1.subtract(vertex2);
  49801. var p3p2 = vertex3.subtract(vertex2);
  49802. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  49803. }
  49804. if (useWorldCoordinates) {
  49805. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  49806. }
  49807. return BABYLON.Vector3.Normalize(result);
  49808. };
  49809. PickingInfo.prototype.getTextureCoordinates = function () {
  49810. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  49811. return null;
  49812. }
  49813. var indices = this.pickedMesh.getIndices();
  49814. if (!indices) {
  49815. return null;
  49816. }
  49817. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  49818. if (!uvs) {
  49819. return null;
  49820. }
  49821. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  49822. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  49823. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  49824. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  49825. uv1 = uv1.scale(this.bu);
  49826. uv2 = uv2.scale(this.bv);
  49827. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  49828. };
  49829. return PickingInfo;
  49830. }());
  49831. BABYLON.PickingInfo = PickingInfo;
  49832. })(BABYLON || (BABYLON = {}));
  49833. //# sourceMappingURL=babylon.pickingInfo.js.map
  49834. var BABYLON;
  49835. (function (BABYLON) {
  49836. var Ray = /** @class */ (function () {
  49837. function Ray(origin, direction, length) {
  49838. if (length === void 0) { length = Number.MAX_VALUE; }
  49839. this.origin = origin;
  49840. this.direction = direction;
  49841. this.length = length;
  49842. }
  49843. // Methods
  49844. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  49845. var d = 0.0;
  49846. var maxValue = Number.MAX_VALUE;
  49847. var inv;
  49848. var min;
  49849. var max;
  49850. var temp;
  49851. if (Math.abs(this.direction.x) < 0.0000001) {
  49852. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  49853. return false;
  49854. }
  49855. }
  49856. else {
  49857. inv = 1.0 / this.direction.x;
  49858. min = (minimum.x - this.origin.x) * inv;
  49859. max = (maximum.x - this.origin.x) * inv;
  49860. if (max === -Infinity) {
  49861. max = Infinity;
  49862. }
  49863. if (min > max) {
  49864. temp = min;
  49865. min = max;
  49866. max = temp;
  49867. }
  49868. d = Math.max(min, d);
  49869. maxValue = Math.min(max, maxValue);
  49870. if (d > maxValue) {
  49871. return false;
  49872. }
  49873. }
  49874. if (Math.abs(this.direction.y) < 0.0000001) {
  49875. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  49876. return false;
  49877. }
  49878. }
  49879. else {
  49880. inv = 1.0 / this.direction.y;
  49881. min = (minimum.y - this.origin.y) * inv;
  49882. max = (maximum.y - this.origin.y) * inv;
  49883. if (max === -Infinity) {
  49884. max = Infinity;
  49885. }
  49886. if (min > max) {
  49887. temp = min;
  49888. min = max;
  49889. max = temp;
  49890. }
  49891. d = Math.max(min, d);
  49892. maxValue = Math.min(max, maxValue);
  49893. if (d > maxValue) {
  49894. return false;
  49895. }
  49896. }
  49897. if (Math.abs(this.direction.z) < 0.0000001) {
  49898. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  49899. return false;
  49900. }
  49901. }
  49902. else {
  49903. inv = 1.0 / this.direction.z;
  49904. min = (minimum.z - this.origin.z) * inv;
  49905. max = (maximum.z - this.origin.z) * inv;
  49906. if (max === -Infinity) {
  49907. max = Infinity;
  49908. }
  49909. if (min > max) {
  49910. temp = min;
  49911. min = max;
  49912. max = temp;
  49913. }
  49914. d = Math.max(min, d);
  49915. maxValue = Math.min(max, maxValue);
  49916. if (d > maxValue) {
  49917. return false;
  49918. }
  49919. }
  49920. return true;
  49921. };
  49922. Ray.prototype.intersectsBox = function (box) {
  49923. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  49924. };
  49925. Ray.prototype.intersectsSphere = function (sphere) {
  49926. var x = sphere.center.x - this.origin.x;
  49927. var y = sphere.center.y - this.origin.y;
  49928. var z = sphere.center.z - this.origin.z;
  49929. var pyth = (x * x) + (y * y) + (z * z);
  49930. var rr = sphere.radius * sphere.radius;
  49931. if (pyth <= rr) {
  49932. return true;
  49933. }
  49934. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  49935. if (dot < 0.0) {
  49936. return false;
  49937. }
  49938. var temp = pyth - (dot * dot);
  49939. return temp <= rr;
  49940. };
  49941. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  49942. if (!this._edge1) {
  49943. this._edge1 = BABYLON.Vector3.Zero();
  49944. this._edge2 = BABYLON.Vector3.Zero();
  49945. this._pvec = BABYLON.Vector3.Zero();
  49946. this._tvec = BABYLON.Vector3.Zero();
  49947. this._qvec = BABYLON.Vector3.Zero();
  49948. }
  49949. vertex1.subtractToRef(vertex0, this._edge1);
  49950. vertex2.subtractToRef(vertex0, this._edge2);
  49951. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  49952. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  49953. if (det === 0) {
  49954. return null;
  49955. }
  49956. var invdet = 1 / det;
  49957. this.origin.subtractToRef(vertex0, this._tvec);
  49958. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  49959. if (bu < 0 || bu > 1.0) {
  49960. return null;
  49961. }
  49962. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  49963. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  49964. if (bv < 0 || bu + bv > 1.0) {
  49965. return null;
  49966. }
  49967. //check if the distance is longer than the predefined length.
  49968. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  49969. if (distance > this.length) {
  49970. return null;
  49971. }
  49972. return new BABYLON.IntersectionInfo(bu, bv, distance);
  49973. };
  49974. Ray.prototype.intersectsPlane = function (plane) {
  49975. var distance;
  49976. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  49977. if (Math.abs(result1) < 9.99999997475243E-07) {
  49978. return null;
  49979. }
  49980. else {
  49981. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  49982. distance = (-plane.d - result2) / result1;
  49983. if (distance < 0.0) {
  49984. if (distance < -9.99999997475243E-07) {
  49985. return null;
  49986. }
  49987. else {
  49988. return 0;
  49989. }
  49990. }
  49991. return distance;
  49992. }
  49993. };
  49994. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  49995. var tm = BABYLON.Tmp.Matrix[0];
  49996. mesh.getWorldMatrix().invertToRef(tm);
  49997. if (this._tmpRay) {
  49998. Ray.TransformToRef(this, tm, this._tmpRay);
  49999. }
  50000. else {
  50001. this._tmpRay = Ray.Transform(this, tm);
  50002. }
  50003. return mesh.intersects(this._tmpRay, fastCheck);
  50004. };
  50005. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  50006. if (results) {
  50007. results.length = 0;
  50008. }
  50009. else {
  50010. results = [];
  50011. }
  50012. for (var i = 0; i < meshes.length; i++) {
  50013. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  50014. if (pickInfo.hit) {
  50015. results.push(pickInfo);
  50016. }
  50017. }
  50018. results.sort(this._comparePickingInfo);
  50019. return results;
  50020. };
  50021. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  50022. if (pickingInfoA.distance < pickingInfoB.distance) {
  50023. return -1;
  50024. }
  50025. else if (pickingInfoA.distance > pickingInfoB.distance) {
  50026. return 1;
  50027. }
  50028. else {
  50029. return 0;
  50030. }
  50031. };
  50032. /**
  50033. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  50034. * @param sega the first point of the segment to test the intersection against
  50035. * @param segb the second point of the segment to test the intersection against
  50036. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  50037. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  50038. */
  50039. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  50040. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  50041. var u = segb.subtract(sega);
  50042. var v = rsegb.subtract(this.origin);
  50043. var w = sega.subtract(this.origin);
  50044. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  50045. var b = BABYLON.Vector3.Dot(u, v);
  50046. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  50047. var d = BABYLON.Vector3.Dot(u, w);
  50048. var e = BABYLON.Vector3.Dot(v, w);
  50049. var D = a * c - b * b; // always >= 0
  50050. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  50051. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  50052. // compute the line parameters of the two closest points
  50053. if (D < Ray.smallnum) {
  50054. sN = 0.0; // force using point P0 on segment S1
  50055. sD = 1.0; // to prevent possible division by 0.0 later
  50056. tN = e;
  50057. tD = c;
  50058. }
  50059. else {
  50060. sN = (b * e - c * d);
  50061. tN = (a * e - b * d);
  50062. if (sN < 0.0) {
  50063. sN = 0.0;
  50064. tN = e;
  50065. tD = c;
  50066. }
  50067. else if (sN > sD) {
  50068. sN = sD;
  50069. tN = e + b;
  50070. tD = c;
  50071. }
  50072. }
  50073. if (tN < 0.0) {
  50074. tN = 0.0;
  50075. // recompute sc for this edge
  50076. if (-d < 0.0) {
  50077. sN = 0.0;
  50078. }
  50079. else if (-d > a)
  50080. sN = sD;
  50081. else {
  50082. sN = -d;
  50083. sD = a;
  50084. }
  50085. }
  50086. else if (tN > tD) {
  50087. tN = tD;
  50088. // recompute sc for this edge
  50089. if ((-d + b) < 0.0) {
  50090. sN = 0;
  50091. }
  50092. else if ((-d + b) > a) {
  50093. sN = sD;
  50094. }
  50095. else {
  50096. sN = (-d + b);
  50097. sD = a;
  50098. }
  50099. }
  50100. // finally do the division to get sc and tc
  50101. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  50102. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  50103. // get the difference of the two closest points
  50104. var qtc = v.multiplyByFloats(tc, tc, tc);
  50105. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  50106. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  50107. if (isIntersected) {
  50108. return qtc.length();
  50109. }
  50110. return -1;
  50111. };
  50112. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  50113. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  50114. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  50115. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  50116. this.direction.normalize();
  50117. return this;
  50118. };
  50119. // Statics
  50120. Ray.Zero = function () {
  50121. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  50122. };
  50123. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  50124. var result = Ray.Zero();
  50125. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  50126. };
  50127. /**
  50128. * Function will create a new transformed ray starting from origin and ending at the end point. Ray's length will be set, and ray will be
  50129. * transformed to the given world matrix.
  50130. * @param origin The origin point
  50131. * @param end The end point
  50132. * @param world a matrix to transform the ray to. Default is the identity matrix.
  50133. */
  50134. Ray.CreateNewFromTo = function (origin, end, world) {
  50135. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  50136. var direction = end.subtract(origin);
  50137. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  50138. direction.normalize();
  50139. return Ray.Transform(new Ray(origin, direction, length), world);
  50140. };
  50141. Ray.Transform = function (ray, matrix) {
  50142. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  50143. Ray.TransformToRef(ray, matrix, result);
  50144. return result;
  50145. };
  50146. Ray.TransformToRef = function (ray, matrix, result) {
  50147. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  50148. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  50149. result.length = ray.length;
  50150. var dir = result.direction;
  50151. var len = dir.length();
  50152. if (!(len === 0 || len === 1)) {
  50153. var num = 1.0 / len;
  50154. dir.x *= num;
  50155. dir.y *= num;
  50156. dir.z *= num;
  50157. result.length *= len;
  50158. }
  50159. };
  50160. Ray.smallnum = 0.00000001;
  50161. Ray.rayl = 10e8;
  50162. return Ray;
  50163. }());
  50164. BABYLON.Ray = Ray;
  50165. })(BABYLON || (BABYLON = {}));
  50166. //# sourceMappingURL=babylon.ray.js.map
  50167. var BABYLON;
  50168. (function (BABYLON) {
  50169. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  50170. if (boxMin.x > sphereCenter.x + sphereRadius)
  50171. return false;
  50172. if (sphereCenter.x - sphereRadius > boxMax.x)
  50173. return false;
  50174. if (boxMin.y > sphereCenter.y + sphereRadius)
  50175. return false;
  50176. if (sphereCenter.y - sphereRadius > boxMax.y)
  50177. return false;
  50178. if (boxMin.z > sphereCenter.z + sphereRadius)
  50179. return false;
  50180. if (sphereCenter.z - sphereRadius > boxMax.z)
  50181. return false;
  50182. return true;
  50183. };
  50184. var getLowestRoot = (function () {
  50185. var result = { root: 0, found: false };
  50186. return function (a, b, c, maxR) {
  50187. result.root = 0;
  50188. result.found = false;
  50189. var determinant = b * b - 4.0 * a * c;
  50190. if (determinant < 0)
  50191. return result;
  50192. var sqrtD = Math.sqrt(determinant);
  50193. var r1 = (-b - sqrtD) / (2.0 * a);
  50194. var r2 = (-b + sqrtD) / (2.0 * a);
  50195. if (r1 > r2) {
  50196. var temp = r2;
  50197. r2 = r1;
  50198. r1 = temp;
  50199. }
  50200. if (r1 > 0 && r1 < maxR) {
  50201. result.root = r1;
  50202. result.found = true;
  50203. return result;
  50204. }
  50205. if (r2 > 0 && r2 < maxR) {
  50206. result.root = r2;
  50207. result.found = true;
  50208. return result;
  50209. }
  50210. return result;
  50211. };
  50212. })();
  50213. var Collider = /** @class */ (function () {
  50214. function Collider() {
  50215. this._collisionPoint = BABYLON.Vector3.Zero();
  50216. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  50217. this._tempVector = BABYLON.Vector3.Zero();
  50218. this._tempVector2 = BABYLON.Vector3.Zero();
  50219. this._tempVector3 = BABYLON.Vector3.Zero();
  50220. this._tempVector4 = BABYLON.Vector3.Zero();
  50221. this._edge = BABYLON.Vector3.Zero();
  50222. this._baseToVertex = BABYLON.Vector3.Zero();
  50223. this._destinationPoint = BABYLON.Vector3.Zero();
  50224. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  50225. this._displacementVector = BABYLON.Vector3.Zero();
  50226. this._radius = BABYLON.Vector3.One();
  50227. this._retry = 0;
  50228. this._basePointWorld = BABYLON.Vector3.Zero();
  50229. this._velocityWorld = BABYLON.Vector3.Zero();
  50230. this._normalizedVelocity = BABYLON.Vector3.Zero();
  50231. this._collisionMask = -1;
  50232. }
  50233. Object.defineProperty(Collider.prototype, "collisionMask", {
  50234. get: function () {
  50235. return this._collisionMask;
  50236. },
  50237. set: function (mask) {
  50238. this._collisionMask = !isNaN(mask) ? mask : -1;
  50239. },
  50240. enumerable: true,
  50241. configurable: true
  50242. });
  50243. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  50244. /**
  50245. * Gets the plane normal used to compute the sliding response (in local space)
  50246. */
  50247. get: function () {
  50248. return this._slidePlaneNormal;
  50249. },
  50250. enumerable: true,
  50251. configurable: true
  50252. });
  50253. // Methods
  50254. Collider.prototype._initialize = function (source, dir, e) {
  50255. this._velocity = dir;
  50256. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  50257. this._basePoint = source;
  50258. source.multiplyToRef(this._radius, this._basePointWorld);
  50259. dir.multiplyToRef(this._radius, this._velocityWorld);
  50260. this._velocityWorldLength = this._velocityWorld.length();
  50261. this._epsilon = e;
  50262. this.collisionFound = false;
  50263. };
  50264. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  50265. pa.subtractToRef(point, this._tempVector);
  50266. pb.subtractToRef(point, this._tempVector2);
  50267. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  50268. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  50269. if (d < 0)
  50270. return false;
  50271. pc.subtractToRef(point, this._tempVector3);
  50272. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  50273. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  50274. if (d < 0)
  50275. return false;
  50276. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  50277. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  50278. return d >= 0;
  50279. };
  50280. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  50281. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  50282. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  50283. if (distance > this._velocityWorldLength + max + sphereRadius) {
  50284. return false;
  50285. }
  50286. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  50287. return false;
  50288. return true;
  50289. };
  50290. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  50291. var t0;
  50292. var embeddedInPlane = false;
  50293. //defensive programming, actually not needed.
  50294. if (!trianglePlaneArray) {
  50295. trianglePlaneArray = [];
  50296. }
  50297. if (!trianglePlaneArray[faceIndex]) {
  50298. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  50299. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  50300. }
  50301. var trianglePlane = trianglePlaneArray[faceIndex];
  50302. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  50303. return;
  50304. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  50305. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  50306. if (normalDotVelocity == 0) {
  50307. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  50308. return;
  50309. embeddedInPlane = true;
  50310. t0 = 0;
  50311. }
  50312. else {
  50313. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  50314. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  50315. if (t0 > t1) {
  50316. var temp = t1;
  50317. t1 = t0;
  50318. t0 = temp;
  50319. }
  50320. if (t0 > 1.0 || t1 < 0.0)
  50321. return;
  50322. if (t0 < 0)
  50323. t0 = 0;
  50324. if (t0 > 1.0)
  50325. t0 = 1.0;
  50326. }
  50327. this._collisionPoint.copyFromFloats(0, 0, 0);
  50328. var found = false;
  50329. var t = 1.0;
  50330. if (!embeddedInPlane) {
  50331. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  50332. this._velocity.scaleToRef(t0, this._tempVector);
  50333. this._planeIntersectionPoint.addInPlace(this._tempVector);
  50334. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  50335. found = true;
  50336. t = t0;
  50337. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  50338. }
  50339. }
  50340. if (!found) {
  50341. var velocitySquaredLength = this._velocity.lengthSquared();
  50342. var a = velocitySquaredLength;
  50343. this._basePoint.subtractToRef(p1, this._tempVector);
  50344. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  50345. var c = this._tempVector.lengthSquared() - 1.0;
  50346. var lowestRoot = getLowestRoot(a, b, c, t);
  50347. if (lowestRoot.found) {
  50348. t = lowestRoot.root;
  50349. found = true;
  50350. this._collisionPoint.copyFrom(p1);
  50351. }
  50352. this._basePoint.subtractToRef(p2, this._tempVector);
  50353. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  50354. c = this._tempVector.lengthSquared() - 1.0;
  50355. lowestRoot = getLowestRoot(a, b, c, t);
  50356. if (lowestRoot.found) {
  50357. t = lowestRoot.root;
  50358. found = true;
  50359. this._collisionPoint.copyFrom(p2);
  50360. }
  50361. this._basePoint.subtractToRef(p3, this._tempVector);
  50362. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  50363. c = this._tempVector.lengthSquared() - 1.0;
  50364. lowestRoot = getLowestRoot(a, b, c, t);
  50365. if (lowestRoot.found) {
  50366. t = lowestRoot.root;
  50367. found = true;
  50368. this._collisionPoint.copyFrom(p3);
  50369. }
  50370. p2.subtractToRef(p1, this._edge);
  50371. p1.subtractToRef(this._basePoint, this._baseToVertex);
  50372. var edgeSquaredLength = this._edge.lengthSquared();
  50373. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  50374. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  50375. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  50376. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  50377. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  50378. lowestRoot = getLowestRoot(a, b, c, t);
  50379. if (lowestRoot.found) {
  50380. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  50381. if (f >= 0.0 && f <= 1.0) {
  50382. t = lowestRoot.root;
  50383. found = true;
  50384. this._edge.scaleInPlace(f);
  50385. p1.addToRef(this._edge, this._collisionPoint);
  50386. }
  50387. }
  50388. p3.subtractToRef(p2, this._edge);
  50389. p2.subtractToRef(this._basePoint, this._baseToVertex);
  50390. edgeSquaredLength = this._edge.lengthSquared();
  50391. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  50392. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  50393. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  50394. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  50395. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  50396. lowestRoot = getLowestRoot(a, b, c, t);
  50397. if (lowestRoot.found) {
  50398. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  50399. if (f >= 0.0 && f <= 1.0) {
  50400. t = lowestRoot.root;
  50401. found = true;
  50402. this._edge.scaleInPlace(f);
  50403. p2.addToRef(this._edge, this._collisionPoint);
  50404. }
  50405. }
  50406. p1.subtractToRef(p3, this._edge);
  50407. p3.subtractToRef(this._basePoint, this._baseToVertex);
  50408. edgeSquaredLength = this._edge.lengthSquared();
  50409. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  50410. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  50411. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  50412. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  50413. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  50414. lowestRoot = getLowestRoot(a, b, c, t);
  50415. if (lowestRoot.found) {
  50416. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  50417. if (f >= 0.0 && f <= 1.0) {
  50418. t = lowestRoot.root;
  50419. found = true;
  50420. this._edge.scaleInPlace(f);
  50421. p3.addToRef(this._edge, this._collisionPoint);
  50422. }
  50423. }
  50424. }
  50425. if (found) {
  50426. var distToCollision = t * this._velocity.length();
  50427. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  50428. if (!this.intersectionPoint) {
  50429. this.intersectionPoint = this._collisionPoint.clone();
  50430. }
  50431. else {
  50432. this.intersectionPoint.copyFrom(this._collisionPoint);
  50433. }
  50434. this._nearestDistance = distToCollision;
  50435. this.collisionFound = true;
  50436. }
  50437. }
  50438. };
  50439. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  50440. for (var i = indexStart; i < indexEnd; i += 3) {
  50441. var p1 = pts[indices[i] - decal];
  50442. var p2 = pts[indices[i + 1] - decal];
  50443. var p3 = pts[indices[i + 2] - decal];
  50444. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  50445. }
  50446. };
  50447. Collider.prototype._getResponse = function (pos, vel) {
  50448. pos.addToRef(vel, this._destinationPoint);
  50449. vel.scaleInPlace((this._nearestDistance / vel.length()));
  50450. this._basePoint.addToRef(vel, pos);
  50451. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  50452. this._slidePlaneNormal.normalize();
  50453. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  50454. pos.addInPlace(this._displacementVector);
  50455. this.intersectionPoint.addInPlace(this._displacementVector);
  50456. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  50457. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  50458. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  50459. };
  50460. return Collider;
  50461. }());
  50462. BABYLON.Collider = Collider;
  50463. })(BABYLON || (BABYLON = {}));
  50464. //# sourceMappingURL=babylon.collider.js.map
  50465. var BABYLON;
  50466. (function (BABYLON) {
  50467. //WebWorker code will be inserted to this variable.
  50468. BABYLON.CollisionWorker = "";
  50469. var WorkerTaskType;
  50470. (function (WorkerTaskType) {
  50471. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  50472. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  50473. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  50474. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  50475. var WorkerReplyType;
  50476. (function (WorkerReplyType) {
  50477. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  50478. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  50479. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  50480. var CollisionCoordinatorWorker = /** @class */ (function () {
  50481. function CollisionCoordinatorWorker() {
  50482. var _this = this;
  50483. this._scaledPosition = BABYLON.Vector3.Zero();
  50484. this._scaledVelocity = BABYLON.Vector3.Zero();
  50485. this.onMeshUpdated = function (transformNode) {
  50486. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  50487. };
  50488. this.onGeometryUpdated = function (geometry) {
  50489. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  50490. };
  50491. this._afterRender = function () {
  50492. if (!_this._init)
  50493. return;
  50494. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  50495. return;
  50496. }
  50497. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  50498. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  50499. if (_this._runningUpdated > 4) {
  50500. return;
  50501. }
  50502. ++_this._runningUpdated;
  50503. var payload = {
  50504. updatedMeshes: _this._addUpdateMeshesList,
  50505. updatedGeometries: _this._addUpdateGeometriesList,
  50506. removedGeometries: _this._toRemoveGeometryArray,
  50507. removedMeshes: _this._toRemoveMeshesArray
  50508. };
  50509. var message = {
  50510. payload: payload,
  50511. taskType: WorkerTaskType.UPDATE
  50512. };
  50513. var serializable = [];
  50514. for (var id in payload.updatedGeometries) {
  50515. if (payload.updatedGeometries.hasOwnProperty(id)) {
  50516. //prepare transferables
  50517. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  50518. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  50519. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  50520. }
  50521. }
  50522. _this._worker.postMessage(message, serializable);
  50523. _this._addUpdateMeshesList = {};
  50524. _this._addUpdateGeometriesList = {};
  50525. _this._toRemoveGeometryArray = [];
  50526. _this._toRemoveMeshesArray = [];
  50527. };
  50528. this._onMessageFromWorker = function (e) {
  50529. var returnData = e.data;
  50530. if (returnData.error != WorkerReplyType.SUCCESS) {
  50531. //TODO what errors can be returned from the worker?
  50532. BABYLON.Tools.Warn("error returned from worker!");
  50533. return;
  50534. }
  50535. switch (returnData.taskType) {
  50536. case WorkerTaskType.INIT:
  50537. _this._init = true;
  50538. //Update the worked with ALL of the scene's current state
  50539. _this._scene.meshes.forEach(function (mesh) {
  50540. _this.onMeshAdded(mesh);
  50541. });
  50542. _this._scene.getGeometries().forEach(function (geometry) {
  50543. _this.onGeometryAdded(geometry);
  50544. });
  50545. break;
  50546. case WorkerTaskType.UPDATE:
  50547. _this._runningUpdated--;
  50548. break;
  50549. case WorkerTaskType.COLLIDE:
  50550. var returnPayload = returnData.payload;
  50551. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  50552. return;
  50553. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  50554. if (callback) {
  50555. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  50556. if (mesh) {
  50557. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  50558. }
  50559. }
  50560. //cleanup
  50561. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  50562. break;
  50563. }
  50564. };
  50565. this._collisionsCallbackArray = [];
  50566. this._init = false;
  50567. this._runningUpdated = 0;
  50568. this._addUpdateMeshesList = {};
  50569. this._addUpdateGeometriesList = {};
  50570. this._toRemoveGeometryArray = [];
  50571. this._toRemoveMeshesArray = [];
  50572. }
  50573. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  50574. if (!this._init)
  50575. return;
  50576. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  50577. return;
  50578. position.divideToRef(collider._radius, this._scaledPosition);
  50579. displacement.divideToRef(collider._radius, this._scaledVelocity);
  50580. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  50581. var payload = {
  50582. collider: {
  50583. position: this._scaledPosition.asArray(),
  50584. velocity: this._scaledVelocity.asArray(),
  50585. radius: collider._radius.asArray()
  50586. },
  50587. collisionId: collisionIndex,
  50588. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  50589. maximumRetry: maximumRetry
  50590. };
  50591. var message = {
  50592. payload: payload,
  50593. taskType: WorkerTaskType.COLLIDE
  50594. };
  50595. this._worker.postMessage(message);
  50596. };
  50597. CollisionCoordinatorWorker.prototype.init = function (scene) {
  50598. this._scene = scene;
  50599. this._scene.registerAfterRender(this._afterRender);
  50600. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  50601. this._worker = new Worker(workerUrl);
  50602. this._worker.onmessage = this._onMessageFromWorker;
  50603. var message = {
  50604. payload: {},
  50605. taskType: WorkerTaskType.INIT
  50606. };
  50607. this._worker.postMessage(message);
  50608. };
  50609. CollisionCoordinatorWorker.prototype.destroy = function () {
  50610. this._scene.unregisterAfterRender(this._afterRender);
  50611. this._worker.terminate();
  50612. };
  50613. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  50614. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  50615. this.onMeshUpdated(mesh);
  50616. };
  50617. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  50618. this._toRemoveMeshesArray.push(mesh.uniqueId);
  50619. };
  50620. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  50621. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  50622. geometry.onGeometryUpdated = this.onGeometryUpdated;
  50623. this.onGeometryUpdated(geometry);
  50624. };
  50625. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  50626. this._toRemoveGeometryArray.push(geometry.id);
  50627. };
  50628. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  50629. var submeshes = [];
  50630. if (mesh.subMeshes) {
  50631. submeshes = mesh.subMeshes.map(function (sm, idx) {
  50632. var boundingInfo = sm.getBoundingInfo();
  50633. return {
  50634. position: idx,
  50635. verticesStart: sm.verticesStart,
  50636. verticesCount: sm.verticesCount,
  50637. indexStart: sm.indexStart,
  50638. indexCount: sm.indexCount,
  50639. hasMaterial: !!sm.getMaterial(),
  50640. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  50641. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  50642. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  50643. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  50644. };
  50645. });
  50646. }
  50647. var geometryId = null;
  50648. if (mesh instanceof BABYLON.Mesh) {
  50649. var geometry = mesh.geometry;
  50650. geometryId = geometry ? geometry.id : null;
  50651. }
  50652. else if (mesh instanceof BABYLON.InstancedMesh) {
  50653. var geometry = mesh.sourceMesh && mesh.sourceMesh.geometry;
  50654. geometryId = geometry ? geometry.id : null;
  50655. }
  50656. var boundingInfo = mesh.getBoundingInfo();
  50657. return {
  50658. uniqueId: mesh.uniqueId,
  50659. id: mesh.id,
  50660. name: mesh.name,
  50661. geometryId: geometryId,
  50662. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  50663. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  50664. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  50665. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  50666. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  50667. subMeshes: submeshes,
  50668. checkCollisions: mesh.checkCollisions
  50669. };
  50670. };
  50671. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  50672. return {
  50673. id: geometry.id,
  50674. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  50675. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  50676. indices: new Uint32Array(geometry.getIndices() || []),
  50677. };
  50678. };
  50679. return CollisionCoordinatorWorker;
  50680. }());
  50681. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  50682. var CollisionCoordinatorLegacy = /** @class */ (function () {
  50683. function CollisionCoordinatorLegacy() {
  50684. this._scaledPosition = BABYLON.Vector3.Zero();
  50685. this._scaledVelocity = BABYLON.Vector3.Zero();
  50686. this._finalPosition = BABYLON.Vector3.Zero();
  50687. }
  50688. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  50689. position.divideToRef(collider._radius, this._scaledPosition);
  50690. displacement.divideToRef(collider._radius, this._scaledVelocity);
  50691. collider.collidedMesh = null;
  50692. collider._retry = 0;
  50693. collider._initialVelocity = this._scaledVelocity;
  50694. collider._initialPosition = this._scaledPosition;
  50695. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  50696. this._finalPosition.multiplyInPlace(collider._radius);
  50697. //run the callback
  50698. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  50699. };
  50700. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  50701. this._scene = scene;
  50702. };
  50703. CollisionCoordinatorLegacy.prototype.destroy = function () {
  50704. //Legacy need no destruction method.
  50705. };
  50706. //No update in legacy mode
  50707. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  50708. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  50709. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  50710. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  50711. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  50712. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  50713. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  50714. if (excludedMesh === void 0) { excludedMesh = null; }
  50715. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  50716. if (collider._retry >= maximumRetry) {
  50717. finalPosition.copyFrom(position);
  50718. return;
  50719. }
  50720. // Check if this is a mesh else camera or -1
  50721. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  50722. collider._initialize(position, velocity, closeDistance);
  50723. // Check all meshes
  50724. for (var index = 0; index < this._scene.meshes.length; index++) {
  50725. var mesh = this._scene.meshes[index];
  50726. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  50727. mesh._checkCollision(collider);
  50728. }
  50729. }
  50730. if (!collider.collisionFound) {
  50731. position.addToRef(velocity, finalPosition);
  50732. return;
  50733. }
  50734. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  50735. collider._getResponse(position, velocity);
  50736. }
  50737. if (velocity.length() <= closeDistance) {
  50738. finalPosition.copyFrom(position);
  50739. return;
  50740. }
  50741. collider._retry++;
  50742. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  50743. };
  50744. return CollisionCoordinatorLegacy;
  50745. }());
  50746. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  50747. })(BABYLON || (BABYLON = {}));
  50748. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  50749. var BABYLON;
  50750. (function (BABYLON) {
  50751. /**
  50752. * A particle represents one of the element emitted by a particle system.
  50753. * This is mainly define by its coordinates, direction, velocity and age.
  50754. */
  50755. var Particle = /** @class */ (function () {
  50756. /**
  50757. * Creates a new instance of @see Particle
  50758. * @param particleSystem the particle system the particle belongs to
  50759. */
  50760. function Particle(
  50761. /**
  50762. * particleSystem the particle system the particle belongs to.
  50763. */
  50764. particleSystem) {
  50765. this.particleSystem = particleSystem;
  50766. /**
  50767. * The world position of the particle in the scene.
  50768. */
  50769. this.position = BABYLON.Vector3.Zero();
  50770. /**
  50771. * The world direction of the particle in the scene.
  50772. */
  50773. this.direction = BABYLON.Vector3.Zero();
  50774. /**
  50775. * The color of the particle.
  50776. */
  50777. this.color = new BABYLON.Color4(0, 0, 0, 0);
  50778. /**
  50779. * The color change of the particle per step.
  50780. */
  50781. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  50782. /**
  50783. * Defines how long will the life of the particle be.
  50784. */
  50785. this.lifeTime = 1.0;
  50786. /**
  50787. * The current age of the particle.
  50788. */
  50789. this.age = 0;
  50790. /**
  50791. * The current size of the particle.
  50792. */
  50793. this.size = 0;
  50794. /**
  50795. * The current angle of the particle.
  50796. */
  50797. this.angle = 0;
  50798. /**
  50799. * Defines how fast is the angle changing.
  50800. */
  50801. this.angularSpeed = 0;
  50802. /**
  50803. * Defines the cell index used by the particle to be rendered from a sprite.
  50804. */
  50805. this.cellIndex = 0;
  50806. this._currentFrameCounter = 0;
  50807. if (!this.particleSystem.isAnimationSheetEnabled) {
  50808. return;
  50809. }
  50810. this.updateCellInfoFromSystem();
  50811. }
  50812. Particle.prototype.updateCellInfoFromSystem = function () {
  50813. this.cellIndex = this.particleSystem.startSpriteCellID;
  50814. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  50815. this.updateCellIndex = this._updateCellIndexWithSpeedCalculated;
  50816. }
  50817. else {
  50818. this.updateCellIndex = this._updateCellIndexWithCustomSpeed;
  50819. }
  50820. };
  50821. Particle.prototype._updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  50822. // (ageOffset / scaledUpdateSpeed) / available cells
  50823. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  50824. this._currentFrameCounter += scaledUpdateSpeed;
  50825. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  50826. this._currentFrameCounter = 0;
  50827. this.cellIndex++;
  50828. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  50829. this.cellIndex = this.particleSystem.endSpriteCellID;
  50830. }
  50831. }
  50832. };
  50833. Particle.prototype._updateCellIndexWithCustomSpeed = function () {
  50834. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  50835. this.cellIndex++;
  50836. this._currentFrameCounter = 0;
  50837. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  50838. if (this.particleSystem.spriteCellLoop) {
  50839. this.cellIndex = this.particleSystem.startSpriteCellID;
  50840. }
  50841. else {
  50842. this.cellIndex = this.particleSystem.endSpriteCellID;
  50843. }
  50844. }
  50845. }
  50846. else {
  50847. this._currentFrameCounter++;
  50848. }
  50849. };
  50850. /**
  50851. * Copy the properties of particle to another one.
  50852. * @param other the particle to copy the information to.
  50853. */
  50854. Particle.prototype.copyTo = function (other) {
  50855. other.position.copyFrom(this.position);
  50856. other.direction.copyFrom(this.direction);
  50857. other.color.copyFrom(this.color);
  50858. other.colorStep.copyFrom(this.colorStep);
  50859. other.lifeTime = this.lifeTime;
  50860. other.age = this.age;
  50861. other.size = this.size;
  50862. other.angle = this.angle;
  50863. other.angularSpeed = this.angularSpeed;
  50864. other.particleSystem = this.particleSystem;
  50865. other.cellIndex = this.cellIndex;
  50866. };
  50867. return Particle;
  50868. }());
  50869. BABYLON.Particle = Particle;
  50870. })(BABYLON || (BABYLON = {}));
  50871. //# sourceMappingURL=babylon.particle.js.map
  50872. var BABYLON;
  50873. (function (BABYLON) {
  50874. /**
  50875. * This represents a particle system in Babylon.
  50876. * Particles are often small sprites used to simulate hard-to-reproduce phenomena like fire, smoke, water, or abstract visual effects like magic glitter and faery dust.
  50877. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  50878. * @example https://doc.babylonjs.com/babylon101/particles
  50879. */
  50880. var ParticleSystem = /** @class */ (function () {
  50881. /**
  50882. * Instantiates a particle system.
  50883. * Particles are often small sprites used to simulate hard-to-reproduce phenomena like fire, smoke, water, or abstract visual effects like magic glitter and faery dust.
  50884. * @param name The name of the particle system
  50885. * @param capacity The max number of particles alive at the same time
  50886. * @param scene The scene the particle system belongs to
  50887. * @param customEffect a custom effect used to change the way particles are rendered by default
  50888. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  50889. * @param epsilon Offset used to render the particles
  50890. */
  50891. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  50892. if (customEffect === void 0) { customEffect = null; }
  50893. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  50894. if (epsilon === void 0) { epsilon = 0.01; }
  50895. var _this = this;
  50896. /**
  50897. * List of animations used by the particle system.
  50898. */
  50899. this.animations = [];
  50900. /**
  50901. * The rendering group used by the Particle system to chose when to render.
  50902. */
  50903. this.renderingGroupId = 0;
  50904. /**
  50905. * The emitter represents the Mesh or position we are attaching the particle system to.
  50906. */
  50907. this.emitter = null;
  50908. /**
  50909. * The maximum number of particles to emit per frame
  50910. */
  50911. this.emitRate = 10;
  50912. /**
  50913. * If you want to launch only a few particles at once, that can be done, as well.
  50914. */
  50915. this.manualEmitCount = -1;
  50916. /**
  50917. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  50918. */
  50919. this.updateSpeed = 0.01;
  50920. /**
  50921. * The amount of time the particle system is running (depends of the overall update speed).
  50922. */
  50923. this.targetStopDuration = 0;
  50924. /**
  50925. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  50926. */
  50927. this.disposeOnStop = false;
  50928. /**
  50929. * Minimum power of emitting particles.
  50930. */
  50931. this.minEmitPower = 1;
  50932. /**
  50933. * Maximum power of emitting particles.
  50934. */
  50935. this.maxEmitPower = 1;
  50936. /**
  50937. * Minimum life time of emitting particles.
  50938. */
  50939. this.minLifeTime = 1;
  50940. /**
  50941. * Maximum life time of emitting particles.
  50942. */
  50943. this.maxLifeTime = 1;
  50944. /**
  50945. * Minimum Size of emitting particles.
  50946. */
  50947. this.minSize = 1;
  50948. /**
  50949. * Maximum Size of emitting particles.
  50950. */
  50951. this.maxSize = 1;
  50952. /**
  50953. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  50954. */
  50955. this.minAngularSpeed = 0;
  50956. /**
  50957. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  50958. */
  50959. this.maxAngularSpeed = 0;
  50960. /**
  50961. * The layer mask we are rendering the particles through.
  50962. */
  50963. this.layerMask = 0x0FFFFFFF;
  50964. /**
  50965. * This can help using your own shader to render the particle system.
  50966. * The according effect will be created
  50967. */
  50968. this.customShader = null;
  50969. /**
  50970. * By default particle system starts as soon as they are created. This prevents the
  50971. * automatic start to happen and let you decide when to start emitting particles.
  50972. */
  50973. this.preventAutoStart = false;
  50974. /**
  50975. * Callback triggered when the particle animation is ending.
  50976. */
  50977. this.onAnimationEnd = null;
  50978. /**
  50979. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  50980. */
  50981. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  50982. /**
  50983. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  50984. * to override the particles.
  50985. */
  50986. this.forceDepthWrite = false;
  50987. /**
  50988. * You can use gravity if you want to give an orientation to your particles.
  50989. */
  50990. this.gravity = BABYLON.Vector3.Zero();
  50991. /**
  50992. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  50993. */
  50994. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  50995. /**
  50996. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  50997. */
  50998. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  50999. /**
  51000. * Color the particle will have at the end of its lifetime.
  51001. */
  51002. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  51003. /**
  51004. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel.
  51005. */
  51006. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  51007. /**
  51008. * If using a spritesheet (isAnimationSheetEnabled), defines if the sprite animation should loop between startSpriteCellID and endSpriteCellID or not.
  51009. */
  51010. this.spriteCellLoop = true;
  51011. /**
  51012. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the speed of the sprite loop.
  51013. */
  51014. this.spriteCellChangeSpeed = 0;
  51015. /**
  51016. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the first sprite cell to display.
  51017. */
  51018. this.startSpriteCellID = 0;
  51019. /**
  51020. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the last sprite cell to display.
  51021. */
  51022. this.endSpriteCellID = 0;
  51023. /**
  51024. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use.
  51025. */
  51026. this.spriteCellWidth = 0;
  51027. /**
  51028. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use.
  51029. */
  51030. this.spriteCellHeight = 0;
  51031. /**
  51032. * An event triggered when the system is disposed.
  51033. */
  51034. this.onDisposeObservable = new BABYLON.Observable();
  51035. this._particles = new Array();
  51036. this._stockParticles = new Array();
  51037. this._newPartsExcess = 0;
  51038. this._vertexBuffers = {};
  51039. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  51040. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  51041. this._scaledDirection = BABYLON.Vector3.Zero();
  51042. this._scaledGravity = BABYLON.Vector3.Zero();
  51043. this._currentRenderId = -1;
  51044. this._started = false;
  51045. this._stopped = false;
  51046. this._actualFrame = 0;
  51047. this._vertexBufferSize = 11;
  51048. // start of sub system methods
  51049. /**
  51050. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  51051. * Its lifetime will start back at 0.
  51052. */
  51053. this.recycleParticle = function (particle) {
  51054. var lastParticle = _this._particles.pop();
  51055. if (lastParticle !== particle) {
  51056. lastParticle.copyTo(particle);
  51057. }
  51058. _this._stockParticles.push(lastParticle);
  51059. };
  51060. this._createParticle = function () {
  51061. var particle;
  51062. if (_this._stockParticles.length !== 0) {
  51063. particle = _this._stockParticles.pop();
  51064. particle.age = 0;
  51065. particle.cellIndex = _this.startSpriteCellID;
  51066. }
  51067. else {
  51068. particle = new BABYLON.Particle(_this);
  51069. }
  51070. return particle;
  51071. };
  51072. this._emitFromParticle = function (particle) {
  51073. if (!_this.subEmitters || _this.subEmitters.length === 0) {
  51074. return;
  51075. }
  51076. var templateIndex = Math.floor(Math.random() * _this.subEmitters.length);
  51077. var subSystem = _this.subEmitters[templateIndex].clone(_this.name + "_sub", particle.position.clone());
  51078. subSystem._rootParticleSystem = _this;
  51079. _this.activeSubSystems.push(subSystem);
  51080. subSystem.start();
  51081. };
  51082. this._appendParticleVertexes = null;
  51083. this.id = name;
  51084. this.name = name;
  51085. this._capacity = capacity;
  51086. this._epsilon = epsilon;
  51087. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  51088. if (isAnimationSheetEnabled) {
  51089. this._vertexBufferSize = 12;
  51090. }
  51091. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  51092. this._customEffect = customEffect;
  51093. scene.particleSystems.push(this);
  51094. this._createIndexBuffer();
  51095. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  51096. this._vertexData = new Float32Array(capacity * this._vertexBufferSize * 4);
  51097. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, this._vertexBufferSize);
  51098. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  51099. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  51100. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  51101. if (this._isAnimationSheetEnabled) {
  51102. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", 11, 1);
  51103. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  51104. }
  51105. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  51106. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  51107. this._vertexBuffers["options"] = options;
  51108. // Default emitter type
  51109. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  51110. this.updateFunction = function (particles) {
  51111. for (var index = 0; index < particles.length; index++) {
  51112. var particle = particles[index];
  51113. particle.age += _this._scaledUpdateSpeed;
  51114. if (particle.age >= particle.lifeTime) {
  51115. _this._emitFromParticle(particle);
  51116. _this.recycleParticle(particle);
  51117. index--;
  51118. continue;
  51119. }
  51120. else {
  51121. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  51122. particle.color.addInPlace(_this._scaledColorStep);
  51123. if (particle.color.a < 0)
  51124. particle.color.a = 0;
  51125. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  51126. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  51127. particle.position.addInPlace(_this._scaledDirection);
  51128. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  51129. particle.direction.addInPlace(_this._scaledGravity);
  51130. if (_this._isAnimationSheetEnabled) {
  51131. particle.updateCellIndex(_this._scaledUpdateSpeed);
  51132. }
  51133. }
  51134. }
  51135. };
  51136. }
  51137. Object.defineProperty(ParticleSystem.prototype, "direction1", {
  51138. /**
  51139. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  51140. * This only works when particleEmitterTyps is a BoxParticleEmitter
  51141. */
  51142. get: function () {
  51143. if (this.particleEmitterType.direction1) {
  51144. return this.particleEmitterType.direction1;
  51145. }
  51146. return BABYLON.Vector3.Zero();
  51147. },
  51148. set: function (value) {
  51149. if (this.particleEmitterType.direction1) {
  51150. this.particleEmitterType.direction1 = value;
  51151. }
  51152. },
  51153. enumerable: true,
  51154. configurable: true
  51155. });
  51156. Object.defineProperty(ParticleSystem.prototype, "direction2", {
  51157. /**
  51158. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  51159. * This only works when particleEmitterTyps is a BoxParticleEmitter
  51160. */
  51161. get: function () {
  51162. if (this.particleEmitterType.direction2) {
  51163. return this.particleEmitterType.direction2;
  51164. }
  51165. return BABYLON.Vector3.Zero();
  51166. },
  51167. set: function (value) {
  51168. if (this.particleEmitterType.direction2) {
  51169. this.particleEmitterType.direction2 = value;
  51170. }
  51171. },
  51172. enumerable: true,
  51173. configurable: true
  51174. });
  51175. Object.defineProperty(ParticleSystem.prototype, "minEmitBox", {
  51176. /**
  51177. * Minimum box point around our emitter. Our emitter is the center of particles source, but if you want your particles to emit from more than one point, then you can tell it to do so.
  51178. * This only works when particleEmitterTyps is a BoxParticleEmitter
  51179. */
  51180. get: function () {
  51181. if (this.particleEmitterType.minEmitBox) {
  51182. return this.particleEmitterType.minEmitBox;
  51183. }
  51184. return BABYLON.Vector3.Zero();
  51185. },
  51186. set: function (value) {
  51187. if (this.particleEmitterType.minEmitBox) {
  51188. this.particleEmitterType.minEmitBox = value;
  51189. }
  51190. },
  51191. enumerable: true,
  51192. configurable: true
  51193. });
  51194. Object.defineProperty(ParticleSystem.prototype, "maxEmitBox", {
  51195. /**
  51196. * Maximum box point around our emitter. Our emitter is the center of particles source, but if you want your particles to emit from more than one point, then you can tell it to do so.
  51197. * This only works when particleEmitterTyps is a BoxParticleEmitter
  51198. */
  51199. get: function () {
  51200. if (this.particleEmitterType.maxEmitBox) {
  51201. return this.particleEmitterType.maxEmitBox;
  51202. }
  51203. return BABYLON.Vector3.Zero();
  51204. },
  51205. set: function (value) {
  51206. if (this.particleEmitterType.maxEmitBox) {
  51207. this.particleEmitterType.maxEmitBox = value;
  51208. }
  51209. },
  51210. enumerable: true,
  51211. configurable: true
  51212. });
  51213. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  51214. /**
  51215. * Sets a callback that will be triggered when the system is disposed.
  51216. */
  51217. set: function (callback) {
  51218. if (this._onDisposeObserver) {
  51219. this.onDisposeObservable.remove(this._onDisposeObserver);
  51220. }
  51221. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  51222. },
  51223. enumerable: true,
  51224. configurable: true
  51225. });
  51226. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  51227. /**
  51228. * Gets wether an animation sprite sheet is enabled or not on the particle system.
  51229. */
  51230. get: function () {
  51231. return this._isAnimationSheetEnabled;
  51232. },
  51233. enumerable: true,
  51234. configurable: true
  51235. });
  51236. Object.defineProperty(ParticleSystem.prototype, "particles", {
  51237. //end of Sub-emitter
  51238. /**
  51239. * Gets the current list of active particles
  51240. */
  51241. get: function () {
  51242. return this._particles;
  51243. },
  51244. enumerable: true,
  51245. configurable: true
  51246. });
  51247. /**
  51248. * Returns the string "ParticleSystem"
  51249. * @returns a string containing the class name
  51250. */
  51251. ParticleSystem.prototype.getClassName = function () {
  51252. return "ParticleSystem";
  51253. };
  51254. ParticleSystem.prototype._createIndexBuffer = function () {
  51255. var indices = [];
  51256. var index = 0;
  51257. for (var count = 0; count < this._capacity; count++) {
  51258. indices.push(index);
  51259. indices.push(index + 1);
  51260. indices.push(index + 2);
  51261. indices.push(index);
  51262. indices.push(index + 2);
  51263. indices.push(index + 3);
  51264. index += 4;
  51265. }
  51266. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  51267. };
  51268. /**
  51269. * Gets the maximum number of particles active at the same time.
  51270. * @returns The max number of active particles.
  51271. */
  51272. ParticleSystem.prototype.getCapacity = function () {
  51273. return this._capacity;
  51274. };
  51275. /**
  51276. * Gets Wether there are still active particles in the system.
  51277. * @returns True if it is alive, otherwise false.
  51278. */
  51279. ParticleSystem.prototype.isAlive = function () {
  51280. return this._alive;
  51281. };
  51282. /**
  51283. * Gets Wether the system has been started.
  51284. * @returns True if it has been started, otherwise false.
  51285. */
  51286. ParticleSystem.prototype.isStarted = function () {
  51287. return this._started;
  51288. };
  51289. /**
  51290. * Starts the particle system and begins to emit.
  51291. */
  51292. ParticleSystem.prototype.start = function () {
  51293. this._started = true;
  51294. this._stopped = false;
  51295. this._actualFrame = 0;
  51296. if (this.subEmitters && this.subEmitters.length != 0) {
  51297. this.activeSubSystems = new Array();
  51298. }
  51299. };
  51300. /**
  51301. * Stops the particle system.
  51302. * @param stopSubEmitters if true it will stop the current system and all created sub-Systems if false it will stop the current root system only, this param is used by the root particle system only. the default value is true.
  51303. */
  51304. ParticleSystem.prototype.stop = function (stopSubEmitters) {
  51305. if (stopSubEmitters === void 0) { stopSubEmitters = true; }
  51306. this._stopped = true;
  51307. if (stopSubEmitters) {
  51308. this._stopSubEmitters();
  51309. }
  51310. };
  51311. // animation sheet
  51312. /**
  51313. * Remove all active particles
  51314. */
  51315. ParticleSystem.prototype.reset = function () {
  51316. this._stockParticles = [];
  51317. this._particles = [];
  51318. };
  51319. /**
  51320. * @ignore (for internal use only)
  51321. */
  51322. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  51323. var offset = index * this._vertexBufferSize;
  51324. this._vertexData[offset] = particle.position.x;
  51325. this._vertexData[offset + 1] = particle.position.y;
  51326. this._vertexData[offset + 2] = particle.position.z;
  51327. this._vertexData[offset + 3] = particle.color.r;
  51328. this._vertexData[offset + 4] = particle.color.g;
  51329. this._vertexData[offset + 5] = particle.color.b;
  51330. this._vertexData[offset + 6] = particle.color.a;
  51331. this._vertexData[offset + 7] = particle.angle;
  51332. this._vertexData[offset + 8] = particle.size;
  51333. this._vertexData[offset + 9] = offsetX;
  51334. this._vertexData[offset + 10] = offsetY;
  51335. };
  51336. /**
  51337. * @ignore (for internal use only)
  51338. */
  51339. ParticleSystem.prototype._appendParticleVertexWithAnimation = function (index, particle, offsetX, offsetY) {
  51340. if (offsetX === 0)
  51341. offsetX = this._epsilon;
  51342. else if (offsetX === 1)
  51343. offsetX = 1 - this._epsilon;
  51344. if (offsetY === 0)
  51345. offsetY = this._epsilon;
  51346. else if (offsetY === 1)
  51347. offsetY = 1 - this._epsilon;
  51348. var offset = index * this._vertexBufferSize;
  51349. this._vertexData[offset] = particle.position.x;
  51350. this._vertexData[offset + 1] = particle.position.y;
  51351. this._vertexData[offset + 2] = particle.position.z;
  51352. this._vertexData[offset + 3] = particle.color.r;
  51353. this._vertexData[offset + 4] = particle.color.g;
  51354. this._vertexData[offset + 5] = particle.color.b;
  51355. this._vertexData[offset + 6] = particle.color.a;
  51356. this._vertexData[offset + 7] = particle.angle;
  51357. this._vertexData[offset + 8] = particle.size;
  51358. this._vertexData[offset + 9] = offsetX;
  51359. this._vertexData[offset + 10] = offsetY;
  51360. this._vertexData[offset + 11] = particle.cellIndex;
  51361. };
  51362. ParticleSystem.prototype._stopSubEmitters = function () {
  51363. if (!this.activeSubSystems) {
  51364. return;
  51365. }
  51366. this.activeSubSystems.forEach(function (subSystem) {
  51367. subSystem.stop(true);
  51368. });
  51369. this.activeSubSystems = new Array();
  51370. };
  51371. ParticleSystem.prototype._removeFromRoot = function () {
  51372. if (!this._rootParticleSystem) {
  51373. return;
  51374. }
  51375. var index = this._rootParticleSystem.activeSubSystems.indexOf(this);
  51376. if (index !== -1) {
  51377. this._rootParticleSystem.activeSubSystems.splice(index, 1);
  51378. }
  51379. };
  51380. // end of sub system methods
  51381. ParticleSystem.prototype._update = function (newParticles) {
  51382. // Update current
  51383. this._alive = this._particles.length > 0;
  51384. this.updateFunction(this._particles);
  51385. // Add new ones
  51386. var worldMatrix;
  51387. if (this.emitter.position) {
  51388. var emitterMesh = this.emitter;
  51389. worldMatrix = emitterMesh.getWorldMatrix();
  51390. }
  51391. else {
  51392. var emitterPosition = this.emitter;
  51393. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  51394. }
  51395. var particle;
  51396. for (var index = 0; index < newParticles; index++) {
  51397. if (this._particles.length === this._capacity) {
  51398. break;
  51399. }
  51400. particle = this._createParticle();
  51401. this._particles.push(particle);
  51402. var emitPower = BABYLON.Scalar.RandomRange(this.minEmitPower, this.maxEmitPower);
  51403. if (this.startPositionFunction) {
  51404. this.startPositionFunction(worldMatrix, particle.position, particle);
  51405. }
  51406. else {
  51407. this.particleEmitterType.startPositionFunction(worldMatrix, particle.position, particle);
  51408. }
  51409. if (this.startDirectionFunction) {
  51410. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  51411. }
  51412. else {
  51413. this.particleEmitterType.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  51414. }
  51415. particle.lifeTime = BABYLON.Scalar.RandomRange(this.minLifeTime, this.maxLifeTime);
  51416. particle.size = BABYLON.Scalar.RandomRange(this.minSize, this.maxSize);
  51417. particle.angularSpeed = BABYLON.Scalar.RandomRange(this.minAngularSpeed, this.maxAngularSpeed);
  51418. var step = BABYLON.Scalar.RandomRange(0, 1.0);
  51419. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  51420. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  51421. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  51422. }
  51423. };
  51424. ParticleSystem.prototype._getEffect = function () {
  51425. if (this._customEffect) {
  51426. return this._customEffect;
  51427. }
  51428. ;
  51429. var defines = [];
  51430. if (this._scene.clipPlane) {
  51431. defines.push("#define CLIPPLANE");
  51432. }
  51433. if (this._isAnimationSheetEnabled) {
  51434. defines.push("#define ANIMATESHEET");
  51435. }
  51436. // Effect
  51437. var join = defines.join("\n");
  51438. if (this._cachedDefines !== join) {
  51439. this._cachedDefines = join;
  51440. var attributesNamesOrOptions;
  51441. var effectCreationOption;
  51442. if (this._isAnimationSheetEnabled) {
  51443. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "cellIndex"];
  51444. effectCreationOption = ["invView", "view", "projection", "particlesInfos", "vClipPlane", "textureMask"];
  51445. }
  51446. else {
  51447. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"];
  51448. effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  51449. }
  51450. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  51451. }
  51452. return this._effect;
  51453. };
  51454. /**
  51455. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  51456. */
  51457. ParticleSystem.prototype.animate = function () {
  51458. if (!this._started)
  51459. return;
  51460. var effect = this._getEffect();
  51461. // Check
  51462. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  51463. return;
  51464. if (this._currentRenderId === this._scene.getRenderId()) {
  51465. return;
  51466. }
  51467. this._currentRenderId = this._scene.getRenderId();
  51468. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  51469. // determine the number of particles we need to create
  51470. var newParticles;
  51471. if (this.manualEmitCount > -1) {
  51472. newParticles = this.manualEmitCount;
  51473. this._newPartsExcess = 0;
  51474. this.manualEmitCount = 0;
  51475. }
  51476. else {
  51477. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  51478. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  51479. }
  51480. if (this._newPartsExcess > 1.0) {
  51481. newParticles += this._newPartsExcess >> 0;
  51482. this._newPartsExcess -= this._newPartsExcess >> 0;
  51483. }
  51484. this._alive = false;
  51485. if (!this._stopped) {
  51486. this._actualFrame += this._scaledUpdateSpeed;
  51487. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  51488. this.stop();
  51489. }
  51490. else {
  51491. newParticles = 0;
  51492. }
  51493. this._update(newParticles);
  51494. // Stopped?
  51495. if (this._stopped) {
  51496. if (!this._alive) {
  51497. this._started = false;
  51498. if (this.onAnimationEnd) {
  51499. this.onAnimationEnd();
  51500. }
  51501. if (this.disposeOnStop) {
  51502. this._scene._toBeDisposed.push(this);
  51503. }
  51504. }
  51505. }
  51506. // Animation sheet
  51507. if (this._isAnimationSheetEnabled) {
  51508. this._appendParticleVertexes = this._appenedParticleVertexesWithSheet;
  51509. }
  51510. else {
  51511. this._appendParticleVertexes = this._appenedParticleVertexesNoSheet;
  51512. }
  51513. // Update VBO
  51514. var offset = 0;
  51515. for (var index = 0; index < this._particles.length; index++) {
  51516. var particle = this._particles[index];
  51517. this._appendParticleVertexes(offset, particle);
  51518. offset += 4;
  51519. }
  51520. if (this._vertexBuffer) {
  51521. this._vertexBuffer.update(this._vertexData);
  51522. }
  51523. if (this.manualEmitCount === 0 && this.disposeOnStop) {
  51524. this.stop();
  51525. }
  51526. };
  51527. ParticleSystem.prototype._appenedParticleVertexesWithSheet = function (offset, particle) {
  51528. this._appendParticleVertexWithAnimation(offset++, particle, 0, 0);
  51529. this._appendParticleVertexWithAnimation(offset++, particle, 1, 0);
  51530. this._appendParticleVertexWithAnimation(offset++, particle, 1, 1);
  51531. this._appendParticleVertexWithAnimation(offset++, particle, 0, 1);
  51532. };
  51533. ParticleSystem.prototype._appenedParticleVertexesNoSheet = function (offset, particle) {
  51534. this._appendParticleVertex(offset++, particle, 0, 0);
  51535. this._appendParticleVertex(offset++, particle, 1, 0);
  51536. this._appendParticleVertex(offset++, particle, 1, 1);
  51537. this._appendParticleVertex(offset++, particle, 0, 1);
  51538. };
  51539. /**
  51540. * Rebuilds the particle system.
  51541. */
  51542. ParticleSystem.prototype.rebuild = function () {
  51543. this._createIndexBuffer();
  51544. if (this._vertexBuffer) {
  51545. this._vertexBuffer._rebuild();
  51546. }
  51547. };
  51548. /**
  51549. * Is this system ready to be used/rendered
  51550. * @return true if the system is ready
  51551. */
  51552. ParticleSystem.prototype.isReady = function () {
  51553. var effect = this._getEffect();
  51554. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  51555. return false;
  51556. }
  51557. return true;
  51558. };
  51559. /**
  51560. * Renders the particle system in its current state.
  51561. * @returns the current number of particles
  51562. */
  51563. ParticleSystem.prototype.render = function () {
  51564. var effect = this._getEffect();
  51565. // Check
  51566. if (!this.isReady() || !this._particles.length) {
  51567. return 0;
  51568. }
  51569. var engine = this._scene.getEngine();
  51570. // Render
  51571. engine.enableEffect(effect);
  51572. engine.setState(false);
  51573. var viewMatrix = this._scene.getViewMatrix();
  51574. effect.setTexture("diffuseSampler", this.particleTexture);
  51575. effect.setMatrix("view", viewMatrix);
  51576. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  51577. if (this._isAnimationSheetEnabled && this.particleTexture) {
  51578. var baseSize = this.particleTexture.getBaseSize();
  51579. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  51580. }
  51581. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  51582. if (this._scene.clipPlane) {
  51583. var clipPlane = this._scene.clipPlane;
  51584. var invView = viewMatrix.clone();
  51585. invView.invert();
  51586. effect.setMatrix("invView", invView);
  51587. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  51588. }
  51589. // VBOs
  51590. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  51591. // Draw order
  51592. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  51593. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  51594. }
  51595. else {
  51596. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  51597. }
  51598. if (this.forceDepthWrite) {
  51599. engine.setDepthWrite(true);
  51600. }
  51601. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  51602. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  51603. return this._particles.length;
  51604. };
  51605. /**
  51606. * Disposes the particle system and free the associated resources
  51607. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  51608. */
  51609. ParticleSystem.prototype.dispose = function (disposeTexture) {
  51610. if (disposeTexture === void 0) { disposeTexture = true; }
  51611. if (this._vertexBuffer) {
  51612. this._vertexBuffer.dispose();
  51613. this._vertexBuffer = null;
  51614. }
  51615. if (this._indexBuffer) {
  51616. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  51617. this._indexBuffer = null;
  51618. }
  51619. if (disposeTexture && this.particleTexture) {
  51620. this.particleTexture.dispose();
  51621. this.particleTexture = null;
  51622. }
  51623. this._removeFromRoot();
  51624. // Remove from scene
  51625. var index = this._scene.particleSystems.indexOf(this);
  51626. if (index > -1) {
  51627. this._scene.particleSystems.splice(index, 1);
  51628. }
  51629. // Callback
  51630. this.onDisposeObservable.notifyObservers(this);
  51631. this.onDisposeObservable.clear();
  51632. };
  51633. /**
  51634. * Creates a Sphere Emitter for the particle system. (emits along the sphere radius)
  51635. * @param radius The radius of the sphere to emit from
  51636. * @returns the emitter
  51637. */
  51638. ParticleSystem.prototype.createSphereEmitter = function (radius) {
  51639. if (radius === void 0) { radius = 1; }
  51640. var particleEmitter = new BABYLON.SphereParticleEmitter(radius);
  51641. this.particleEmitterType = particleEmitter;
  51642. return particleEmitter;
  51643. };
  51644. /**
  51645. * Creates a Directed Sphere Emitter for the particle system. (emits between direction1 and direction2)
  51646. * @param radius The radius of the sphere to emit from
  51647. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  51648. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  51649. * @returns the emitter
  51650. */
  51651. ParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  51652. if (radius === void 0) { radius = 1; }
  51653. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  51654. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  51655. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  51656. this.particleEmitterType = particleEmitter;
  51657. return particleEmitter;
  51658. };
  51659. /**
  51660. * Creates a Cone Emitter for the particle system. (emits from the cone to the particle position)
  51661. * @param radius The radius of the cone to emit from
  51662. * @param angle The base angle of the cone
  51663. * @returns the emitter
  51664. */
  51665. ParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  51666. if (radius === void 0) { radius = 1; }
  51667. if (angle === void 0) { angle = Math.PI / 4; }
  51668. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  51669. this.particleEmitterType = particleEmitter;
  51670. return particleEmitter;
  51671. };
  51672. // this method needs to be changed when breaking changes will be allowed to match the sphere and cone methods and properties direction1,2 and minEmitBox,maxEmitBox to be removed from the system.
  51673. /**
  51674. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  51675. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  51676. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  51677. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  51678. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  51679. * @returns the emitter
  51680. */
  51681. ParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  51682. var particleEmitter = new BABYLON.BoxParticleEmitter();
  51683. this.direction1 = direction1;
  51684. this.direction2 = direction2;
  51685. this.minEmitBox = minEmitBox;
  51686. this.maxEmitBox = maxEmitBox;
  51687. this.particleEmitterType = particleEmitter;
  51688. return particleEmitter;
  51689. };
  51690. // Clone
  51691. /**
  51692. * Clones the particle system.
  51693. * @param name The name of the cloned object
  51694. * @param newEmitter The new emitter to use
  51695. * @returns the cloned particle system
  51696. */
  51697. ParticleSystem.prototype.clone = function (name, newEmitter) {
  51698. var custom = null;
  51699. var program = null;
  51700. if (this.customShader != null) {
  51701. program = this.customShader;
  51702. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  51703. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  51704. }
  51705. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  51706. result.customShader = program;
  51707. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  51708. if (newEmitter === undefined) {
  51709. newEmitter = this.emitter;
  51710. }
  51711. result.emitter = newEmitter;
  51712. if (this.particleTexture) {
  51713. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  51714. }
  51715. if (!this.preventAutoStart) {
  51716. result.start();
  51717. }
  51718. return result;
  51719. };
  51720. /**
  51721. * Serializes the particle system to a JSON object.
  51722. * @returns the JSON object
  51723. */
  51724. ParticleSystem.prototype.serialize = function () {
  51725. var serializationObject = {};
  51726. serializationObject.name = this.name;
  51727. serializationObject.id = this.id;
  51728. // Emitter
  51729. if (this.emitter.position) {
  51730. var emitterMesh = this.emitter;
  51731. serializationObject.emitterId = emitterMesh.id;
  51732. }
  51733. else {
  51734. var emitterPosition = this.emitter;
  51735. serializationObject.emitter = emitterPosition.asArray();
  51736. }
  51737. serializationObject.capacity = this.getCapacity();
  51738. if (this.particleTexture) {
  51739. serializationObject.textureName = this.particleTexture.name;
  51740. }
  51741. // Animations
  51742. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  51743. // Particle system
  51744. serializationObject.minAngularSpeed = this.minAngularSpeed;
  51745. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  51746. serializationObject.minSize = this.minSize;
  51747. serializationObject.maxSize = this.maxSize;
  51748. serializationObject.minEmitPower = this.minEmitPower;
  51749. serializationObject.maxEmitPower = this.maxEmitPower;
  51750. serializationObject.minLifeTime = this.minLifeTime;
  51751. serializationObject.maxLifeTime = this.maxLifeTime;
  51752. serializationObject.emitRate = this.emitRate;
  51753. serializationObject.minEmitBox = this.minEmitBox.asArray();
  51754. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  51755. serializationObject.gravity = this.gravity.asArray();
  51756. serializationObject.direction1 = this.direction1.asArray();
  51757. serializationObject.direction2 = this.direction2.asArray();
  51758. serializationObject.color1 = this.color1.asArray();
  51759. serializationObject.color2 = this.color2.asArray();
  51760. serializationObject.colorDead = this.colorDead.asArray();
  51761. serializationObject.updateSpeed = this.updateSpeed;
  51762. serializationObject.targetStopDuration = this.targetStopDuration;
  51763. serializationObject.textureMask = this.textureMask.asArray();
  51764. serializationObject.blendMode = this.blendMode;
  51765. serializationObject.customShader = this.customShader;
  51766. serializationObject.preventAutoStart = this.preventAutoStart;
  51767. serializationObject.startSpriteCellID = this.startSpriteCellID;
  51768. serializationObject.endSpriteCellID = this.endSpriteCellID;
  51769. serializationObject.spriteCellLoop = this.spriteCellLoop;
  51770. serializationObject.spriteCellChangeSpeed = this.spriteCellChangeSpeed;
  51771. serializationObject.spriteCellWidth = this.spriteCellWidth;
  51772. serializationObject.spriteCellHeight = this.spriteCellHeight;
  51773. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  51774. // Emitter
  51775. if (this.particleEmitterType) {
  51776. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  51777. }
  51778. return serializationObject;
  51779. };
  51780. /**
  51781. * Parses a JSON object to create a particle system.
  51782. * @param parsedParticleSystem The JSON object to parse
  51783. * @param scene The scene to create the particle system in
  51784. * @param rootUrl The root url to use to load external dependencies like texture
  51785. * @returns the Parsed particle system
  51786. */
  51787. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  51788. var name = parsedParticleSystem.name;
  51789. var custom = null;
  51790. var program = null;
  51791. if (parsedParticleSystem.customShader) {
  51792. program = parsedParticleSystem.customShader;
  51793. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  51794. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  51795. }
  51796. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  51797. particleSystem.customShader = program;
  51798. if (parsedParticleSystem.id) {
  51799. particleSystem.id = parsedParticleSystem.id;
  51800. }
  51801. // Auto start
  51802. if (parsedParticleSystem.preventAutoStart) {
  51803. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  51804. }
  51805. // Texture
  51806. if (parsedParticleSystem.textureName) {
  51807. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  51808. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  51809. }
  51810. // Emitter
  51811. if (parsedParticleSystem.emitterId) {
  51812. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  51813. }
  51814. else {
  51815. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  51816. }
  51817. // Animations
  51818. if (parsedParticleSystem.animations) {
  51819. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  51820. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  51821. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  51822. }
  51823. }
  51824. if (parsedParticleSystem.autoAnimate) {
  51825. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  51826. }
  51827. // Particle system
  51828. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  51829. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  51830. particleSystem.minSize = parsedParticleSystem.minSize;
  51831. particleSystem.maxSize = parsedParticleSystem.maxSize;
  51832. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  51833. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  51834. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  51835. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  51836. particleSystem.emitRate = parsedParticleSystem.emitRate;
  51837. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  51838. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  51839. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  51840. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  51841. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  51842. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  51843. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  51844. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  51845. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  51846. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  51847. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  51848. particleSystem.blendMode = parsedParticleSystem.blendMode;
  51849. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  51850. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  51851. particleSystem.spriteCellLoop = parsedParticleSystem.spriteCellLoop;
  51852. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  51853. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  51854. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  51855. if (!particleSystem.preventAutoStart) {
  51856. particleSystem.start();
  51857. }
  51858. return particleSystem;
  51859. };
  51860. /**
  51861. * Source color is added to the destination color without alpha affecting the result.
  51862. */
  51863. ParticleSystem.BLENDMODE_ONEONE = 0;
  51864. /**
  51865. * Blend current color and particle color using particle’s alpha.
  51866. */
  51867. ParticleSystem.BLENDMODE_STANDARD = 1;
  51868. return ParticleSystem;
  51869. }());
  51870. BABYLON.ParticleSystem = ParticleSystem;
  51871. })(BABYLON || (BABYLON = {}));
  51872. //# sourceMappingURL=babylon.particleSystem.js.map
  51873. //# sourceMappingURL=babylon.IParticleEmitterType.js.map
  51874. var BABYLON;
  51875. (function (BABYLON) {
  51876. /**
  51877. * Particle emitter emitting particles from the inside of a box.
  51878. * It emits the particles randomly between 2 given directions.
  51879. */
  51880. var BoxParticleEmitter = /** @class */ (function () {
  51881. /**
  51882. * Creates a new instance of @see BoxParticleEmitter
  51883. */
  51884. function BoxParticleEmitter() {
  51885. /**
  51886. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  51887. */
  51888. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  51889. /**
  51890. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  51891. */
  51892. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  51893. /**
  51894. * Minimum box point around our emitter. Our emitter is the center of particles source, but if you want your particles to emit from more than one point, then you can tell it to do so.
  51895. */
  51896. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  51897. /**
  51898. * Maximum box point around our emitter. Our emitter is the center of particles source, but if you want your particles to emit from more than one point, then you can tell it to do so.
  51899. */
  51900. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  51901. }
  51902. /**
  51903. * Called by the particle System when the direction is computed for the created particle.
  51904. * @param emitPower is the power of the particle (speed)
  51905. * @param worldMatrix is the world matrix of the particle system
  51906. * @param directionToUpdate is the direction vector to update with the result
  51907. * @param particle is the particle we are computed the direction for
  51908. */
  51909. BoxParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  51910. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  51911. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  51912. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  51913. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  51914. };
  51915. /**
  51916. * Called by the particle System when the position is computed for the created particle.
  51917. * @param worldMatrix is the world matrix of the particle system
  51918. * @param positionToUpdate is the position vector to update with the result
  51919. * @param particle is the particle we are computed the position for
  51920. */
  51921. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  51922. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  51923. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  51924. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  51925. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  51926. };
  51927. /**
  51928. * Clones the current emitter and returns a copy of it
  51929. * @returns the new emitter
  51930. */
  51931. BoxParticleEmitter.prototype.clone = function () {
  51932. var newOne = new BoxParticleEmitter();
  51933. BABYLON.Tools.DeepCopy(this, newOne);
  51934. return newOne;
  51935. };
  51936. /**
  51937. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  51938. * @param effect defines the update shader
  51939. */
  51940. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  51941. effect.setVector3("direction1", this.direction1);
  51942. effect.setVector3("direction2", this.direction2);
  51943. effect.setVector3("minEmitBox", this.minEmitBox);
  51944. effect.setVector3("maxEmitBox", this.maxEmitBox);
  51945. };
  51946. /**
  51947. * Returns a string to use to update the GPU particles update shader
  51948. * @returns a string containng the defines string
  51949. */
  51950. BoxParticleEmitter.prototype.getEffectDefines = function () {
  51951. return "#define BOXEMITTER";
  51952. };
  51953. /**
  51954. * Returns the string "BoxEmitter"
  51955. * @returns a string containing the class name
  51956. */
  51957. BoxParticleEmitter.prototype.getClassName = function () {
  51958. return "BoxEmitter";
  51959. };
  51960. /**
  51961. * Serializes the particle system to a JSON object.
  51962. * @returns the JSON object
  51963. */
  51964. BoxParticleEmitter.prototype.serialize = function () {
  51965. var serializationObject = {};
  51966. serializationObject.type = this.getClassName();
  51967. serializationObject.direction1 = this.direction1.asArray();
  51968. ;
  51969. serializationObject.direction2 = this.direction2.asArray();
  51970. ;
  51971. serializationObject.minEmitBox = this.minEmitBox.asArray();
  51972. ;
  51973. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  51974. ;
  51975. return serializationObject;
  51976. };
  51977. /**
  51978. * Parse properties from a JSON object
  51979. * @param serializationObject defines the JSON object
  51980. */
  51981. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  51982. this.direction1.copyFrom(serializationObject.direction1);
  51983. this.direction2.copyFrom(serializationObject.direction2);
  51984. this.minEmitBox.copyFrom(serializationObject.minEmitBox);
  51985. this.maxEmitBox.copyFrom(serializationObject.maxEmitBox);
  51986. };
  51987. return BoxParticleEmitter;
  51988. }());
  51989. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  51990. })(BABYLON || (BABYLON = {}));
  51991. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  51992. var BABYLON;
  51993. (function (BABYLON) {
  51994. /**
  51995. * Particle emitter emitting particles from the inside of a cone.
  51996. * It emits the particles alongside the cone volume from the base to the particle.
  51997. * The emission direction might be randomized.
  51998. */
  51999. var ConeParticleEmitter = /** @class */ (function () {
  52000. /**
  52001. * Creates a new instance of @see ConeParticleEmitter
  52002. * @param radius the radius of the emission cone (1 by default)
  52003. * @param angles the cone base angle (PI by default)
  52004. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  52005. */
  52006. function ConeParticleEmitter(radius,
  52007. /**
  52008. * The radius of the emission cone.
  52009. */
  52010. angle,
  52011. /**
  52012. * The cone base angle.
  52013. */
  52014. directionRandomizer) {
  52015. if (radius === void 0) { radius = 1; }
  52016. if (angle === void 0) { angle = Math.PI; }
  52017. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  52018. this.angle = angle;
  52019. this.directionRandomizer = directionRandomizer;
  52020. this.radius = radius;
  52021. }
  52022. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  52023. /**
  52024. * Gets the radius of the emission cone.
  52025. */
  52026. get: function () {
  52027. return this._radius;
  52028. },
  52029. /**
  52030. * Sets the radius of the emission cone.
  52031. */
  52032. set: function (value) {
  52033. this._radius = value;
  52034. if (this.angle !== 0) {
  52035. this._height = value / Math.tan(this.angle / 2);
  52036. }
  52037. else {
  52038. this._height = 1;
  52039. }
  52040. },
  52041. enumerable: true,
  52042. configurable: true
  52043. });
  52044. /**
  52045. * Called by the particle System when the direction is computed for the created particle.
  52046. * @param emitPower is the power of the particle (speed)
  52047. * @param worldMatrix is the world matrix of the particle system
  52048. * @param directionToUpdate is the direction vector to update with the result
  52049. * @param particle is the particle we are computed the direction for
  52050. */
  52051. ConeParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  52052. if (this.angle === 0) {
  52053. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, emitPower, 0, worldMatrix, directionToUpdate);
  52054. }
  52055. else {
  52056. // measure the direction Vector from the emitter to the particle.
  52057. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  52058. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  52059. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  52060. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  52061. direction.x += randX;
  52062. direction.y += randY;
  52063. direction.z += randZ;
  52064. direction.normalize();
  52065. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  52066. }
  52067. };
  52068. /**
  52069. * Called by the particle System when the position is computed for the created particle.
  52070. * @param worldMatrix is the world matrix of the particle system
  52071. * @param positionToUpdate is the position vector to update with the result
  52072. * @param particle is the particle we are computed the position for
  52073. */
  52074. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  52075. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  52076. var h = BABYLON.Scalar.RandomRange(0, 1);
  52077. // Better distribution in a cone at normal angles.
  52078. h = 1 - h * h;
  52079. var radius = BABYLON.Scalar.RandomRange(0, this._radius);
  52080. radius = radius * h / this._height;
  52081. var randX = radius * Math.sin(s);
  52082. var randZ = radius * Math.cos(s);
  52083. var randY = h * this._height;
  52084. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  52085. };
  52086. /**
  52087. * Clones the current emitter and returns a copy of it
  52088. * @returns the new emitter
  52089. */
  52090. ConeParticleEmitter.prototype.clone = function () {
  52091. var newOne = new ConeParticleEmitter(this.radius, this.angle, this.directionRandomizer);
  52092. BABYLON.Tools.DeepCopy(this, newOne);
  52093. return newOne;
  52094. };
  52095. /**
  52096. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  52097. * @param effect defines the update shader
  52098. */
  52099. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  52100. effect.setFloat("radius", this.radius);
  52101. effect.setFloat("angle", this.angle);
  52102. effect.setFloat("height", this._height);
  52103. effect.setFloat("directionRandomizer", this.directionRandomizer);
  52104. };
  52105. /**
  52106. * Returns a string to use to update the GPU particles update shader
  52107. * @returns a string containng the defines string
  52108. */
  52109. ConeParticleEmitter.prototype.getEffectDefines = function () {
  52110. return "#define CONEEMITTER";
  52111. };
  52112. /**
  52113. * Returns the string "BoxEmitter"
  52114. * @returns a string containing the class name
  52115. */
  52116. ConeParticleEmitter.prototype.getClassName = function () {
  52117. return "ConeEmitter";
  52118. };
  52119. /**
  52120. * Serializes the particle system to a JSON object.
  52121. * @returns the JSON object
  52122. */
  52123. ConeParticleEmitter.prototype.serialize = function () {
  52124. var serializationObject = {};
  52125. serializationObject.type = this.getClassName();
  52126. serializationObject.radius = this.radius;
  52127. serializationObject.angle = this.angle;
  52128. serializationObject.directionRandomizer = this.directionRandomizer;
  52129. return serializationObject;
  52130. };
  52131. /**
  52132. * Parse properties from a JSON object
  52133. * @param serializationObject defines the JSON object
  52134. */
  52135. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  52136. this.radius = serializationObject.radius;
  52137. this.angle = serializationObject.angle;
  52138. this.directionRandomizer = serializationObject.directionRandomizer;
  52139. };
  52140. return ConeParticleEmitter;
  52141. }());
  52142. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  52143. })(BABYLON || (BABYLON = {}));
  52144. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  52145. var BABYLON;
  52146. (function (BABYLON) {
  52147. /**
  52148. * Particle emitter emitting particles from the inside of a sphere.
  52149. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  52150. */
  52151. var SphereParticleEmitter = /** @class */ (function () {
  52152. /**
  52153. * Creates a new instance of @see SphereParticleEmitter
  52154. * @param radius the radius of the emission sphere (1 by default)
  52155. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  52156. */
  52157. function SphereParticleEmitter(
  52158. /**
  52159. * The radius of the emission sphere.
  52160. */
  52161. radius,
  52162. /**
  52163. * How much to randomize the particle direction [0-1].
  52164. */
  52165. directionRandomizer) {
  52166. if (radius === void 0) { radius = 1; }
  52167. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  52168. this.radius = radius;
  52169. this.directionRandomizer = directionRandomizer;
  52170. }
  52171. /**
  52172. * Called by the particle System when the direction is computed for the created particle.
  52173. * @param emitPower is the power of the particle (speed)
  52174. * @param worldMatrix is the world matrix of the particle system
  52175. * @param directionToUpdate is the direction vector to update with the result
  52176. * @param particle is the particle we are computed the direction for
  52177. */
  52178. SphereParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  52179. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  52180. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  52181. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  52182. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  52183. direction.x += randX;
  52184. direction.y += randY;
  52185. direction.z += randZ;
  52186. direction.normalize();
  52187. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  52188. };
  52189. /**
  52190. * Called by the particle System when the position is computed for the created particle.
  52191. * @param worldMatrix is the world matrix of the particle system
  52192. * @param positionToUpdate is the position vector to update with the result
  52193. * @param particle is the particle we are computed the position for
  52194. */
  52195. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  52196. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  52197. var theta = BABYLON.Scalar.RandomRange(0, Math.PI);
  52198. var randRadius = BABYLON.Scalar.RandomRange(0, this.radius);
  52199. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  52200. var randY = randRadius * Math.cos(theta);
  52201. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  52202. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  52203. };
  52204. /**
  52205. * Clones the current emitter and returns a copy of it
  52206. * @returns the new emitter
  52207. */
  52208. SphereParticleEmitter.prototype.clone = function () {
  52209. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  52210. BABYLON.Tools.DeepCopy(this, newOne);
  52211. return newOne;
  52212. };
  52213. /**
  52214. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  52215. * @param effect defines the update shader
  52216. */
  52217. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  52218. effect.setFloat("radius", this.radius);
  52219. effect.setFloat("directionRandomizer", this.directionRandomizer);
  52220. };
  52221. /**
  52222. * Returns a string to use to update the GPU particles update shader
  52223. * @returns a string containng the defines string
  52224. */
  52225. SphereParticleEmitter.prototype.getEffectDefines = function () {
  52226. return "#define SPHEREEMITTER";
  52227. };
  52228. /**
  52229. * Returns the string "SphereParticleEmitter"
  52230. * @returns a string containing the class name
  52231. */
  52232. SphereParticleEmitter.prototype.getClassName = function () {
  52233. return "SphereParticleEmitter";
  52234. };
  52235. /**
  52236. * Serializes the particle system to a JSON object.
  52237. * @returns the JSON object
  52238. */
  52239. SphereParticleEmitter.prototype.serialize = function () {
  52240. var serializationObject = {};
  52241. serializationObject.type = this.getClassName();
  52242. serializationObject.radius = this.radius;
  52243. serializationObject.directionRandomizer = this.directionRandomizer;
  52244. return serializationObject;
  52245. };
  52246. /**
  52247. * Parse properties from a JSON object
  52248. * @param serializationObject defines the JSON object
  52249. */
  52250. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  52251. this.radius = serializationObject.radius;
  52252. this.directionRandomizer = serializationObject.directionRandomizer;
  52253. };
  52254. return SphereParticleEmitter;
  52255. }());
  52256. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  52257. /**
  52258. * Particle emitter emitting particles from the inside of a sphere.
  52259. * It emits the particles randomly between two vectors.
  52260. */
  52261. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  52262. __extends(SphereDirectedParticleEmitter, _super);
  52263. /**
  52264. * Creates a new instance of @see SphereDirectedParticleEmitter
  52265. * @param radius the radius of the emission sphere (1 by default)
  52266. * @param direction1 the min limit of the emission direction (up vector by default)
  52267. * @param direction2 the max limit of the emission direction (up vector by default)
  52268. */
  52269. function SphereDirectedParticleEmitter(radius,
  52270. /**
  52271. * The min limit of the emission direction.
  52272. */
  52273. direction1,
  52274. /**
  52275. * The max limit of the emission direction.
  52276. */
  52277. direction2) {
  52278. if (radius === void 0) { radius = 1; }
  52279. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  52280. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  52281. var _this = _super.call(this, radius) || this;
  52282. _this.direction1 = direction1;
  52283. _this.direction2 = direction2;
  52284. return _this;
  52285. }
  52286. /**
  52287. * Called by the particle System when the direction is computed for the created particle.
  52288. * @param emitPower is the power of the particle (speed)
  52289. * @param worldMatrix is the world matrix of the particle system
  52290. * @param directionToUpdate is the direction vector to update with the result
  52291. * @param particle is the particle we are computed the direction for
  52292. */
  52293. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  52294. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  52295. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  52296. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  52297. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  52298. };
  52299. /**
  52300. * Clones the current emitter and returns a copy of it
  52301. * @returns the new emitter
  52302. */
  52303. SphereDirectedParticleEmitter.prototype.clone = function () {
  52304. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  52305. BABYLON.Tools.DeepCopy(this, newOne);
  52306. return newOne;
  52307. };
  52308. /**
  52309. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  52310. * @param effect defines the update shader
  52311. */
  52312. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  52313. effect.setFloat("radius", this.radius);
  52314. effect.setVector3("direction1", this.direction1);
  52315. effect.setVector3("direction2", this.direction2);
  52316. };
  52317. /**
  52318. * Returns a string to use to update the GPU particles update shader
  52319. * @returns a string containng the defines string
  52320. */
  52321. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  52322. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  52323. };
  52324. /**
  52325. * Returns the string "SphereDirectedParticleEmitter"
  52326. * @returns a string containing the class name
  52327. */
  52328. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  52329. return "SphereDirectedParticleEmitter";
  52330. };
  52331. /**
  52332. * Serializes the particle system to a JSON object.
  52333. * @returns the JSON object
  52334. */
  52335. SphereDirectedParticleEmitter.prototype.serialize = function () {
  52336. var serializationObject = _super.prototype.serialize.call(this);
  52337. ;
  52338. serializationObject.direction1 = this.direction1.asArray();
  52339. ;
  52340. serializationObject.direction2 = this.direction2.asArray();
  52341. ;
  52342. return serializationObject;
  52343. };
  52344. /**
  52345. * Parse properties from a JSON object
  52346. * @param serializationObject defines the JSON object
  52347. */
  52348. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  52349. _super.prototype.parse.call(this, serializationObject);
  52350. this.direction1.copyFrom(serializationObject.direction1);
  52351. this.direction2.copyFrom(serializationObject.direction2);
  52352. };
  52353. return SphereDirectedParticleEmitter;
  52354. }(SphereParticleEmitter));
  52355. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  52356. })(BABYLON || (BABYLON = {}));
  52357. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  52358. var __assign = (this && this.__assign) || Object.assign || function(t) {
  52359. for (var s, i = 1, n = arguments.length; i < n; i++) {
  52360. s = arguments[i];
  52361. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  52362. t[p] = s[p];
  52363. }
  52364. return t;
  52365. };
  52366. var BABYLON;
  52367. (function (BABYLON) {
  52368. /**
  52369. * This represents a GPU particle system in Babylon
  52370. * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data
  52371. * @see https://www.babylonjs-playground.com/#PU4WYI#4
  52372. */
  52373. var GPUParticleSystem = /** @class */ (function () {
  52374. /**
  52375. * Instantiates a GPU particle system.
  52376. * Particles are often small sprites used to simulate hard-to-reproduce phenomena like fire, smoke, water, or abstract visual effects like magic glitter and faery dust.
  52377. * @param name The name of the particle system
  52378. * @param capacity The max number of particles alive at the same time
  52379. * @param scene The scene the particle system belongs to
  52380. */
  52381. function GPUParticleSystem(name, options, scene) {
  52382. /**
  52383. * The emitter represents the Mesh or position we are attaching the particle system to.
  52384. */
  52385. this.emitter = null;
  52386. /**
  52387. * The rendering group used by the Particle system to chose when to render.
  52388. */
  52389. this.renderingGroupId = 0;
  52390. /**
  52391. * The layer mask we are rendering the particles through.
  52392. */
  52393. this.layerMask = 0x0FFFFFFF;
  52394. this._targetIndex = 0;
  52395. this._currentRenderId = -1;
  52396. this._started = false;
  52397. this._stopped = false;
  52398. this._timeDelta = 0;
  52399. this._attributesStrideSize = 14;
  52400. this._actualFrame = 0;
  52401. /**
  52402. * List of animations used by the particle system.
  52403. */
  52404. this.animations = [];
  52405. /**
  52406. * An event triggered when the system is disposed.
  52407. */
  52408. this.onDisposeObservable = new BABYLON.Observable();
  52409. /**
  52410. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  52411. */
  52412. this.updateSpeed = 0.01;
  52413. /**
  52414. * The amount of time the particle system is running (depends of the overall update speed).
  52415. */
  52416. this.targetStopDuration = 0;
  52417. /**
  52418. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  52419. */
  52420. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  52421. /**
  52422. * Minimum life time of emitting particles.
  52423. */
  52424. this.minLifeTime = 1;
  52425. /**
  52426. * Maximum life time of emitting particles.
  52427. */
  52428. this.maxLifeTime = 1;
  52429. /**
  52430. * Minimum Size of emitting particles.
  52431. */
  52432. this.minSize = 1;
  52433. /**
  52434. * Maximum Size of emitting particles.
  52435. */
  52436. this.maxSize = 1;
  52437. /**
  52438. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  52439. */
  52440. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  52441. /**
  52442. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  52443. */
  52444. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  52445. /**
  52446. * Color the particle will have at the end of its lifetime.
  52447. */
  52448. this.colorDead = new BABYLON.Color4(0, 0, 0, 0);
  52449. /**
  52450. * The maximum number of particles to emit per frame until we reach the activeParticleCount value
  52451. */
  52452. this.emitRate = 100;
  52453. /**
  52454. * You can use gravity if you want to give an orientation to your particles.
  52455. */
  52456. this.gravity = BABYLON.Vector3.Zero();
  52457. /**
  52458. * Minimum power of emitting particles.
  52459. */
  52460. this.minEmitPower = 1;
  52461. /**
  52462. * Maximum power of emitting particles.
  52463. */
  52464. this.maxEmitPower = 1;
  52465. /**
  52466. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  52467. * to override the particles.
  52468. */
  52469. this.forceDepthWrite = false;
  52470. this.id = name;
  52471. this.name = name;
  52472. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  52473. this._engine = this._scene.getEngine();
  52474. var fullOptions = __assign({ capacity: 50000, randomTextureSize: this._engine.getCaps().maxTextureSize }, options);
  52475. this._capacity = fullOptions.capacity;
  52476. this._activeCount = fullOptions.capacity;
  52477. this._currentActiveCount = 0;
  52478. this._scene.particleSystems.push(this);
  52479. this._updateEffectOptions = {
  52480. attributes: ["position", "age", "life", "seed", "size", "color", "direction"],
  52481. uniformsNames: ["currentCount", "timeDelta", "generalRandoms", "emitterWM", "lifeTime", "color1", "color2", "sizeRange", "gravity", "emitPower",
  52482. "direction1", "direction2", "minEmitBox", "maxEmitBox", "radius", "directionRandomizer", "height", "angle", "stopFactor"],
  52483. uniformBuffersNames: [],
  52484. samplers: ["randomSampler"],
  52485. defines: "",
  52486. fallbacks: null,
  52487. onCompiled: null,
  52488. onError: null,
  52489. indexParameters: null,
  52490. maxSimultaneousLights: 0,
  52491. transformFeedbackVaryings: ["outPosition", "outAge", "outLife", "outSeed", "outSize", "outColor", "outDirection"]
  52492. };
  52493. // Random data
  52494. var maxTextureSize = Math.min(this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);
  52495. var d = [];
  52496. for (var i = 0; i < maxTextureSize; ++i) {
  52497. d.push(Math.random());
  52498. d.push(Math.random());
  52499. d.push(Math.random());
  52500. d.push(Math.random());
  52501. }
  52502. this._randomTexture = new BABYLON.RawTexture(new Float32Array(d), maxTextureSize, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA32F, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE, BABYLON.Engine.TEXTURETYPE_FLOAT);
  52503. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  52504. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  52505. this._randomTextureSize = maxTextureSize;
  52506. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  52507. }
  52508. Object.defineProperty(GPUParticleSystem, "IsSupported", {
  52509. /**
  52510. * Gets a boolean indicating if the GPU particles can be rendered on current browser
  52511. */
  52512. get: function () {
  52513. if (!BABYLON.Engine.LastCreatedEngine) {
  52514. return false;
  52515. }
  52516. return BABYLON.Engine.LastCreatedEngine.webGLVersion > 1;
  52517. },
  52518. enumerable: true,
  52519. configurable: true
  52520. });
  52521. Object.defineProperty(GPUParticleSystem.prototype, "direction1", {
  52522. /**
  52523. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  52524. * This only works when particleEmitterTyps is a BoxParticleEmitter
  52525. */
  52526. get: function () {
  52527. if (this.particleEmitterType.direction1) {
  52528. return this.particleEmitterType.direction1;
  52529. }
  52530. return BABYLON.Vector3.Zero();
  52531. },
  52532. set: function (value) {
  52533. if (this.particleEmitterType.direction1) {
  52534. this.particleEmitterType.direction1 = value;
  52535. }
  52536. },
  52537. enumerable: true,
  52538. configurable: true
  52539. });
  52540. Object.defineProperty(GPUParticleSystem.prototype, "direction2", {
  52541. /**
  52542. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  52543. * This only works when particleEmitterTyps is a BoxParticleEmitter
  52544. */
  52545. get: function () {
  52546. if (this.particleEmitterType.direction2) {
  52547. return this.particleEmitterType.direction2;
  52548. }
  52549. return BABYLON.Vector3.Zero();
  52550. },
  52551. set: function (value) {
  52552. if (this.particleEmitterType.direction2) {
  52553. this.particleEmitterType.direction2 = value;
  52554. }
  52555. },
  52556. enumerable: true,
  52557. configurable: true
  52558. });
  52559. Object.defineProperty(GPUParticleSystem.prototype, "minEmitBox", {
  52560. /**
  52561. * Minimum box point around our emitter. Our emitter is the center of particles source, but if you want your particles to emit from more than one point, then you can tell it to do so.
  52562. * This only works when particleEmitterTyps is a BoxParticleEmitter
  52563. */
  52564. get: function () {
  52565. if (this.particleEmitterType.minEmitBox) {
  52566. return this.particleEmitterType.minEmitBox;
  52567. }
  52568. return BABYLON.Vector3.Zero();
  52569. },
  52570. set: function (value) {
  52571. if (this.particleEmitterType.minEmitBox) {
  52572. this.particleEmitterType.minEmitBox = value;
  52573. }
  52574. },
  52575. enumerable: true,
  52576. configurable: true
  52577. });
  52578. Object.defineProperty(GPUParticleSystem.prototype, "maxEmitBox", {
  52579. /**
  52580. * Maximum box point around our emitter. Our emitter is the center of particles source, but if you want your particles to emit from more than one point, then you can tell it to do so.
  52581. * This only works when particleEmitterTyps is a BoxParticleEmitter
  52582. */
  52583. get: function () {
  52584. if (this.particleEmitterType.maxEmitBox) {
  52585. return this.particleEmitterType.maxEmitBox;
  52586. }
  52587. return BABYLON.Vector3.Zero();
  52588. },
  52589. set: function (value) {
  52590. if (this.particleEmitterType.maxEmitBox) {
  52591. this.particleEmitterType.maxEmitBox = value;
  52592. }
  52593. },
  52594. enumerable: true,
  52595. configurable: true
  52596. });
  52597. /**
  52598. * Gets the maximum number of particles active at the same time.
  52599. * @returns The max number of active particles.
  52600. */
  52601. GPUParticleSystem.prototype.getCapacity = function () {
  52602. return this._capacity;
  52603. };
  52604. Object.defineProperty(GPUParticleSystem.prototype, "activeParticleCount", {
  52605. /**
  52606. * Gets or set the number of active particles
  52607. */
  52608. get: function () {
  52609. return this._activeCount;
  52610. },
  52611. set: function (value) {
  52612. this._activeCount = Math.min(value, this._capacity);
  52613. },
  52614. enumerable: true,
  52615. configurable: true
  52616. });
  52617. /**
  52618. * Is this system ready to be used/rendered
  52619. * @return true if the system is ready
  52620. */
  52621. GPUParticleSystem.prototype.isReady = function () {
  52622. if (!this.emitter || !this._updateEffect.isReady() || !this._renderEffect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  52623. return false;
  52624. }
  52625. return true;
  52626. };
  52627. /**
  52628. * Gets Wether the system has been started.
  52629. * @returns True if it has been started, otherwise false.
  52630. */
  52631. GPUParticleSystem.prototype.isStarted = function () {
  52632. return this._started;
  52633. };
  52634. /**
  52635. * Starts the particle system and begins to emit.
  52636. */
  52637. GPUParticleSystem.prototype.start = function () {
  52638. this._started = true;
  52639. this._stopped = false;
  52640. };
  52641. /**
  52642. * Stops the particle system.
  52643. */
  52644. GPUParticleSystem.prototype.stop = function () {
  52645. this._stopped = true;
  52646. };
  52647. /**
  52648. * Remove all active particles
  52649. */
  52650. GPUParticleSystem.prototype.reset = function () {
  52651. this._releaseBuffers();
  52652. this._releaseVAOs();
  52653. this._currentActiveCount = 0;
  52654. this._targetIndex = 0;
  52655. };
  52656. /**
  52657. * Returns the string "GPUParticleSystem"
  52658. * @returns a string containing the class name
  52659. */
  52660. GPUParticleSystem.prototype.getClassName = function () {
  52661. return "GPUParticleSystem";
  52662. };
  52663. GPUParticleSystem.prototype._createUpdateVAO = function (source) {
  52664. var updateVertexBuffers = {};
  52665. updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3);
  52666. updateVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1);
  52667. updateVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1);
  52668. updateVertexBuffers["seed"] = source.createVertexBuffer("seed", 5, 1);
  52669. updateVertexBuffers["size"] = source.createVertexBuffer("size", 6, 1);
  52670. updateVertexBuffers["color"] = source.createVertexBuffer("color", 7, 4);
  52671. updateVertexBuffers["direction"] = source.createVertexBuffer("direction", 11, 3);
  52672. var vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);
  52673. this._engine.bindArrayBuffer(null);
  52674. return vao;
  52675. };
  52676. GPUParticleSystem.prototype._createRenderVAO = function (source, spriteSource) {
  52677. var renderVertexBuffers = {};
  52678. renderVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
  52679. renderVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1, this._attributesStrideSize, true);
  52680. renderVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1, this._attributesStrideSize, true);
  52681. renderVertexBuffers["size"] = source.createVertexBuffer("size", 6, 1, this._attributesStrideSize, true);
  52682. renderVertexBuffers["color"] = source.createVertexBuffer("color", 7, 4, this._attributesStrideSize, true);
  52683. renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
  52684. renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
  52685. var vao = this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._renderEffect);
  52686. this._engine.bindArrayBuffer(null);
  52687. return vao;
  52688. };
  52689. GPUParticleSystem.prototype._initialize = function (force) {
  52690. if (force === void 0) { force = false; }
  52691. if (this._buffer0 && !force) {
  52692. return;
  52693. }
  52694. var engine = this._scene.getEngine();
  52695. var data = new Array();
  52696. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  52697. // position
  52698. data.push(0.0);
  52699. data.push(0.0);
  52700. data.push(0.0);
  52701. // Age and life
  52702. data.push(0.0); // create the particle as a dead one to create a new one at start
  52703. data.push(0.0);
  52704. // Seed
  52705. data.push(Math.random());
  52706. // Size
  52707. data.push(0.0);
  52708. // color
  52709. data.push(0.0);
  52710. data.push(0.0);
  52711. data.push(0.0);
  52712. data.push(0.0);
  52713. // direction
  52714. data.push(0.0);
  52715. data.push(0.0);
  52716. data.push(0.0);
  52717. }
  52718. // Sprite data
  52719. var spriteData = new Float32Array([0.5, 0.5, 1, 1,
  52720. -0.5, 0.5, 0, 1,
  52721. -0.5, -0.5, 0, 0,
  52722. 0.5, -0.5, 1, 0]);
  52723. // Buffers
  52724. this._buffer0 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  52725. this._buffer1 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  52726. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 4);
  52727. // Update VAO
  52728. this._updateVAO = [];
  52729. this._updateVAO.push(this._createUpdateVAO(this._buffer0));
  52730. this._updateVAO.push(this._createUpdateVAO(this._buffer1));
  52731. // Render VAO
  52732. this._renderVAO = [];
  52733. this._renderVAO.push(this._createRenderVAO(this._buffer1, this._spriteBuffer));
  52734. this._renderVAO.push(this._createRenderVAO(this._buffer0, this._spriteBuffer));
  52735. // Links
  52736. this._sourceBuffer = this._buffer0;
  52737. this._targetBuffer = this._buffer1;
  52738. };
  52739. /** @ignore */
  52740. GPUParticleSystem.prototype._recreateUpdateEffect = function () {
  52741. var defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
  52742. if (this._updateEffect && this._updateEffectOptions.defines === defines) {
  52743. return;
  52744. }
  52745. this._updateEffectOptions.defines = defines;
  52746. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", this._updateEffectOptions, this._scene.getEngine());
  52747. };
  52748. /** @ignore */
  52749. GPUParticleSystem.prototype._recreateRenderEffect = function () {
  52750. var defines = "";
  52751. if (this._scene.clipPlane) {
  52752. defines = "\n#define CLIPPLANE";
  52753. }
  52754. if (this._renderEffect && this._renderEffect.defines === defines) {
  52755. return;
  52756. }
  52757. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "size", "color", "offset", "uv"], ["view", "projection", "colorDead", "invView", "vClipPlane"], ["textureSampler"], this._scene.getEngine(), defines);
  52758. };
  52759. /**
  52760. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  52761. */
  52762. GPUParticleSystem.prototype.animate = function () {
  52763. this._timeDelta = this.updateSpeed * this._scene.getAnimationRatio();
  52764. this._actualFrame += this._timeDelta;
  52765. if (!this._stopped) {
  52766. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
  52767. this.stop();
  52768. }
  52769. }
  52770. };
  52771. /**
  52772. * Renders the particle system in its current state.
  52773. * @returns the current number of particles
  52774. */
  52775. GPUParticleSystem.prototype.render = function () {
  52776. if (!this._started) {
  52777. return 0;
  52778. }
  52779. this._recreateUpdateEffect();
  52780. this._recreateRenderEffect();
  52781. if (!this.isReady()) {
  52782. return 0;
  52783. }
  52784. if (this._currentRenderId === this._scene.getRenderId()) {
  52785. return 0;
  52786. }
  52787. this._currentRenderId = this._scene.getRenderId();
  52788. // Get everything ready to render
  52789. this._initialize();
  52790. this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + (this.emitRate * this._timeDelta) | 0);
  52791. // Enable update effect
  52792. this._engine.enableEffect(this._updateEffect);
  52793. this._engine.setState(false);
  52794. this._updateEffect.setFloat("currentCount", this._currentActiveCount);
  52795. this._updateEffect.setFloat("timeDelta", this._timeDelta);
  52796. this._updateEffect.setFloat("stopFactor", this._stopped ? 0 : 1);
  52797. this._updateEffect.setFloat3("generalRandoms", Math.random(), Math.random(), Math.random());
  52798. this._updateEffect.setTexture("randomSampler", this._randomTexture);
  52799. this._updateEffect.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime);
  52800. this._updateEffect.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower);
  52801. this._updateEffect.setDirectColor4("color1", this.color1);
  52802. this._updateEffect.setDirectColor4("color2", this.color2);
  52803. this._updateEffect.setFloat2("sizeRange", this.minSize, this.maxSize);
  52804. this._updateEffect.setVector3("gravity", this.gravity);
  52805. if (this.particleEmitterType) {
  52806. this.particleEmitterType.applyToShader(this._updateEffect);
  52807. }
  52808. var emitterWM;
  52809. if (this.emitter.position) {
  52810. var emitterMesh = this.emitter;
  52811. emitterWM = emitterMesh.getWorldMatrix();
  52812. }
  52813. else {
  52814. var emitterPosition = this.emitter;
  52815. emitterWM = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  52816. }
  52817. this._updateEffect.setMatrix("emitterWM", emitterWM);
  52818. // Bind source VAO
  52819. this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex], null);
  52820. // Update
  52821. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  52822. this._engine.setRasterizerState(false);
  52823. this._engine.beginTransformFeedback();
  52824. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._currentActiveCount);
  52825. this._engine.endTransformFeedback();
  52826. this._engine.setRasterizerState(true);
  52827. this._engine.bindTransformFeedbackBuffer(null);
  52828. // Enable render effect
  52829. this._engine.enableEffect(this._renderEffect);
  52830. var viewMatrix = this._scene.getViewMatrix();
  52831. this._renderEffect.setMatrix("view", viewMatrix);
  52832. this._renderEffect.setMatrix("projection", this._scene.getProjectionMatrix());
  52833. this._renderEffect.setTexture("textureSampler", this.particleTexture);
  52834. this._renderEffect.setDirectColor4("colorDead", this.colorDead);
  52835. if (this._scene.clipPlane) {
  52836. var clipPlane = this._scene.clipPlane;
  52837. var invView = viewMatrix.clone();
  52838. invView.invert();
  52839. this._renderEffect.setMatrix("invView", invView);
  52840. this._renderEffect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  52841. }
  52842. // Draw order
  52843. if (this.blendMode === BABYLON.ParticleSystem.BLENDMODE_ONEONE) {
  52844. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  52845. }
  52846. else {
  52847. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  52848. }
  52849. if (this.forceDepthWrite) {
  52850. this._engine.setDepthWrite(true);
  52851. }
  52852. // Bind source VAO
  52853. this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex], null);
  52854. // Render
  52855. this._engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._currentActiveCount);
  52856. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  52857. // Switch VAOs
  52858. this._targetIndex++;
  52859. if (this._targetIndex === 2) {
  52860. this._targetIndex = 0;
  52861. }
  52862. // Switch buffers
  52863. var tmpBuffer = this._sourceBuffer;
  52864. this._sourceBuffer = this._targetBuffer;
  52865. this._targetBuffer = tmpBuffer;
  52866. return this._currentActiveCount;
  52867. };
  52868. /**
  52869. * Rebuilds the particle system
  52870. */
  52871. GPUParticleSystem.prototype.rebuild = function () {
  52872. this._initialize(true);
  52873. };
  52874. GPUParticleSystem.prototype._releaseBuffers = function () {
  52875. if (this._buffer0) {
  52876. this._buffer0.dispose();
  52877. this._buffer0 = null;
  52878. }
  52879. if (this._buffer1) {
  52880. this._buffer1.dispose();
  52881. this._buffer1 = null;
  52882. }
  52883. if (this._spriteBuffer) {
  52884. this._spriteBuffer.dispose();
  52885. this._spriteBuffer = null;
  52886. }
  52887. };
  52888. GPUParticleSystem.prototype._releaseVAOs = function () {
  52889. if (!this._updateVAO) {
  52890. return;
  52891. }
  52892. for (var index = 0; index < this._updateVAO.length; index++) {
  52893. this._engine.releaseVertexArrayObject(this._updateVAO[index]);
  52894. }
  52895. this._updateVAO = [];
  52896. for (var index = 0; index < this._renderVAO.length; index++) {
  52897. this._engine.releaseVertexArrayObject(this._renderVAO[index]);
  52898. }
  52899. this._renderVAO = [];
  52900. };
  52901. /**
  52902. * Disposes the particle system and free the associated resources
  52903. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  52904. */
  52905. GPUParticleSystem.prototype.dispose = function (disposeTexture) {
  52906. if (disposeTexture === void 0) { disposeTexture = true; }
  52907. var index = this._scene.particleSystems.indexOf(this);
  52908. if (index > -1) {
  52909. this._scene.particleSystems.splice(index, 1);
  52910. }
  52911. this._releaseBuffers();
  52912. this._releaseVAOs();
  52913. if (this._randomTexture) {
  52914. this._randomTexture.dispose();
  52915. this._randomTexture = null;
  52916. }
  52917. if (disposeTexture && this.particleTexture) {
  52918. this.particleTexture.dispose();
  52919. this.particleTexture = null;
  52920. }
  52921. // Callback
  52922. this.onDisposeObservable.notifyObservers(this);
  52923. this.onDisposeObservable.clear();
  52924. };
  52925. /**
  52926. * Clones the particle system.
  52927. * @param name The name of the cloned object
  52928. * @param newEmitter The new emitter to use
  52929. * @returns the cloned particle system
  52930. */
  52931. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  52932. var result = new GPUParticleSystem(name, { capacity: this._capacity, randomTextureSize: this._randomTextureSize }, this._scene);
  52933. BABYLON.Tools.DeepCopy(this, result);
  52934. if (newEmitter === undefined) {
  52935. newEmitter = this.emitter;
  52936. }
  52937. result.emitter = newEmitter;
  52938. if (this.particleTexture) {
  52939. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  52940. }
  52941. return result;
  52942. };
  52943. /**
  52944. * Serializes the particle system to a JSON object.
  52945. * @returns the JSON object
  52946. */
  52947. GPUParticleSystem.prototype.serialize = function () {
  52948. var serializationObject = {};
  52949. serializationObject.name = this.name;
  52950. serializationObject.id = this.id;
  52951. // Emitter
  52952. if (this.emitter.position) {
  52953. var emitterMesh = this.emitter;
  52954. serializationObject.emitterId = emitterMesh.id;
  52955. }
  52956. else {
  52957. var emitterPosition = this.emitter;
  52958. serializationObject.emitter = emitterPosition.asArray();
  52959. }
  52960. serializationObject.capacity = this.getCapacity();
  52961. if (this.particleTexture) {
  52962. serializationObject.textureName = this.particleTexture.name;
  52963. }
  52964. // Animations
  52965. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  52966. // Particle system
  52967. serializationObject.activeParticleCount = this.activeParticleCount;
  52968. serializationObject.randomTextureSize = this._randomTextureSize;
  52969. serializationObject.minSize = this.minSize;
  52970. serializationObject.maxSize = this.maxSize;
  52971. serializationObject.minEmitPower = this.minEmitPower;
  52972. serializationObject.maxEmitPower = this.maxEmitPower;
  52973. serializationObject.minLifeTime = this.minLifeTime;
  52974. serializationObject.maxLifeTime = this.maxLifeTime;
  52975. serializationObject.emitRate = this.emitRate;
  52976. serializationObject.gravity = this.gravity.asArray();
  52977. serializationObject.color1 = this.color1.asArray();
  52978. serializationObject.color2 = this.color2.asArray();
  52979. serializationObject.colorDead = this.colorDead.asArray();
  52980. serializationObject.updateSpeed = this.updateSpeed;
  52981. serializationObject.targetStopDuration = this.targetStopDuration;
  52982. serializationObject.blendMode = this.blendMode;
  52983. // Emitter
  52984. if (this.particleEmitterType) {
  52985. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  52986. }
  52987. return serializationObject;
  52988. };
  52989. /**
  52990. * Parses a JSON object to create a GPU particle system.
  52991. * @param parsedParticleSystem The JSON object to parse
  52992. * @param scene The scene to create the particle system in
  52993. * @param rootUrl The root url to use to load external dependencies like texture
  52994. * @returns the parsed GPU particle system
  52995. */
  52996. GPUParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  52997. var name = parsedParticleSystem.name;
  52998. var particleSystem = new GPUParticleSystem(name, { capacity: parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, scene);
  52999. if (parsedParticleSystem.id) {
  53000. particleSystem.id = parsedParticleSystem.id;
  53001. }
  53002. // Texture
  53003. if (parsedParticleSystem.textureName) {
  53004. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  53005. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  53006. }
  53007. // Emitter
  53008. if (parsedParticleSystem.emitterId) {
  53009. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  53010. }
  53011. else {
  53012. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  53013. }
  53014. // Animations
  53015. if (parsedParticleSystem.animations) {
  53016. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  53017. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  53018. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  53019. }
  53020. }
  53021. // Particle system
  53022. particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;
  53023. particleSystem.minSize = parsedParticleSystem.minSize;
  53024. particleSystem.maxSize = parsedParticleSystem.maxSize;
  53025. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  53026. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  53027. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  53028. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  53029. particleSystem.emitRate = parsedParticleSystem.emitRate;
  53030. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  53031. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  53032. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  53033. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  53034. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  53035. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  53036. particleSystem.blendMode = parsedParticleSystem.blendMode;
  53037. // Emitter
  53038. if (parsedParticleSystem.particleEmitterType) {
  53039. var emitterType = void 0;
  53040. switch (parsedParticleSystem.particleEmitterType.type) {
  53041. case "SphereEmitter":
  53042. emitterType = new BABYLON.SphereParticleEmitter();
  53043. break;
  53044. case "SphereDirectedParticleEmitter":
  53045. emitterType = new BABYLON.SphereDirectedParticleEmitter();
  53046. break;
  53047. case "ConeEmitter":
  53048. emitterType = new BABYLON.ConeParticleEmitter();
  53049. break;
  53050. case "BoxEmitter":
  53051. default:
  53052. emitterType = new BABYLON.BoxParticleEmitter();
  53053. break;
  53054. }
  53055. emitterType.parse(parsedParticleSystem.particleEmitterType);
  53056. particleSystem.particleEmitterType = emitterType;
  53057. }
  53058. return particleSystem;
  53059. };
  53060. return GPUParticleSystem;
  53061. }());
  53062. BABYLON.GPUParticleSystem = GPUParticleSystem;
  53063. })(BABYLON || (BABYLON = {}));
  53064. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  53065. var BABYLON;
  53066. (function (BABYLON) {
  53067. /**
  53068. * Represents one particle of a solid particle system.
  53069. * @see SolidParticleSystem
  53070. */
  53071. var SolidParticle = /** @class */ (function () {
  53072. /**
  53073. * Creates a Solid Particle object.
  53074. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  53075. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  53076. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  53077. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  53078. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  53079. * @param shapeId (integer) is the model shape identifier in the SPS.
  53080. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  53081. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  53082. */
  53083. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  53084. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  53085. /**
  53086. * particle global index
  53087. */
  53088. this.idx = 0;
  53089. /**
  53090. * The color of the particle
  53091. */
  53092. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  53093. /**
  53094. * The world space position of the particle.
  53095. */
  53096. this.position = BABYLON.Vector3.Zero();
  53097. /**
  53098. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  53099. */
  53100. this.rotation = BABYLON.Vector3.Zero();
  53101. /**
  53102. * The scaling of the particle.
  53103. */
  53104. this.scaling = BABYLON.Vector3.One();
  53105. /**
  53106. * The uvs of the particle.
  53107. */
  53108. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  53109. /**
  53110. * The current speed of the particle.
  53111. */
  53112. this.velocity = BABYLON.Vector3.Zero();
  53113. /**
  53114. * The pivot point in the particle local space.
  53115. */
  53116. this.pivot = BABYLON.Vector3.Zero();
  53117. /**
  53118. * Must the particle be translated from its pivot point in its local space ?
  53119. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  53120. * Default : false
  53121. */
  53122. this.translateFromPivot = false;
  53123. /**
  53124. * Is the particle active or not ?
  53125. */
  53126. this.alive = true;
  53127. /**
  53128. * Is the particle visible or not ?
  53129. */
  53130. this.isVisible = true;
  53131. /**
  53132. * Index of this particle in the global "positions" array (Internal use)
  53133. */
  53134. this._pos = 0;
  53135. /**
  53136. * Index of this particle in the global "indices" array (Internal use)
  53137. */
  53138. this._ind = 0;
  53139. /**
  53140. * ModelShape id of this particle
  53141. */
  53142. this.shapeId = 0;
  53143. /**
  53144. * Index of the particle in its shape id (Internal use)
  53145. */
  53146. this.idxInShape = 0;
  53147. /**
  53148. * Still set as invisible in order to skip useless computations (Internal use)
  53149. */
  53150. this._stillInvisible = false;
  53151. /**
  53152. * Last computed particle rotation matrix
  53153. */
  53154. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  53155. /**
  53156. * Parent particle Id, if any.
  53157. * Default null.
  53158. */
  53159. this.parentId = null;
  53160. /**
  53161. * Internal global position in the SPS.
  53162. */
  53163. this._globalPosition = BABYLON.Vector3.Zero();
  53164. this.idx = particleIndex;
  53165. this._pos = positionIndex;
  53166. this._ind = indiceIndex;
  53167. this._model = model;
  53168. this.shapeId = shapeId;
  53169. this.idxInShape = idxInShape;
  53170. this._sps = sps;
  53171. if (modelBoundingInfo) {
  53172. this._modelBoundingInfo = modelBoundingInfo;
  53173. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  53174. }
  53175. }
  53176. Object.defineProperty(SolidParticle.prototype, "scale", {
  53177. /**
  53178. * Legacy support, changed scale to scaling
  53179. */
  53180. get: function () {
  53181. return this.scaling;
  53182. },
  53183. /**
  53184. * Legacy support, changed scale to scaling
  53185. */
  53186. set: function (scale) {
  53187. this.scaling = scale;
  53188. },
  53189. enumerable: true,
  53190. configurable: true
  53191. });
  53192. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  53193. /**
  53194. * Legacy support, changed quaternion to rotationQuaternion
  53195. */
  53196. get: function () {
  53197. return this.rotationQuaternion;
  53198. },
  53199. /**
  53200. * Legacy support, changed quaternion to rotationQuaternion
  53201. */
  53202. set: function (q) {
  53203. this.rotationQuaternion = q;
  53204. },
  53205. enumerable: true,
  53206. configurable: true
  53207. });
  53208. /**
  53209. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  53210. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  53211. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  53212. * @returns true if it intersects
  53213. */
  53214. SolidParticle.prototype.intersectsMesh = function (target) {
  53215. if (!this._boundingInfo || !target._boundingInfo) {
  53216. return false;
  53217. }
  53218. if (this._sps._bSphereOnly) {
  53219. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  53220. }
  53221. return this._boundingInfo.intersects(target._boundingInfo, false);
  53222. };
  53223. return SolidParticle;
  53224. }());
  53225. BABYLON.SolidParticle = SolidParticle;
  53226. /**
  53227. * Represents the shape of the model used by one particle of a solid particle system.
  53228. * SPS internal tool, don't use it manually.
  53229. * @see SolidParticleSystem
  53230. */
  53231. var ModelShape = /** @class */ (function () {
  53232. /**
  53233. * Creates a ModelShape object. This is an internal simplified reference to a mesh used as for a model to replicate particles from by the SPS.
  53234. * SPS internal tool, don't use it manually.
  53235. * @ignore
  53236. */
  53237. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  53238. /**
  53239. * length of the shape in the model indices array (internal use)
  53240. */
  53241. this._indicesLength = 0;
  53242. this.shapeID = id;
  53243. this._shape = shape;
  53244. this._indicesLength = indicesLength;
  53245. this._shapeUV = shapeUV;
  53246. this._positionFunction = posFunction;
  53247. this._vertexFunction = vtxFunction;
  53248. }
  53249. return ModelShape;
  53250. }());
  53251. BABYLON.ModelShape = ModelShape;
  53252. /**
  53253. * Represents a Depth Sorted Particle in the solid particle system.
  53254. * @see SolidParticleSystem
  53255. */
  53256. var DepthSortedParticle = /** @class */ (function () {
  53257. function DepthSortedParticle() {
  53258. /**
  53259. * Index of the particle in the "indices" array
  53260. */
  53261. this.ind = 0;
  53262. /**
  53263. * Length of the particle shape in the "indices" array
  53264. */
  53265. this.indicesLength = 0;
  53266. /**
  53267. * Squared distance from the particle to the camera
  53268. */
  53269. this.sqDistance = 0.0;
  53270. }
  53271. return DepthSortedParticle;
  53272. }());
  53273. BABYLON.DepthSortedParticle = DepthSortedParticle;
  53274. })(BABYLON || (BABYLON = {}));
  53275. //# sourceMappingURL=babylon.solidParticle.js.map
  53276. var BABYLON;
  53277. (function (BABYLON) {
  53278. /**
  53279. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  53280. *As it is just a mesh, the SPS has all the same properties than any other BJS mesh : not more, not less. It can be scaled, rotated, translated, enlighted, textured, moved, etc.
  53281. * The SPS is also a particle system. It provides some methods to manage the particles.
  53282. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  53283. *
  53284. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  53285. */
  53286. var SolidParticleSystem = /** @class */ (function () {
  53287. /**
  53288. * Creates a SPS (Solid Particle System) object.
  53289. * @param name (String) is the SPS name, this will be the underlying mesh name.
  53290. * @param scene (Scene) is the scene in which the SPS is added.
  53291. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  53292. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  53293. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  53294. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  53295. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  53296. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  53297. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  53298. */
  53299. function SolidParticleSystem(name, scene, options) {
  53300. /**
  53301. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  53302. * Example : var p = SPS.particles[i];
  53303. */
  53304. this.particles = new Array();
  53305. /**
  53306. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  53307. */
  53308. this.nbParticles = 0;
  53309. /**
  53310. * If the particles must ever face the camera (default false). Useful for planar particles.
  53311. */
  53312. this.billboard = false;
  53313. /**
  53314. * Recompute normals when adding a shape
  53315. */
  53316. this.recomputeNormals = true;
  53317. /**
  53318. * This a counter ofr your own usage. It's not set by any SPS functions.
  53319. */
  53320. this.counter = 0;
  53321. /**
  53322. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  53323. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  53324. */
  53325. this.vars = {};
  53326. /**
  53327. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  53328. */
  53329. this._bSphereOnly = false;
  53330. /**
  53331. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  53332. */
  53333. this._bSphereRadiusFactor = 1.0;
  53334. this._positions = new Array();
  53335. this._indices = new Array();
  53336. this._normals = new Array();
  53337. this._colors = new Array();
  53338. this._uvs = new Array();
  53339. this._index = 0; // indices index
  53340. this._updatable = true;
  53341. this._pickable = false;
  53342. this._isVisibilityBoxLocked = false;
  53343. this._alwaysVisible = false;
  53344. this._depthSort = false;
  53345. this._shapeCounter = 0;
  53346. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  53347. this._color = new BABYLON.Color4(0, 0, 0, 0);
  53348. this._computeParticleColor = true;
  53349. this._computeParticleTexture = true;
  53350. this._computeParticleRotation = true;
  53351. this._computeParticleVertex = false;
  53352. this._computeBoundingBox = false;
  53353. this._depthSortParticles = true;
  53354. this._cam_axisZ = BABYLON.Vector3.Zero();
  53355. this._cam_axisY = BABYLON.Vector3.Zero();
  53356. this._cam_axisX = BABYLON.Vector3.Zero();
  53357. this._axisZ = BABYLON.Axis.Z;
  53358. this._camDir = BABYLON.Vector3.Zero();
  53359. this._camInvertedPosition = BABYLON.Vector3.Zero();
  53360. this._rotMatrix = new BABYLON.Matrix();
  53361. this._invertMatrix = new BABYLON.Matrix();
  53362. this._rotated = BABYLON.Vector3.Zero();
  53363. this._quaternion = new BABYLON.Quaternion();
  53364. this._vertex = BABYLON.Vector3.Zero();
  53365. this._normal = BABYLON.Vector3.Zero();
  53366. this._yaw = 0.0;
  53367. this._pitch = 0.0;
  53368. this._roll = 0.0;
  53369. this._halfroll = 0.0;
  53370. this._halfpitch = 0.0;
  53371. this._halfyaw = 0.0;
  53372. this._sinRoll = 0.0;
  53373. this._cosRoll = 0.0;
  53374. this._sinPitch = 0.0;
  53375. this._cosPitch = 0.0;
  53376. this._sinYaw = 0.0;
  53377. this._cosYaw = 0.0;
  53378. this._mustUnrotateFixedNormals = false;
  53379. this._minimum = BABYLON.Vector3.Zero();
  53380. this._maximum = BABYLON.Vector3.Zero();
  53381. this._minBbox = BABYLON.Vector3.Zero();
  53382. this._maxBbox = BABYLON.Vector3.Zero();
  53383. this._particlesIntersect = false;
  53384. this._depthSortFunction = function (p1, p2) {
  53385. return (p2.sqDistance - p1.sqDistance);
  53386. };
  53387. this._needs32Bits = false;
  53388. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  53389. this._scaledPivot = BABYLON.Vector3.Zero();
  53390. this._particleHasParent = false;
  53391. this.name = name;
  53392. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  53393. this._camera = scene.activeCamera;
  53394. this._pickable = options ? options.isPickable : false;
  53395. this._depthSort = options ? options.enableDepthSort : false;
  53396. this._particlesIntersect = options ? options.particleIntersection : false;
  53397. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  53398. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  53399. if (options && options.updatable) {
  53400. this._updatable = options.updatable;
  53401. }
  53402. else {
  53403. this._updatable = true;
  53404. }
  53405. if (this._pickable) {
  53406. this.pickedParticles = [];
  53407. }
  53408. if (this._depthSort) {
  53409. this.depthSortedParticles = [];
  53410. }
  53411. }
  53412. /**
  53413. * Builds the SPS underlying mesh. Returns a standard Mesh.
  53414. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  53415. * @returns the created mesh
  53416. */
  53417. SolidParticleSystem.prototype.buildMesh = function () {
  53418. if (this.nbParticles === 0) {
  53419. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  53420. this.addShape(triangle, 1);
  53421. triangle.dispose();
  53422. }
  53423. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  53424. this._positions32 = new Float32Array(this._positions);
  53425. this._uvs32 = new Float32Array(this._uvs);
  53426. this._colors32 = new Float32Array(this._colors);
  53427. if (this.recomputeNormals) {
  53428. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  53429. }
  53430. this._normals32 = new Float32Array(this._normals);
  53431. this._fixedNormal32 = new Float32Array(this._normals);
  53432. if (this._mustUnrotateFixedNormals) {
  53433. this._unrotateFixedNormals();
  53434. }
  53435. var vertexData = new BABYLON.VertexData();
  53436. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  53437. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  53438. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  53439. if (this._uvs32) {
  53440. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  53441. ;
  53442. }
  53443. if (this._colors32) {
  53444. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  53445. }
  53446. var mesh = new BABYLON.Mesh(this.name, this._scene);
  53447. vertexData.applyToMesh(mesh, this._updatable);
  53448. this.mesh = mesh;
  53449. this.mesh.isPickable = this._pickable;
  53450. // free memory
  53451. if (!this._depthSort) {
  53452. this._indices = null;
  53453. }
  53454. this._positions = null;
  53455. this._normals = null;
  53456. this._uvs = null;
  53457. this._colors = null;
  53458. if (!this._updatable) {
  53459. this.particles.length = 0;
  53460. }
  53461. return mesh;
  53462. };
  53463. /**
  53464. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  53465. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  53466. * Thus the particles generated from `digest()` have their property `position` set yet.
  53467. * @param mesh ( Mesh ) is the mesh to be digested
  53468. * @param options {facetNb} (optional integer, default 1) is the number of mesh facets per particle, this parameter is overriden by the parameter `number` if any
  53469. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  53470. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  53471. * @returns the current SPS
  53472. */
  53473. SolidParticleSystem.prototype.digest = function (mesh, options) {
  53474. var size = (options && options.facetNb) || 1;
  53475. var number = (options && options.number) || 0;
  53476. var delta = (options && options.delta) || 0;
  53477. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  53478. var meshInd = mesh.getIndices();
  53479. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  53480. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  53481. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  53482. var f = 0; // facet counter
  53483. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  53484. // compute size from number
  53485. if (number) {
  53486. number = (number > totalFacets) ? totalFacets : number;
  53487. size = Math.round(totalFacets / number);
  53488. delta = 0;
  53489. }
  53490. else {
  53491. size = (size > totalFacets) ? totalFacets : size;
  53492. }
  53493. var facetPos = []; // submesh positions
  53494. var facetInd = []; // submesh indices
  53495. var facetUV = []; // submesh UV
  53496. var facetCol = []; // submesh colors
  53497. var barycenter = BABYLON.Vector3.Zero();
  53498. var sizeO = size;
  53499. while (f < totalFacets) {
  53500. size = sizeO + Math.floor((1 + delta) * Math.random());
  53501. if (f > totalFacets - size) {
  53502. size = totalFacets - f;
  53503. }
  53504. // reset temp arrays
  53505. facetPos.length = 0;
  53506. facetInd.length = 0;
  53507. facetUV.length = 0;
  53508. facetCol.length = 0;
  53509. // iterate over "size" facets
  53510. var fi = 0;
  53511. for (var j = f * 3; j < (f + size) * 3; j++) {
  53512. facetInd.push(fi);
  53513. var i = meshInd[j];
  53514. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  53515. if (meshUV) {
  53516. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  53517. }
  53518. if (meshCol) {
  53519. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  53520. }
  53521. fi++;
  53522. }
  53523. // create a model shape for each single particle
  53524. var idx = this.nbParticles;
  53525. var shape = this._posToShape(facetPos);
  53526. var shapeUV = this._uvsToShapeUV(facetUV);
  53527. // compute the barycenter of the shape
  53528. var v;
  53529. for (v = 0; v < shape.length; v++) {
  53530. barycenter.addInPlace(shape[v]);
  53531. }
  53532. barycenter.scaleInPlace(1 / shape.length);
  53533. // shift the shape from its barycenter to the origin
  53534. for (v = 0; v < shape.length; v++) {
  53535. shape[v].subtractInPlace(barycenter);
  53536. }
  53537. var bInfo;
  53538. if (this._particlesIntersect) {
  53539. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  53540. }
  53541. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  53542. // add the particle in the SPS
  53543. var currentPos = this._positions.length;
  53544. var currentInd = this._indices.length;
  53545. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  53546. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  53547. // initialize the particle position
  53548. this.particles[this.nbParticles].position.addInPlace(barycenter);
  53549. this._index += shape.length;
  53550. idx++;
  53551. this.nbParticles++;
  53552. this._shapeCounter++;
  53553. f += size;
  53554. }
  53555. return this;
  53556. };
  53557. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  53558. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  53559. var index = 0;
  53560. var idx = 0;
  53561. for (var p = 0; p < this.particles.length; p++) {
  53562. this._particle = this.particles[p];
  53563. this._shape = this._particle._model._shape;
  53564. if (this._particle.rotationQuaternion) {
  53565. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  53566. }
  53567. else {
  53568. this._yaw = this._particle.rotation.y;
  53569. this._pitch = this._particle.rotation.x;
  53570. this._roll = this._particle.rotation.z;
  53571. this._quaternionRotationYPR();
  53572. }
  53573. this._quaternionToRotationMatrix();
  53574. this._rotMatrix.invertToRef(this._invertMatrix);
  53575. for (var pt = 0; pt < this._shape.length; pt++) {
  53576. idx = index + pt * 3;
  53577. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  53578. this._fixedNormal32[idx] = this._normal.x;
  53579. this._fixedNormal32[idx + 1] = this._normal.y;
  53580. this._fixedNormal32[idx + 2] = this._normal.z;
  53581. }
  53582. index = idx + 3;
  53583. }
  53584. };
  53585. //reset copy
  53586. SolidParticleSystem.prototype._resetCopy = function () {
  53587. this._copy.position.x = 0;
  53588. this._copy.position.y = 0;
  53589. this._copy.position.z = 0;
  53590. this._copy.rotation.x = 0;
  53591. this._copy.rotation.y = 0;
  53592. this._copy.rotation.z = 0;
  53593. this._copy.rotationQuaternion = null;
  53594. this._copy.scaling.x = 1.0;
  53595. this._copy.scaling.y = 1.0;
  53596. this._copy.scaling.z = 1.0;
  53597. this._copy.uvs.x = 0;
  53598. this._copy.uvs.y = 0;
  53599. this._copy.uvs.z = 1.0;
  53600. this._copy.uvs.w = 1.0;
  53601. this._copy.color = null;
  53602. this._copy.translateFromPivot = false;
  53603. };
  53604. // _meshBuilder : inserts the shape model in the global SPS mesh
  53605. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  53606. var i;
  53607. var u = 0;
  53608. var c = 0;
  53609. var n = 0;
  53610. this._resetCopy();
  53611. if (options && options.positionFunction) {
  53612. options.positionFunction(this._copy, idx, idxInShape);
  53613. this._mustUnrotateFixedNormals = true;
  53614. }
  53615. if (this._copy.rotationQuaternion) {
  53616. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  53617. }
  53618. else {
  53619. this._yaw = this._copy.rotation.y;
  53620. this._pitch = this._copy.rotation.x;
  53621. this._roll = this._copy.rotation.z;
  53622. this._quaternionRotationYPR();
  53623. }
  53624. this._quaternionToRotationMatrix();
  53625. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  53626. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  53627. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  53628. if (this._copy.translateFromPivot) {
  53629. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  53630. }
  53631. else {
  53632. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  53633. }
  53634. for (i = 0; i < shape.length; i++) {
  53635. this._vertex.x = shape[i].x;
  53636. this._vertex.y = shape[i].y;
  53637. this._vertex.z = shape[i].z;
  53638. if (options && options.vertexFunction) {
  53639. options.vertexFunction(this._copy, this._vertex, i);
  53640. }
  53641. this._vertex.x *= this._copy.scaling.x;
  53642. this._vertex.y *= this._copy.scaling.y;
  53643. this._vertex.z *= this._copy.scaling.z;
  53644. this._vertex.x -= this._scaledPivot.x;
  53645. this._vertex.y -= this._scaledPivot.y;
  53646. this._vertex.z -= this._scaledPivot.z;
  53647. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  53648. this._rotated.addInPlace(this._pivotBackTranslation);
  53649. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  53650. if (meshUV) {
  53651. uvs.push((this._copy.uvs.z - this._copy.uvs.x) * meshUV[u] + this._copy.uvs.x, (this._copy.uvs.w - this._copy.uvs.y) * meshUV[u + 1] + this._copy.uvs.y);
  53652. u += 2;
  53653. }
  53654. if (this._copy.color) {
  53655. this._color = this._copy.color;
  53656. }
  53657. else if (meshCol && meshCol[c] !== undefined) {
  53658. this._color.r = meshCol[c];
  53659. this._color.g = meshCol[c + 1];
  53660. this._color.b = meshCol[c + 2];
  53661. this._color.a = meshCol[c + 3];
  53662. }
  53663. else {
  53664. this._color.r = 1.0;
  53665. this._color.g = 1.0;
  53666. this._color.b = 1.0;
  53667. this._color.a = 1.0;
  53668. }
  53669. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  53670. c += 4;
  53671. if (!this.recomputeNormals && meshNor) {
  53672. this._normal.x = meshNor[n];
  53673. this._normal.y = meshNor[n + 1];
  53674. this._normal.z = meshNor[n + 2];
  53675. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  53676. normals.push(this._normal.x, this._normal.y, this._normal.z);
  53677. n += 3;
  53678. }
  53679. }
  53680. for (i = 0; i < meshInd.length; i++) {
  53681. var current_ind = p + meshInd[i];
  53682. indices.push(current_ind);
  53683. if (current_ind > 65535) {
  53684. this._needs32Bits = true;
  53685. }
  53686. }
  53687. if (this._pickable) {
  53688. var nbfaces = meshInd.length / 3;
  53689. for (i = 0; i < nbfaces; i++) {
  53690. this.pickedParticles.push({ idx: idx, faceId: i });
  53691. }
  53692. }
  53693. if (this._depthSort) {
  53694. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  53695. }
  53696. return this._copy;
  53697. };
  53698. // returns a shape array from positions array
  53699. SolidParticleSystem.prototype._posToShape = function (positions) {
  53700. var shape = [];
  53701. for (var i = 0; i < positions.length; i += 3) {
  53702. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  53703. }
  53704. return shape;
  53705. };
  53706. // returns a shapeUV array from a Vector4 uvs
  53707. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  53708. var shapeUV = [];
  53709. if (uvs) {
  53710. for (var i = 0; i < uvs.length; i++)
  53711. shapeUV.push(uvs[i]);
  53712. }
  53713. return shapeUV;
  53714. };
  53715. // adds a new particle object in the particles array
  53716. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  53717. if (bInfo === void 0) { bInfo = null; }
  53718. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  53719. this.particles.push(sp);
  53720. return sp;
  53721. };
  53722. /**
  53723. * Adds some particles to the SPS from the model shape. Returns the shape id.
  53724. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  53725. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  53726. * @param nb (positive integer) the number of particles to be created from this model
  53727. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  53728. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  53729. * @returns the number of shapes in the system
  53730. */
  53731. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  53732. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  53733. var meshInd = mesh.getIndices();
  53734. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  53735. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  53736. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  53737. var bbInfo;
  53738. if (this._particlesIntersect) {
  53739. bbInfo = mesh.getBoundingInfo();
  53740. }
  53741. var shape = this._posToShape(meshPos);
  53742. var shapeUV = this._uvsToShapeUV(meshUV);
  53743. var posfunc = options ? options.positionFunction : null;
  53744. var vtxfunc = options ? options.vertexFunction : null;
  53745. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  53746. // particles
  53747. var sp;
  53748. var currentCopy;
  53749. var idx = this.nbParticles;
  53750. for (var i = 0; i < nb; i++) {
  53751. var currentPos = this._positions.length;
  53752. var currentInd = this._indices.length;
  53753. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  53754. if (this._updatable) {
  53755. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  53756. sp.position.copyFrom(currentCopy.position);
  53757. sp.rotation.copyFrom(currentCopy.rotation);
  53758. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  53759. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  53760. }
  53761. if (currentCopy.color && sp.color) {
  53762. sp.color.copyFrom(currentCopy.color);
  53763. }
  53764. sp.scaling.copyFrom(currentCopy.scaling);
  53765. sp.uvs.copyFrom(currentCopy.uvs);
  53766. }
  53767. this._index += shape.length;
  53768. idx++;
  53769. }
  53770. this.nbParticles += nb;
  53771. this._shapeCounter++;
  53772. return this._shapeCounter - 1;
  53773. };
  53774. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  53775. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  53776. this._resetCopy();
  53777. if (particle._model._positionFunction) {
  53778. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  53779. }
  53780. if (this._copy.rotationQuaternion) {
  53781. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  53782. }
  53783. else {
  53784. this._yaw = this._copy.rotation.y;
  53785. this._pitch = this._copy.rotation.x;
  53786. this._roll = this._copy.rotation.z;
  53787. this._quaternionRotationYPR();
  53788. }
  53789. this._quaternionToRotationMatrix();
  53790. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  53791. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  53792. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  53793. if (this._copy.translateFromPivot) {
  53794. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  53795. }
  53796. else {
  53797. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  53798. }
  53799. this._shape = particle._model._shape;
  53800. for (var pt = 0; pt < this._shape.length; pt++) {
  53801. this._vertex.x = this._shape[pt].x;
  53802. this._vertex.y = this._shape[pt].y;
  53803. this._vertex.z = this._shape[pt].z;
  53804. if (particle._model._vertexFunction) {
  53805. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  53806. }
  53807. this._vertex.x *= this._copy.scaling.x;
  53808. this._vertex.y *= this._copy.scaling.y;
  53809. this._vertex.z *= this._copy.scaling.z;
  53810. this._vertex.x -= this._scaledPivot.x;
  53811. this._vertex.y -= this._scaledPivot.y;
  53812. this._vertex.z -= this._scaledPivot.z;
  53813. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  53814. this._rotated.addInPlace(this._pivotBackTranslation);
  53815. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  53816. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  53817. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  53818. }
  53819. particle.position.x = 0.0;
  53820. particle.position.y = 0.0;
  53821. particle.position.z = 0.0;
  53822. particle.rotation.x = 0.0;
  53823. particle.rotation.y = 0.0;
  53824. particle.rotation.z = 0.0;
  53825. particle.rotationQuaternion = null;
  53826. particle.scaling.x = 1.0;
  53827. particle.scaling.y = 1.0;
  53828. particle.scaling.z = 1.0;
  53829. particle.uvs.x = 0.0;
  53830. particle.uvs.y = 0.0;
  53831. particle.uvs.z = 1.0;
  53832. particle.uvs.w = 1.0;
  53833. particle.pivot.x = 0.0;
  53834. particle.pivot.y = 0.0;
  53835. particle.pivot.z = 0.0;
  53836. particle.translateFromPivot = false;
  53837. particle.parentId = null;
  53838. };
  53839. /**
  53840. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  53841. * @returns the SPS.
  53842. */
  53843. SolidParticleSystem.prototype.rebuildMesh = function () {
  53844. for (var p = 0; p < this.particles.length; p++) {
  53845. this._rebuildParticle(this.particles[p]);
  53846. }
  53847. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  53848. return this;
  53849. };
  53850. /**
  53851. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  53852. * This method calls `updateParticle()` for each particle of the SPS.
  53853. * For an animated SPS, it is usually called within the render loop.
  53854. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  53855. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  53856. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  53857. * @returns the SPS.
  53858. */
  53859. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  53860. if (start === void 0) { start = 0; }
  53861. if (end === void 0) { end = this.nbParticles - 1; }
  53862. if (update === void 0) { update = true; }
  53863. if (!this._updatable) {
  53864. return this;
  53865. }
  53866. // custom beforeUpdate
  53867. this.beforeUpdateParticles(start, end, update);
  53868. this._cam_axisX.x = 1.0;
  53869. this._cam_axisX.y = 0.0;
  53870. this._cam_axisX.z = 0.0;
  53871. this._cam_axisY.x = 0.0;
  53872. this._cam_axisY.y = 1.0;
  53873. this._cam_axisY.z = 0.0;
  53874. this._cam_axisZ.x = 0.0;
  53875. this._cam_axisZ.y = 0.0;
  53876. this._cam_axisZ.z = 1.0;
  53877. // cases when the World Matrix is to be computed first
  53878. if (this.billboard || this._depthSort) {
  53879. this.mesh.computeWorldMatrix(true);
  53880. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  53881. }
  53882. // if the particles will always face the camera
  53883. if (this.billboard) {
  53884. // compute the camera position and un-rotate it by the current mesh rotation
  53885. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  53886. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  53887. this._cam_axisZ.normalize();
  53888. // same for camera up vector extracted from the cam view matrix
  53889. var view = this._camera.getViewMatrix(true);
  53890. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  53891. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  53892. this._cam_axisY.normalize();
  53893. this._cam_axisX.normalize();
  53894. }
  53895. // if depthSort, compute the camera global position in the mesh local system
  53896. if (this._depthSort) {
  53897. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  53898. }
  53899. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  53900. var idx = 0; // current position index in the global array positions32
  53901. var index = 0; // position start index in the global array positions32 of the current particle
  53902. var colidx = 0; // current color index in the global array colors32
  53903. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  53904. var uvidx = 0; // current uv index in the global array uvs32
  53905. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  53906. var pt = 0; // current index in the particle model shape
  53907. if (this.mesh.isFacetDataEnabled) {
  53908. this._computeBoundingBox = true;
  53909. }
  53910. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  53911. if (this._computeBoundingBox) {
  53912. if (start == 0 && end == this.nbParticles - 1) {
  53913. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  53914. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  53915. }
  53916. else {
  53917. if (this.mesh._boundingInfo) {
  53918. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  53919. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  53920. }
  53921. }
  53922. }
  53923. // particle loop
  53924. index = this.particles[start]._pos;
  53925. var vpos = (index / 3) | 0;
  53926. colorIndex = vpos * 4;
  53927. uvIndex = vpos * 2;
  53928. for (var p = start; p <= end; p++) {
  53929. this._particle = this.particles[p];
  53930. this._shape = this._particle._model._shape;
  53931. this._shapeUV = this._particle._model._shapeUV;
  53932. // call to custom user function to update the particle properties
  53933. this.updateParticle(this._particle);
  53934. // camera-particle distance for depth sorting
  53935. if (this._depthSort && this._depthSortParticles) {
  53936. var dsp = this.depthSortedParticles[p];
  53937. dsp.ind = this._particle._ind;
  53938. dsp.indicesLength = this._particle._model._indicesLength;
  53939. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  53940. }
  53941. // skip the computations for inactive or already invisible particles
  53942. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  53943. // increment indexes for the next particle
  53944. pt = this._shape.length;
  53945. index += pt * 3;
  53946. colorIndex += pt * 4;
  53947. uvIndex += pt * 2;
  53948. continue;
  53949. }
  53950. if (this._particle.isVisible) {
  53951. this._particle._stillInvisible = false; // un-mark permanent invisibility
  53952. this._particleHasParent = (this._particle.parentId !== null);
  53953. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  53954. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  53955. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  53956. // particle rotation matrix
  53957. if (this.billboard) {
  53958. this._particle.rotation.x = 0.0;
  53959. this._particle.rotation.y = 0.0;
  53960. }
  53961. if (this._computeParticleRotation || this.billboard) {
  53962. if (this._particle.rotationQuaternion) {
  53963. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  53964. }
  53965. else {
  53966. this._yaw = this._particle.rotation.y;
  53967. this._pitch = this._particle.rotation.x;
  53968. this._roll = this._particle.rotation.z;
  53969. this._quaternionRotationYPR();
  53970. }
  53971. this._quaternionToRotationMatrix();
  53972. }
  53973. if (this._particleHasParent) {
  53974. this._parent = this.particles[this._particle.parentId];
  53975. this._rotated.x = this._particle.position.x * this._parent._rotationMatrix[0] + this._particle.position.y * this._parent._rotationMatrix[3] + this._particle.position.z * this._parent._rotationMatrix[6];
  53976. this._rotated.y = this._particle.position.x * this._parent._rotationMatrix[1] + this._particle.position.y * this._parent._rotationMatrix[4] + this._particle.position.z * this._parent._rotationMatrix[7];
  53977. this._rotated.z = this._particle.position.x * this._parent._rotationMatrix[2] + this._particle.position.y * this._parent._rotationMatrix[5] + this._particle.position.z * this._parent._rotationMatrix[8];
  53978. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  53979. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  53980. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  53981. if (this._computeParticleRotation || this.billboard) {
  53982. this._particle._rotationMatrix[0] = this._rotMatrix.m[0] * this._parent._rotationMatrix[0] + this._rotMatrix.m[1] * this._parent._rotationMatrix[3] + this._rotMatrix.m[2] * this._parent._rotationMatrix[6];
  53983. this._particle._rotationMatrix[1] = this._rotMatrix.m[0] * this._parent._rotationMatrix[1] + this._rotMatrix.m[1] * this._parent._rotationMatrix[4] + this._rotMatrix.m[2] * this._parent._rotationMatrix[7];
  53984. this._particle._rotationMatrix[2] = this._rotMatrix.m[0] * this._parent._rotationMatrix[2] + this._rotMatrix.m[1] * this._parent._rotationMatrix[5] + this._rotMatrix.m[2] * this._parent._rotationMatrix[8];
  53985. this._particle._rotationMatrix[3] = this._rotMatrix.m[4] * this._parent._rotationMatrix[0] + this._rotMatrix.m[5] * this._parent._rotationMatrix[3] + this._rotMatrix.m[6] * this._parent._rotationMatrix[6];
  53986. this._particle._rotationMatrix[4] = this._rotMatrix.m[4] * this._parent._rotationMatrix[1] + this._rotMatrix.m[5] * this._parent._rotationMatrix[4] + this._rotMatrix.m[6] * this._parent._rotationMatrix[7];
  53987. this._particle._rotationMatrix[5] = this._rotMatrix.m[4] * this._parent._rotationMatrix[2] + this._rotMatrix.m[5] * this._parent._rotationMatrix[5] + this._rotMatrix.m[6] * this._parent._rotationMatrix[8];
  53988. this._particle._rotationMatrix[6] = this._rotMatrix.m[8] * this._parent._rotationMatrix[0] + this._rotMatrix.m[9] * this._parent._rotationMatrix[3] + this._rotMatrix.m[10] * this._parent._rotationMatrix[6];
  53989. this._particle._rotationMatrix[7] = this._rotMatrix.m[8] * this._parent._rotationMatrix[1] + this._rotMatrix.m[9] * this._parent._rotationMatrix[4] + this._rotMatrix.m[10] * this._parent._rotationMatrix[7];
  53990. this._particle._rotationMatrix[8] = this._rotMatrix.m[8] * this._parent._rotationMatrix[2] + this._rotMatrix.m[9] * this._parent._rotationMatrix[5] + this._rotMatrix.m[10] * this._parent._rotationMatrix[8];
  53991. }
  53992. }
  53993. else {
  53994. this._particle._globalPosition.x = this._particle.position.x;
  53995. this._particle._globalPosition.y = this._particle.position.y;
  53996. this._particle._globalPosition.z = this._particle.position.z;
  53997. if (this._computeParticleRotation || this.billboard) {
  53998. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  53999. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  54000. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  54001. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  54002. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  54003. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  54004. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  54005. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  54006. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  54007. }
  54008. }
  54009. if (this._particle.translateFromPivot) {
  54010. this._pivotBackTranslation.x = 0.0;
  54011. this._pivotBackTranslation.y = 0.0;
  54012. this._pivotBackTranslation.z = 0.0;
  54013. }
  54014. else {
  54015. this._pivotBackTranslation.x = this._scaledPivot.x;
  54016. this._pivotBackTranslation.y = this._scaledPivot.y;
  54017. this._pivotBackTranslation.z = this._scaledPivot.z;
  54018. }
  54019. // particle vertex loop
  54020. for (pt = 0; pt < this._shape.length; pt++) {
  54021. idx = index + pt * 3;
  54022. colidx = colorIndex + pt * 4;
  54023. uvidx = uvIndex + pt * 2;
  54024. this._vertex.x = this._shape[pt].x;
  54025. this._vertex.y = this._shape[pt].y;
  54026. this._vertex.z = this._shape[pt].z;
  54027. if (this._computeParticleVertex) {
  54028. this.updateParticleVertex(this._particle, this._vertex, pt);
  54029. }
  54030. // positions
  54031. this._vertex.x *= this._particle.scaling.x;
  54032. this._vertex.y *= this._particle.scaling.y;
  54033. this._vertex.z *= this._particle.scaling.z;
  54034. this._vertex.x -= this._scaledPivot.x;
  54035. this._vertex.y -= this._scaledPivot.y;
  54036. this._vertex.z -= this._scaledPivot.z;
  54037. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  54038. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  54039. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  54040. this._rotated.x += this._pivotBackTranslation.x;
  54041. this._rotated.y += this._pivotBackTranslation.y;
  54042. this._rotated.z += this._pivotBackTranslation.z;
  54043. this._positions32[idx] = this._particle._globalPosition.x + this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  54044. this._positions32[idx + 1] = this._particle._globalPosition.y + this._cam_axisX.y * this._rotated.x + this._cam_axisY.y * this._rotated.y + this._cam_axisZ.y * this._rotated.z;
  54045. this._positions32[idx + 2] = this._particle._globalPosition.z + this._cam_axisX.z * this._rotated.x + this._cam_axisY.z * this._rotated.y + this._cam_axisZ.z * this._rotated.z;
  54046. if (this._computeBoundingBox) {
  54047. if (this._positions32[idx] < this._minimum.x) {
  54048. this._minimum.x = this._positions32[idx];
  54049. }
  54050. if (this._positions32[idx] > this._maximum.x) {
  54051. this._maximum.x = this._positions32[idx];
  54052. }
  54053. if (this._positions32[idx + 1] < this._minimum.y) {
  54054. this._minimum.y = this._positions32[idx + 1];
  54055. }
  54056. if (this._positions32[idx + 1] > this._maximum.y) {
  54057. this._maximum.y = this._positions32[idx + 1];
  54058. }
  54059. if (this._positions32[idx + 2] < this._minimum.z) {
  54060. this._minimum.z = this._positions32[idx + 2];
  54061. }
  54062. if (this._positions32[idx + 2] > this._maximum.z) {
  54063. this._maximum.z = this._positions32[idx + 2];
  54064. }
  54065. }
  54066. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  54067. if (!this._computeParticleVertex) {
  54068. this._normal.x = this._fixedNormal32[idx];
  54069. this._normal.y = this._fixedNormal32[idx + 1];
  54070. this._normal.z = this._fixedNormal32[idx + 2];
  54071. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  54072. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  54073. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  54074. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  54075. this._normals32[idx + 1] = this._cam_axisX.y * this._rotated.x + this._cam_axisY.y * this._rotated.y + this._cam_axisZ.y * this._rotated.z;
  54076. this._normals32[idx + 2] = this._cam_axisX.z * this._rotated.x + this._cam_axisY.z * this._rotated.y + this._cam_axisZ.z * this._rotated.z;
  54077. }
  54078. if (this._computeParticleColor && this._particle.color) {
  54079. this._colors32[colidx] = this._particle.color.r;
  54080. this._colors32[colidx + 1] = this._particle.color.g;
  54081. this._colors32[colidx + 2] = this._particle.color.b;
  54082. this._colors32[colidx + 3] = this._particle.color.a;
  54083. }
  54084. if (this._computeParticleTexture) {
  54085. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  54086. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  54087. }
  54088. }
  54089. }
  54090. else {
  54091. this._particle._stillInvisible = true; // mark the particle as invisible
  54092. for (pt = 0; pt < this._shape.length; pt++) {
  54093. idx = index + pt * 3;
  54094. colidx = colorIndex + pt * 4;
  54095. uvidx = uvIndex + pt * 2;
  54096. this._positions32[idx] = 0.0;
  54097. this._positions32[idx + 1] = 0.0;
  54098. this._positions32[idx + 2] = 0.0;
  54099. this._normals32[idx] = 0.0;
  54100. this._normals32[idx + 1] = 0.0;
  54101. this._normals32[idx + 2] = 0.0;
  54102. if (this._computeParticleColor && this._particle.color) {
  54103. this._colors32[colidx] = this._particle.color.r;
  54104. this._colors32[colidx + 1] = this._particle.color.g;
  54105. this._colors32[colidx + 2] = this._particle.color.b;
  54106. this._colors32[colidx + 3] = this._particle.color.a;
  54107. }
  54108. if (this._computeParticleTexture) {
  54109. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  54110. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  54111. }
  54112. }
  54113. }
  54114. // if the particle intersections must be computed : update the bbInfo
  54115. if (this._particlesIntersect) {
  54116. var bInfo = this._particle._boundingInfo;
  54117. var bBox = bInfo.boundingBox;
  54118. var bSphere = bInfo.boundingSphere;
  54119. if (!this._bSphereOnly) {
  54120. // place, scale and rotate the particle bbox within the SPS local system, then update it
  54121. for (var b = 0; b < bBox.vectors.length; b++) {
  54122. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  54123. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  54124. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  54125. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  54126. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  54127. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  54128. bBox.vectors[b].x = this._particle.position.x + this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  54129. bBox.vectors[b].y = this._particle.position.y + this._cam_axisX.y * this._rotated.x + this._cam_axisY.y * this._rotated.y + this._cam_axisZ.y * this._rotated.z;
  54130. bBox.vectors[b].z = this._particle.position.z + this._cam_axisX.z * this._rotated.x + this._cam_axisY.z * this._rotated.y + this._cam_axisZ.z * this._rotated.z;
  54131. }
  54132. bBox._update(this.mesh._worldMatrix);
  54133. }
  54134. // place and scale the particle bouding sphere in the SPS local system, then update it
  54135. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  54136. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  54137. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  54138. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  54139. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  54140. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  54141. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  54142. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  54143. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  54144. bSphere.radius = this._bSphereRadiusFactor * 0.5 * Math.sqrt((this._maxBbox.x - this._minBbox.x) * (this._maxBbox.x - this._minBbox.x) + (this._maxBbox.y - this._minBbox.y) * (this._maxBbox.y - this._minBbox.y) + (this._maxBbox.z - this._minBbox.z) * (this._maxBbox.z - this._minBbox.z));
  54145. bSphere._update(this.mesh._worldMatrix);
  54146. }
  54147. // increment indexes for the next particle
  54148. index = idx + 3;
  54149. colorIndex = colidx + 4;
  54150. uvIndex = uvidx + 2;
  54151. }
  54152. // if the VBO must be updated
  54153. if (update) {
  54154. if (this._computeParticleColor) {
  54155. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  54156. }
  54157. if (this._computeParticleTexture) {
  54158. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  54159. }
  54160. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  54161. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  54162. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  54163. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  54164. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  54165. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  54166. for (var i = 0; i < this._normals32.length; i++) {
  54167. this._fixedNormal32[i] = this._normals32[i];
  54168. }
  54169. }
  54170. if (!this.mesh.areNormalsFrozen) {
  54171. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  54172. }
  54173. }
  54174. if (this._depthSort && this._depthSortParticles) {
  54175. this.depthSortedParticles.sort(this._depthSortFunction);
  54176. var dspl = this.depthSortedParticles.length;
  54177. var sorted = 0;
  54178. var lind = 0;
  54179. var sind = 0;
  54180. var sid = 0;
  54181. for (sorted = 0; sorted < dspl; sorted++) {
  54182. lind = this.depthSortedParticles[sorted].indicesLength;
  54183. sind = this.depthSortedParticles[sorted].ind;
  54184. for (var i = 0; i < lind; i++) {
  54185. this._indices32[sid] = this._indices[sind + i];
  54186. sid++;
  54187. }
  54188. }
  54189. this.mesh.updateIndices(this._indices32);
  54190. }
  54191. }
  54192. if (this._computeBoundingBox) {
  54193. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  54194. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  54195. }
  54196. this.afterUpdateParticles(start, end, update);
  54197. return this;
  54198. };
  54199. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  54200. this._halfroll = this._roll * 0.5;
  54201. this._halfpitch = this._pitch * 0.5;
  54202. this._halfyaw = this._yaw * 0.5;
  54203. this._sinRoll = Math.sin(this._halfroll);
  54204. this._cosRoll = Math.cos(this._halfroll);
  54205. this._sinPitch = Math.sin(this._halfpitch);
  54206. this._cosPitch = Math.cos(this._halfpitch);
  54207. this._sinYaw = Math.sin(this._halfyaw);
  54208. this._cosYaw = Math.cos(this._halfyaw);
  54209. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  54210. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  54211. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  54212. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  54213. };
  54214. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  54215. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  54216. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  54217. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  54218. this._rotMatrix.m[3] = 0;
  54219. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  54220. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  54221. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  54222. this._rotMatrix.m[7] = 0;
  54223. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  54224. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  54225. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  54226. this._rotMatrix.m[11] = 0;
  54227. this._rotMatrix.m[12] = 0;
  54228. this._rotMatrix.m[13] = 0;
  54229. this._rotMatrix.m[14] = 0;
  54230. this._rotMatrix.m[15] = 1.0;
  54231. };
  54232. /**
  54233. * Disposes the SPS.
  54234. */
  54235. SolidParticleSystem.prototype.dispose = function () {
  54236. this.mesh.dispose();
  54237. this.vars = null;
  54238. // drop references to internal big arrays for the GC
  54239. this._positions = null;
  54240. this._indices = null;
  54241. this._normals = null;
  54242. this._uvs = null;
  54243. this._colors = null;
  54244. this._indices32 = null;
  54245. this._positions32 = null;
  54246. this._normals32 = null;
  54247. this._fixedNormal32 = null;
  54248. this._uvs32 = null;
  54249. this._colors32 = null;
  54250. this.pickedParticles = null;
  54251. };
  54252. /**
  54253. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  54254. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  54255. * @returns the SPS.
  54256. */
  54257. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  54258. if (!this._isVisibilityBoxLocked) {
  54259. this.mesh.refreshBoundingInfo();
  54260. }
  54261. return this;
  54262. };
  54263. /**
  54264. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  54265. * @param size the size (float) of the visibility box
  54266. * note : this doesn't lock the SPS mesh bounding box.
  54267. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  54268. */
  54269. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  54270. var vis = size / 2;
  54271. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  54272. };
  54273. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  54274. /**
  54275. * Gets whether the SPS as always visible or not
  54276. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  54277. */
  54278. get: function () {
  54279. return this._alwaysVisible;
  54280. },
  54281. /**
  54282. * Sets the SPS as always visible or not
  54283. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  54284. */
  54285. set: function (val) {
  54286. this._alwaysVisible = val;
  54287. this.mesh.alwaysSelectAsActiveMesh = val;
  54288. },
  54289. enumerable: true,
  54290. configurable: true
  54291. });
  54292. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  54293. /**
  54294. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  54295. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  54296. */
  54297. get: function () {
  54298. return this._isVisibilityBoxLocked;
  54299. },
  54300. /**
  54301. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  54302. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  54303. */
  54304. set: function (val) {
  54305. this._isVisibilityBoxLocked = val;
  54306. var boundingInfo = this.mesh.getBoundingInfo();
  54307. boundingInfo.isLocked = val;
  54308. },
  54309. enumerable: true,
  54310. configurable: true
  54311. });
  54312. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  54313. /**
  54314. * Gets if `setParticles()` computes the particle rotations or not.
  54315. * Default value : true. The SPS is faster when it's set to false.
  54316. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  54317. */
  54318. get: function () {
  54319. return this._computeParticleRotation;
  54320. },
  54321. /**
  54322. * Tells to `setParticles()` to compute the particle rotations or not.
  54323. * Default value : true. The SPS is faster when it's set to false.
  54324. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  54325. */
  54326. set: function (val) {
  54327. this._computeParticleRotation = val;
  54328. },
  54329. enumerable: true,
  54330. configurable: true
  54331. });
  54332. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  54333. /**
  54334. * Gets if `setParticles()` computes the particle colors or not.
  54335. * Default value : true. The SPS is faster when it's set to false.
  54336. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  54337. */
  54338. get: function () {
  54339. return this._computeParticleColor;
  54340. },
  54341. /**
  54342. * Tells to `setParticles()` to compute the particle colors or not.
  54343. * Default value : true. The SPS is faster when it's set to false.
  54344. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  54345. */
  54346. set: function (val) {
  54347. this._computeParticleColor = val;
  54348. },
  54349. enumerable: true,
  54350. configurable: true
  54351. });
  54352. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  54353. /**
  54354. * Gets if `setParticles()` computes the particle textures or not.
  54355. * Default value : true. The SPS is faster when it's set to false.
  54356. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  54357. */
  54358. get: function () {
  54359. return this._computeParticleTexture;
  54360. },
  54361. set: function (val) {
  54362. this._computeParticleTexture = val;
  54363. },
  54364. enumerable: true,
  54365. configurable: true
  54366. });
  54367. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  54368. /**
  54369. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  54370. * Default value : false. The SPS is faster when it's set to false.
  54371. * Note : the particle custom vertex positions aren't stored values.
  54372. */
  54373. get: function () {
  54374. return this._computeParticleVertex;
  54375. },
  54376. /**
  54377. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  54378. * Default value : false. The SPS is faster when it's set to false.
  54379. * Note : the particle custom vertex positions aren't stored values.
  54380. */
  54381. set: function (val) {
  54382. this._computeParticleVertex = val;
  54383. },
  54384. enumerable: true,
  54385. configurable: true
  54386. });
  54387. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  54388. /**
  54389. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  54390. */
  54391. get: function () {
  54392. return this._computeBoundingBox;
  54393. },
  54394. /**
  54395. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  54396. */
  54397. set: function (val) {
  54398. this._computeBoundingBox = val;
  54399. },
  54400. enumerable: true,
  54401. configurable: true
  54402. });
  54403. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  54404. /**
  54405. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  54406. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  54407. * Default : `true`
  54408. */
  54409. get: function () {
  54410. return this._depthSortParticles;
  54411. },
  54412. /**
  54413. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  54414. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  54415. * Default : `true`
  54416. */
  54417. set: function (val) {
  54418. this._depthSortParticles = val;
  54419. },
  54420. enumerable: true,
  54421. configurable: true
  54422. });
  54423. // =======================================================================
  54424. // Particle behavior logic
  54425. // these following methods may be overwritten by the user to fit his needs
  54426. /**
  54427. * This function does nothing. It may be overwritten to set all the particle first values.
  54428. * The SPS doesn't call this function, you may have to call it by your own.
  54429. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  54430. */
  54431. SolidParticleSystem.prototype.initParticles = function () {
  54432. };
  54433. /**
  54434. * This function does nothing. It may be overwritten to recycle a particle.
  54435. * The SPS doesn't call this function, you may have to call it by your own.
  54436. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  54437. * @param particle The particle to recycle
  54438. * @returns the recycled particle
  54439. */
  54440. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  54441. return particle;
  54442. };
  54443. /**
  54444. * Updates a particle : this function should be overwritten by the user.
  54445. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  54446. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  54447. * @example : just set a particle position or velocity and recycle conditions
  54448. * @param particle The particle to update
  54449. * @returns the updated particle
  54450. */
  54451. SolidParticleSystem.prototype.updateParticle = function (particle) {
  54452. return particle;
  54453. };
  54454. /**
  54455. * Updates a vertex of a particle : it can be overwritten by the user.
  54456. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  54457. * @param particle the current particle
  54458. * @param vertex the current index of the current particle
  54459. * @param pt the index of the current vertex in the particle shape
  54460. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  54461. * @example : just set a vertex particle position
  54462. * @returns the updated vertex
  54463. */
  54464. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  54465. return vertex;
  54466. };
  54467. /**
  54468. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  54469. * This does nothing and may be overwritten by the user.
  54470. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  54471. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  54472. * @param update the boolean update value actually passed to setParticles()
  54473. */
  54474. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  54475. };
  54476. /**
  54477. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  54478. * This will be passed three parameters.
  54479. * This does nothing and may be overwritten by the user.
  54480. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  54481. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  54482. * @param update the boolean update value actually passed to setParticles()
  54483. */
  54484. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  54485. };
  54486. return SolidParticleSystem;
  54487. }());
  54488. BABYLON.SolidParticleSystem = SolidParticleSystem;
  54489. })(BABYLON || (BABYLON = {}));
  54490. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  54491. var BABYLON;
  54492. (function (BABYLON) {
  54493. var ShaderMaterial = /** @class */ (function (_super) {
  54494. __extends(ShaderMaterial, _super);
  54495. function ShaderMaterial(name, scene, shaderPath, options) {
  54496. var _this = _super.call(this, name, scene) || this;
  54497. _this._textures = {};
  54498. _this._textureArrays = {};
  54499. _this._floats = {};
  54500. _this._ints = {};
  54501. _this._floatsArrays = {};
  54502. _this._colors3 = {};
  54503. _this._colors3Arrays = {};
  54504. _this._colors4 = {};
  54505. _this._vectors2 = {};
  54506. _this._vectors3 = {};
  54507. _this._vectors4 = {};
  54508. _this._matrices = {};
  54509. _this._matrices3x3 = {};
  54510. _this._matrices2x2 = {};
  54511. _this._vectors2Arrays = {};
  54512. _this._vectors3Arrays = {};
  54513. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  54514. _this._shaderPath = shaderPath;
  54515. options.needAlphaBlending = options.needAlphaBlending || false;
  54516. options.needAlphaTesting = options.needAlphaTesting || false;
  54517. options.attributes = options.attributes || ["position", "normal", "uv"];
  54518. options.uniforms = options.uniforms || ["worldViewProjection"];
  54519. options.uniformBuffers = options.uniformBuffers || [];
  54520. options.samplers = options.samplers || [];
  54521. options.defines = options.defines || [];
  54522. _this._options = options;
  54523. return _this;
  54524. }
  54525. ShaderMaterial.prototype.getClassName = function () {
  54526. return "ShaderMaterial";
  54527. };
  54528. ShaderMaterial.prototype.needAlphaBlending = function () {
  54529. return this._options.needAlphaBlending;
  54530. };
  54531. ShaderMaterial.prototype.needAlphaTesting = function () {
  54532. return this._options.needAlphaTesting;
  54533. };
  54534. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  54535. if (this._options.uniforms.indexOf(uniformName) === -1) {
  54536. this._options.uniforms.push(uniformName);
  54537. }
  54538. };
  54539. ShaderMaterial.prototype.setTexture = function (name, texture) {
  54540. if (this._options.samplers.indexOf(name) === -1) {
  54541. this._options.samplers.push(name);
  54542. }
  54543. this._textures[name] = texture;
  54544. return this;
  54545. };
  54546. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  54547. if (this._options.samplers.indexOf(name) === -1) {
  54548. this._options.samplers.push(name);
  54549. }
  54550. this._checkUniform(name);
  54551. this._textureArrays[name] = textures;
  54552. return this;
  54553. };
  54554. ShaderMaterial.prototype.setFloat = function (name, value) {
  54555. this._checkUniform(name);
  54556. this._floats[name] = value;
  54557. return this;
  54558. };
  54559. ShaderMaterial.prototype.setInt = function (name, value) {
  54560. this._checkUniform(name);
  54561. this._ints[name] = value;
  54562. return this;
  54563. };
  54564. ShaderMaterial.prototype.setFloats = function (name, value) {
  54565. this._checkUniform(name);
  54566. this._floatsArrays[name] = value;
  54567. return this;
  54568. };
  54569. ShaderMaterial.prototype.setColor3 = function (name, value) {
  54570. this._checkUniform(name);
  54571. this._colors3[name] = value;
  54572. return this;
  54573. };
  54574. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  54575. this._checkUniform(name);
  54576. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  54577. color.toArray(arr, arr.length);
  54578. return arr;
  54579. }, []);
  54580. return this;
  54581. };
  54582. ShaderMaterial.prototype.setColor4 = function (name, value) {
  54583. this._checkUniform(name);
  54584. this._colors4[name] = value;
  54585. return this;
  54586. };
  54587. ShaderMaterial.prototype.setVector2 = function (name, value) {
  54588. this._checkUniform(name);
  54589. this._vectors2[name] = value;
  54590. return this;
  54591. };
  54592. ShaderMaterial.prototype.setVector3 = function (name, value) {
  54593. this._checkUniform(name);
  54594. this._vectors3[name] = value;
  54595. return this;
  54596. };
  54597. ShaderMaterial.prototype.setVector4 = function (name, value) {
  54598. this._checkUniform(name);
  54599. this._vectors4[name] = value;
  54600. return this;
  54601. };
  54602. ShaderMaterial.prototype.setMatrix = function (name, value) {
  54603. this._checkUniform(name);
  54604. this._matrices[name] = value;
  54605. return this;
  54606. };
  54607. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  54608. this._checkUniform(name);
  54609. this._matrices3x3[name] = value;
  54610. return this;
  54611. };
  54612. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  54613. this._checkUniform(name);
  54614. this._matrices2x2[name] = value;
  54615. return this;
  54616. };
  54617. ShaderMaterial.prototype.setArray2 = function (name, value) {
  54618. this._checkUniform(name);
  54619. this._vectors2Arrays[name] = value;
  54620. return this;
  54621. };
  54622. ShaderMaterial.prototype.setArray3 = function (name, value) {
  54623. this._checkUniform(name);
  54624. this._vectors3Arrays[name] = value;
  54625. return this;
  54626. };
  54627. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  54628. if (!mesh) {
  54629. return true;
  54630. }
  54631. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  54632. return false;
  54633. }
  54634. return false;
  54635. };
  54636. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  54637. var scene = this.getScene();
  54638. var engine = scene.getEngine();
  54639. if (!this.checkReadyOnEveryCall) {
  54640. if (this._renderId === scene.getRenderId()) {
  54641. if (this._checkCache(scene, mesh, useInstances)) {
  54642. return true;
  54643. }
  54644. }
  54645. }
  54646. // Instances
  54647. var defines = [];
  54648. var attribs = [];
  54649. var fallbacks = new BABYLON.EffectFallbacks();
  54650. if (useInstances) {
  54651. defines.push("#define INSTANCES");
  54652. }
  54653. for (var index = 0; index < this._options.defines.length; index++) {
  54654. defines.push(this._options.defines[index]);
  54655. }
  54656. for (var index = 0; index < this._options.attributes.length; index++) {
  54657. attribs.push(this._options.attributes[index]);
  54658. }
  54659. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  54660. attribs.push(BABYLON.VertexBuffer.ColorKind);
  54661. defines.push("#define VERTEXCOLOR");
  54662. }
  54663. // Bones
  54664. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  54665. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  54666. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  54667. if (mesh.numBoneInfluencers > 4) {
  54668. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  54669. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  54670. }
  54671. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  54672. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  54673. fallbacks.addCPUSkinningFallback(0, mesh);
  54674. if (this._options.uniforms.indexOf("mBones") === -1) {
  54675. this._options.uniforms.push("mBones");
  54676. }
  54677. }
  54678. else {
  54679. defines.push("#define NUM_BONE_INFLUENCERS 0");
  54680. }
  54681. // Textures
  54682. for (var name in this._textures) {
  54683. if (!this._textures[name].isReady()) {
  54684. return false;
  54685. }
  54686. }
  54687. // Alpha test
  54688. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  54689. defines.push("#define ALPHATEST");
  54690. }
  54691. var previousEffect = this._effect;
  54692. var join = defines.join("\n");
  54693. this._effect = engine.createEffect(this._shaderPath, {
  54694. attributes: attribs,
  54695. uniformsNames: this._options.uniforms,
  54696. uniformBuffersNames: this._options.uniformBuffers,
  54697. samplers: this._options.samplers,
  54698. defines: join,
  54699. fallbacks: fallbacks,
  54700. onCompiled: this.onCompiled,
  54701. onError: this.onError
  54702. }, engine);
  54703. if (!this._effect.isReady()) {
  54704. return false;
  54705. }
  54706. if (previousEffect !== this._effect) {
  54707. scene.resetCachedMaterial();
  54708. }
  54709. this._renderId = scene.getRenderId();
  54710. return true;
  54711. };
  54712. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  54713. var scene = this.getScene();
  54714. if (!this._effect) {
  54715. return;
  54716. }
  54717. if (this._options.uniforms.indexOf("world") !== -1) {
  54718. this._effect.setMatrix("world", world);
  54719. }
  54720. if (this._options.uniforms.indexOf("worldView") !== -1) {
  54721. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  54722. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  54723. }
  54724. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  54725. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  54726. }
  54727. };
  54728. ShaderMaterial.prototype.bind = function (world, mesh) {
  54729. // Std values
  54730. this.bindOnlyWorldMatrix(world);
  54731. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  54732. if (this._options.uniforms.indexOf("view") !== -1) {
  54733. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  54734. }
  54735. if (this._options.uniforms.indexOf("projection") !== -1) {
  54736. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  54737. }
  54738. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  54739. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  54740. }
  54741. // Bones
  54742. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  54743. var name;
  54744. // Texture
  54745. for (name in this._textures) {
  54746. this._effect.setTexture(name, this._textures[name]);
  54747. }
  54748. // Texture arrays
  54749. for (name in this._textureArrays) {
  54750. this._effect.setTextureArray(name, this._textureArrays[name]);
  54751. }
  54752. // Int
  54753. for (name in this._ints) {
  54754. this._effect.setInt(name, this._ints[name]);
  54755. }
  54756. // Float
  54757. for (name in this._floats) {
  54758. this._effect.setFloat(name, this._floats[name]);
  54759. }
  54760. // Floats
  54761. for (name in this._floatsArrays) {
  54762. this._effect.setArray(name, this._floatsArrays[name]);
  54763. }
  54764. // Color3
  54765. for (name in this._colors3) {
  54766. this._effect.setColor3(name, this._colors3[name]);
  54767. }
  54768. for (name in this._colors3Arrays) {
  54769. this._effect.setArray3(name, this._colors3Arrays[name]);
  54770. }
  54771. // Color4
  54772. for (name in this._colors4) {
  54773. var color = this._colors4[name];
  54774. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  54775. }
  54776. // Vector2
  54777. for (name in this._vectors2) {
  54778. this._effect.setVector2(name, this._vectors2[name]);
  54779. }
  54780. // Vector3
  54781. for (name in this._vectors3) {
  54782. this._effect.setVector3(name, this._vectors3[name]);
  54783. }
  54784. // Vector4
  54785. for (name in this._vectors4) {
  54786. this._effect.setVector4(name, this._vectors4[name]);
  54787. }
  54788. // Matrix
  54789. for (name in this._matrices) {
  54790. this._effect.setMatrix(name, this._matrices[name]);
  54791. }
  54792. // Matrix 3x3
  54793. for (name in this._matrices3x3) {
  54794. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  54795. }
  54796. // Matrix 2x2
  54797. for (name in this._matrices2x2) {
  54798. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  54799. }
  54800. // Vector2Array
  54801. for (name in this._vectors2Arrays) {
  54802. this._effect.setArray2(name, this._vectors2Arrays[name]);
  54803. }
  54804. // Vector3Array
  54805. for (name in this._vectors3Arrays) {
  54806. this._effect.setArray3(name, this._vectors3Arrays[name]);
  54807. }
  54808. }
  54809. this._afterBind(mesh);
  54810. };
  54811. ShaderMaterial.prototype.getActiveTextures = function () {
  54812. var activeTextures = _super.prototype.getActiveTextures.call(this);
  54813. for (var name in this._textures) {
  54814. activeTextures.push(this._textures[name]);
  54815. }
  54816. for (var name in this._textureArrays) {
  54817. var array = this._textureArrays[name];
  54818. for (var index = 0; index < array.length; index++) {
  54819. activeTextures.push(array[index]);
  54820. }
  54821. }
  54822. return activeTextures;
  54823. };
  54824. ShaderMaterial.prototype.hasTexture = function (texture) {
  54825. if (_super.prototype.hasTexture.call(this, texture)) {
  54826. return true;
  54827. }
  54828. for (var name in this._textures) {
  54829. if (this._textures[name] === texture) {
  54830. return true;
  54831. }
  54832. }
  54833. for (var name in this._textureArrays) {
  54834. var array = this._textureArrays[name];
  54835. for (var index = 0; index < array.length; index++) {
  54836. if (array[index] === texture) {
  54837. return true;
  54838. }
  54839. }
  54840. }
  54841. return false;
  54842. };
  54843. ShaderMaterial.prototype.clone = function (name) {
  54844. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  54845. return newShaderMaterial;
  54846. };
  54847. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  54848. if (forceDisposeTextures) {
  54849. var name;
  54850. for (name in this._textures) {
  54851. this._textures[name].dispose();
  54852. }
  54853. for (name in this._textureArrays) {
  54854. var array = this._textureArrays[name];
  54855. for (var index = 0; index < array.length; index++) {
  54856. array[index].dispose();
  54857. }
  54858. }
  54859. }
  54860. this._textures = {};
  54861. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  54862. };
  54863. ShaderMaterial.prototype.serialize = function () {
  54864. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  54865. serializationObject.customType = "BABYLON.ShaderMaterial";
  54866. serializationObject.options = this._options;
  54867. serializationObject.shaderPath = this._shaderPath;
  54868. var name;
  54869. // Texture
  54870. serializationObject.textures = {};
  54871. for (name in this._textures) {
  54872. serializationObject.textures[name] = this._textures[name].serialize();
  54873. }
  54874. // Texture arrays
  54875. serializationObject.textureArrays = {};
  54876. for (name in this._textureArrays) {
  54877. serializationObject.textureArrays[name] = [];
  54878. var array = this._textureArrays[name];
  54879. for (var index = 0; index < array.length; index++) {
  54880. serializationObject.textureArrays[name].push(array[index].serialize());
  54881. }
  54882. }
  54883. // Float
  54884. serializationObject.floats = {};
  54885. for (name in this._floats) {
  54886. serializationObject.floats[name] = this._floats[name];
  54887. }
  54888. // Float s
  54889. serializationObject.FloatArrays = {};
  54890. for (name in this._floatsArrays) {
  54891. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  54892. }
  54893. // Color3
  54894. serializationObject.colors3 = {};
  54895. for (name in this._colors3) {
  54896. serializationObject.colors3[name] = this._colors3[name].asArray();
  54897. }
  54898. // Color3 array
  54899. serializationObject.colors3Arrays = {};
  54900. for (name in this._colors3Arrays) {
  54901. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  54902. }
  54903. // Color4
  54904. serializationObject.colors4 = {};
  54905. for (name in this._colors4) {
  54906. serializationObject.colors4[name] = this._colors4[name].asArray();
  54907. }
  54908. // Vector2
  54909. serializationObject.vectors2 = {};
  54910. for (name in this._vectors2) {
  54911. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  54912. }
  54913. // Vector3
  54914. serializationObject.vectors3 = {};
  54915. for (name in this._vectors3) {
  54916. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  54917. }
  54918. // Vector4
  54919. serializationObject.vectors4 = {};
  54920. for (name in this._vectors4) {
  54921. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  54922. }
  54923. // Matrix
  54924. serializationObject.matrices = {};
  54925. for (name in this._matrices) {
  54926. serializationObject.matrices[name] = this._matrices[name].asArray();
  54927. }
  54928. // Matrix 3x3
  54929. serializationObject.matrices3x3 = {};
  54930. for (name in this._matrices3x3) {
  54931. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  54932. }
  54933. // Matrix 2x2
  54934. serializationObject.matrices2x2 = {};
  54935. for (name in this._matrices2x2) {
  54936. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  54937. }
  54938. // Vector2Array
  54939. serializationObject.vectors2Arrays = {};
  54940. for (name in this._vectors2Arrays) {
  54941. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  54942. }
  54943. // Vector3Array
  54944. serializationObject.vectors3Arrays = {};
  54945. for (name in this._vectors3Arrays) {
  54946. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  54947. }
  54948. return serializationObject;
  54949. };
  54950. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  54951. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  54952. var name;
  54953. // Texture
  54954. for (name in source.textures) {
  54955. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  54956. }
  54957. // Texture arrays
  54958. for (name in source.textureArrays) {
  54959. var array = source.textureArrays[name];
  54960. var textureArray = new Array();
  54961. for (var index = 0; index < array.length; index++) {
  54962. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  54963. }
  54964. material.setTextureArray(name, textureArray);
  54965. }
  54966. // Float
  54967. for (name in source.floats) {
  54968. material.setFloat(name, source.floats[name]);
  54969. }
  54970. // Float s
  54971. for (name in source.floatsArrays) {
  54972. material.setFloats(name, source.floatsArrays[name]);
  54973. }
  54974. // Color3
  54975. for (name in source.colors3) {
  54976. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  54977. }
  54978. // Color3 arrays
  54979. for (name in source.colors3Arrays) {
  54980. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  54981. if (i % 3 === 0) {
  54982. arr.push([num]);
  54983. }
  54984. else {
  54985. arr[arr.length - 1].push(num);
  54986. }
  54987. return arr;
  54988. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  54989. material.setColor3Array(name, colors);
  54990. }
  54991. // Color4
  54992. for (name in source.colors4) {
  54993. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  54994. }
  54995. // Vector2
  54996. for (name in source.vectors2) {
  54997. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  54998. }
  54999. // Vector3
  55000. for (name in source.vectors3) {
  55001. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  55002. }
  55003. // Vector4
  55004. for (name in source.vectors4) {
  55005. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  55006. }
  55007. // Matrix
  55008. for (name in source.matrices) {
  55009. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  55010. }
  55011. // Matrix 3x3
  55012. for (name in source.matrices3x3) {
  55013. material.setMatrix3x3(name, source.matrices3x3[name]);
  55014. }
  55015. // Matrix 2x2
  55016. for (name in source.matrices2x2) {
  55017. material.setMatrix2x2(name, source.matrices2x2[name]);
  55018. }
  55019. // Vector2Array
  55020. for (name in source.vectors2Arrays) {
  55021. material.setArray2(name, source.vectors2Arrays[name]);
  55022. }
  55023. // Vector3Array
  55024. for (name in source.vectors3Arrays) {
  55025. material.setArray3(name, source.vectors3Arrays[name]);
  55026. }
  55027. return material;
  55028. };
  55029. return ShaderMaterial;
  55030. }(BABYLON.Material));
  55031. BABYLON.ShaderMaterial = ShaderMaterial;
  55032. })(BABYLON || (BABYLON = {}));
  55033. //# sourceMappingURL=babylon.shaderMaterial.js.map
  55034. var BABYLON;
  55035. (function (BABYLON) {
  55036. var GroundMesh = /** @class */ (function (_super) {
  55037. __extends(GroundMesh, _super);
  55038. function GroundMesh(name, scene) {
  55039. var _this = _super.call(this, name, scene) || this;
  55040. _this.generateOctree = false;
  55041. return _this;
  55042. }
  55043. GroundMesh.prototype.getClassName = function () {
  55044. return "GroundMesh";
  55045. };
  55046. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  55047. get: function () {
  55048. return Math.min(this._subdivisionsX, this._subdivisionsY);
  55049. },
  55050. enumerable: true,
  55051. configurable: true
  55052. });
  55053. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  55054. get: function () {
  55055. return this._subdivisionsX;
  55056. },
  55057. enumerable: true,
  55058. configurable: true
  55059. });
  55060. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  55061. get: function () {
  55062. return this._subdivisionsY;
  55063. },
  55064. enumerable: true,
  55065. configurable: true
  55066. });
  55067. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  55068. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  55069. this._subdivisionsX = chunksCount;
  55070. this._subdivisionsY = chunksCount;
  55071. this.subdivide(chunksCount);
  55072. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  55073. };
  55074. /**
  55075. * Returns a height (y) value in the Worl system :
  55076. * the ground altitude at the coordinates (x, z) expressed in the World system.
  55077. * Returns the ground y position if (x, z) are outside the ground surface.
  55078. */
  55079. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  55080. var world = this.getWorldMatrix();
  55081. var invMat = BABYLON.Tmp.Matrix[5];
  55082. world.invertToRef(invMat);
  55083. var tmpVect = BABYLON.Tmp.Vector3[8];
  55084. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  55085. x = tmpVect.x;
  55086. z = tmpVect.z;
  55087. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  55088. return this.position.y;
  55089. }
  55090. if (!this._heightQuads || this._heightQuads.length == 0) {
  55091. this._initHeightQuads();
  55092. this._computeHeightQuads();
  55093. }
  55094. var facet = this._getFacetAt(x, z);
  55095. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  55096. // return y in the World system
  55097. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  55098. return tmpVect.y;
  55099. };
  55100. /**
  55101. * Returns a normalized vector (Vector3) orthogonal to the ground
  55102. * at the ground coordinates (x, z) expressed in the World system.
  55103. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  55104. */
  55105. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  55106. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  55107. this.getNormalAtCoordinatesToRef(x, z, normal);
  55108. return normal;
  55109. };
  55110. /**
  55111. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  55112. * at the ground coordinates (x, z) expressed in the World system.
  55113. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  55114. * Returns the GroundMesh.
  55115. */
  55116. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  55117. var world = this.getWorldMatrix();
  55118. var tmpMat = BABYLON.Tmp.Matrix[5];
  55119. world.invertToRef(tmpMat);
  55120. var tmpVect = BABYLON.Tmp.Vector3[8];
  55121. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  55122. x = tmpVect.x;
  55123. z = tmpVect.z;
  55124. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  55125. return this;
  55126. }
  55127. if (!this._heightQuads || this._heightQuads.length == 0) {
  55128. this._initHeightQuads();
  55129. this._computeHeightQuads();
  55130. }
  55131. var facet = this._getFacetAt(x, z);
  55132. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  55133. return this;
  55134. };
  55135. /**
  55136. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  55137. * if the ground has been updated.
  55138. * This can be used in the render loop.
  55139. * Returns the GroundMesh.
  55140. */
  55141. GroundMesh.prototype.updateCoordinateHeights = function () {
  55142. if (!this._heightQuads || this._heightQuads.length == 0) {
  55143. this._initHeightQuads();
  55144. }
  55145. this._computeHeightQuads();
  55146. return this;
  55147. };
  55148. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  55149. GroundMesh.prototype._getFacetAt = function (x, z) {
  55150. // retrieve col and row from x, z coordinates in the ground local system
  55151. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  55152. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  55153. var quad = this._heightQuads[row * this._subdivisionsX + col];
  55154. var facet;
  55155. if (z < quad.slope.x * x + quad.slope.y) {
  55156. facet = quad.facet1;
  55157. }
  55158. else {
  55159. facet = quad.facet2;
  55160. }
  55161. return facet;
  55162. };
  55163. // Creates and populates the heightMap array with "facet" elements :
  55164. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  55165. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  55166. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  55167. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  55168. // Returns the GroundMesh.
  55169. GroundMesh.prototype._initHeightQuads = function () {
  55170. var subdivisionsX = this._subdivisionsX;
  55171. var subdivisionsY = this._subdivisionsY;
  55172. this._heightQuads = new Array();
  55173. for (var row = 0; row < subdivisionsY; row++) {
  55174. for (var col = 0; col < subdivisionsX; col++) {
  55175. var quad = { slope: BABYLON.Vector2.Zero(), facet1: new BABYLON.Vector4(0.0, 0.0, 0.0, 0.0), facet2: new BABYLON.Vector4(0.0, 0.0, 0.0, 0.0) };
  55176. this._heightQuads[row * subdivisionsX + col] = quad;
  55177. }
  55178. }
  55179. return this;
  55180. };
  55181. // Compute each quad element values and update the the heightMap array :
  55182. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  55183. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  55184. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  55185. // Returns the GroundMesh.
  55186. GroundMesh.prototype._computeHeightQuads = function () {
  55187. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  55188. if (!positions) {
  55189. return this;
  55190. }
  55191. var v1 = BABYLON.Tmp.Vector3[3];
  55192. var v2 = BABYLON.Tmp.Vector3[2];
  55193. var v3 = BABYLON.Tmp.Vector3[1];
  55194. var v4 = BABYLON.Tmp.Vector3[0];
  55195. var v1v2 = BABYLON.Tmp.Vector3[4];
  55196. var v1v3 = BABYLON.Tmp.Vector3[5];
  55197. var v1v4 = BABYLON.Tmp.Vector3[6];
  55198. var norm1 = BABYLON.Tmp.Vector3[7];
  55199. var norm2 = BABYLON.Tmp.Vector3[8];
  55200. var i = 0;
  55201. var j = 0;
  55202. var k = 0;
  55203. var cd = 0; // 2D slope coefficient : z = cd * x + h
  55204. var h = 0;
  55205. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  55206. var d2 = 0;
  55207. var subdivisionsX = this._subdivisionsX;
  55208. var subdivisionsY = this._subdivisionsY;
  55209. for (var row = 0; row < subdivisionsY; row++) {
  55210. for (var col = 0; col < subdivisionsX; col++) {
  55211. i = col * 3;
  55212. j = row * (subdivisionsX + 1) * 3;
  55213. k = (row + 1) * (subdivisionsX + 1) * 3;
  55214. v1.x = positions[j + i];
  55215. v1.y = positions[j + i + 1];
  55216. v1.z = positions[j + i + 2];
  55217. v2.x = positions[j + i + 3];
  55218. v2.y = positions[j + i + 4];
  55219. v2.z = positions[j + i + 5];
  55220. v3.x = positions[k + i];
  55221. v3.y = positions[k + i + 1];
  55222. v3.z = positions[k + i + 2];
  55223. v4.x = positions[k + i + 3];
  55224. v4.y = positions[k + i + 4];
  55225. v4.z = positions[k + i + 5];
  55226. // 2D slope V1V4
  55227. cd = (v4.z - v1.z) / (v4.x - v1.x);
  55228. h = v1.z - cd * v1.x; // v1 belongs to the slope
  55229. // facet equations :
  55230. // we compute each facet normal vector
  55231. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  55232. // we compute the value d by applying the equation to v1 which belongs to the plane
  55233. // then we store the facet equation in a Vector4
  55234. v2.subtractToRef(v1, v1v2);
  55235. v3.subtractToRef(v1, v1v3);
  55236. v4.subtractToRef(v1, v1v4);
  55237. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  55238. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  55239. norm1.normalize();
  55240. norm2.normalize();
  55241. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  55242. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  55243. var quad = this._heightQuads[row * subdivisionsX + col];
  55244. quad.slope.copyFromFloats(cd, h);
  55245. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  55246. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  55247. }
  55248. }
  55249. return this;
  55250. };
  55251. GroundMesh.prototype.serialize = function (serializationObject) {
  55252. _super.prototype.serialize.call(this, serializationObject);
  55253. serializationObject.subdivisionsX = this._subdivisionsX;
  55254. serializationObject.subdivisionsY = this._subdivisionsY;
  55255. serializationObject.minX = this._minX;
  55256. serializationObject.maxX = this._maxX;
  55257. serializationObject.minZ = this._minZ;
  55258. serializationObject.maxZ = this._maxZ;
  55259. serializationObject.width = this._width;
  55260. serializationObject.height = this._height;
  55261. };
  55262. GroundMesh.Parse = function (parsedMesh, scene) {
  55263. var result = new GroundMesh(parsedMesh.name, scene);
  55264. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  55265. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  55266. result._minX = parsedMesh.minX;
  55267. result._maxX = parsedMesh.maxX;
  55268. result._minZ = parsedMesh.minZ;
  55269. result._maxZ = parsedMesh.maxZ;
  55270. result._width = parsedMesh.width;
  55271. result._height = parsedMesh.height;
  55272. return result;
  55273. };
  55274. return GroundMesh;
  55275. }(BABYLON.Mesh));
  55276. BABYLON.GroundMesh = GroundMesh;
  55277. })(BABYLON || (BABYLON = {}));
  55278. //# sourceMappingURL=babylon.groundMesh.js.map
  55279. var BABYLON;
  55280. (function (BABYLON) {
  55281. /**
  55282. * Creates an instance based on a source mesh.
  55283. */
  55284. var InstancedMesh = /** @class */ (function (_super) {
  55285. __extends(InstancedMesh, _super);
  55286. function InstancedMesh(name, source) {
  55287. var _this = _super.call(this, name, source.getScene()) || this;
  55288. source.instances.push(_this);
  55289. _this._sourceMesh = source;
  55290. _this.position.copyFrom(source.position);
  55291. _this.rotation.copyFrom(source.rotation);
  55292. _this.scaling.copyFrom(source.scaling);
  55293. if (source.rotationQuaternion) {
  55294. _this.rotationQuaternion = source.rotationQuaternion.clone();
  55295. }
  55296. _this.infiniteDistance = source.infiniteDistance;
  55297. _this.setPivotMatrix(source.getPivotMatrix());
  55298. _this.refreshBoundingInfo();
  55299. _this._syncSubMeshes();
  55300. return _this;
  55301. }
  55302. /**
  55303. * Returns the string "InstancedMesh".
  55304. */
  55305. InstancedMesh.prototype.getClassName = function () {
  55306. return "InstancedMesh";
  55307. };
  55308. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  55309. // Methods
  55310. get: function () {
  55311. return this._sourceMesh.receiveShadows;
  55312. },
  55313. enumerable: true,
  55314. configurable: true
  55315. });
  55316. Object.defineProperty(InstancedMesh.prototype, "material", {
  55317. get: function () {
  55318. return this._sourceMesh.material;
  55319. },
  55320. enumerable: true,
  55321. configurable: true
  55322. });
  55323. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  55324. get: function () {
  55325. return this._sourceMesh.visibility;
  55326. },
  55327. enumerable: true,
  55328. configurable: true
  55329. });
  55330. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  55331. get: function () {
  55332. return this._sourceMesh.skeleton;
  55333. },
  55334. enumerable: true,
  55335. configurable: true
  55336. });
  55337. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  55338. get: function () {
  55339. return this._sourceMesh.renderingGroupId;
  55340. },
  55341. set: function (value) {
  55342. if (!this._sourceMesh || value === this._sourceMesh.renderingGroupId) {
  55343. return;
  55344. }
  55345. //no-op with warning
  55346. BABYLON.Tools.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene");
  55347. },
  55348. enumerable: true,
  55349. configurable: true
  55350. });
  55351. /**
  55352. * Returns the total number of vertices (integer).
  55353. */
  55354. InstancedMesh.prototype.getTotalVertices = function () {
  55355. return this._sourceMesh.getTotalVertices();
  55356. };
  55357. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  55358. get: function () {
  55359. return this._sourceMesh;
  55360. },
  55361. enumerable: true,
  55362. configurable: true
  55363. });
  55364. /**
  55365. * Is this node ready to be used/rendered
  55366. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  55367. * @return {boolean} is it ready
  55368. */
  55369. InstancedMesh.prototype.isReady = function (completeCheck) {
  55370. if (completeCheck === void 0) { completeCheck = false; }
  55371. return this._sourceMesh.isReady(completeCheck, true);
  55372. };
  55373. /**
  55374. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  55375. */
  55376. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  55377. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  55378. };
  55379. /**
  55380. * Sets the vertex data of the mesh geometry for the requested `kind`.
  55381. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  55382. * The `data` are either a numeric array either a Float32Array.
  55383. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  55384. * The parameter `stride` is an optional positive integer, it is usually automatically deducted from the `kind` (3 for positions or normals, 2 for UV, etc).
  55385. * Note that a new underlying VertexBuffer object is created each call.
  55386. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  55387. *
  55388. * Possible `kind` values :
  55389. * - BABYLON.VertexBuffer.PositionKind
  55390. * - BABYLON.VertexBuffer.UVKind
  55391. * - BABYLON.VertexBuffer.UV2Kind
  55392. * - BABYLON.VertexBuffer.UV3Kind
  55393. * - BABYLON.VertexBuffer.UV4Kind
  55394. * - BABYLON.VertexBuffer.UV5Kind
  55395. * - BABYLON.VertexBuffer.UV6Kind
  55396. * - BABYLON.VertexBuffer.ColorKind
  55397. * - BABYLON.VertexBuffer.MatricesIndicesKind
  55398. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  55399. * - BABYLON.VertexBuffer.MatricesWeightsKind
  55400. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  55401. *
  55402. * Returns the Mesh.
  55403. */
  55404. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  55405. if (this.sourceMesh) {
  55406. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  55407. }
  55408. return this.sourceMesh;
  55409. };
  55410. /**
  55411. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  55412. * If the mesh has no geometry, it is simply returned as it is.
  55413. * The `data` are either a numeric array either a Float32Array.
  55414. * No new underlying VertexBuffer object is created.
  55415. * If the `kind` is the `PositionKind` and if `updateExtends` is true, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  55416. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  55417. *
  55418. * Possible `kind` values :
  55419. * - BABYLON.VertexBuffer.PositionKind
  55420. * - BABYLON.VertexBuffer.UVKind
  55421. * - BABYLON.VertexBuffer.UV2Kind
  55422. * - BABYLON.VertexBuffer.UV3Kind
  55423. * - BABYLON.VertexBuffer.UV4Kind
  55424. * - BABYLON.VertexBuffer.UV5Kind
  55425. * - BABYLON.VertexBuffer.UV6Kind
  55426. * - BABYLON.VertexBuffer.ColorKind
  55427. * - BABYLON.VertexBuffer.MatricesIndicesKind
  55428. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  55429. * - BABYLON.VertexBuffer.MatricesWeightsKind
  55430. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  55431. *
  55432. * Returns the Mesh.
  55433. */
  55434. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  55435. if (this.sourceMesh) {
  55436. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  55437. }
  55438. return this.sourceMesh;
  55439. };
  55440. /**
  55441. * Sets the mesh indices.
  55442. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  55443. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  55444. * This method creates a new index buffer each call.
  55445. * Returns the Mesh.
  55446. */
  55447. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  55448. if (totalVertices === void 0) { totalVertices = null; }
  55449. if (this.sourceMesh) {
  55450. this.sourceMesh.setIndices(indices, totalVertices);
  55451. }
  55452. return this.sourceMesh;
  55453. };
  55454. /**
  55455. * Boolean : True if the mesh owns the requested kind of data.
  55456. */
  55457. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  55458. return this._sourceMesh.isVerticesDataPresent(kind);
  55459. };
  55460. /**
  55461. * Returns an array of indices (IndicesArray).
  55462. */
  55463. InstancedMesh.prototype.getIndices = function () {
  55464. return this._sourceMesh.getIndices();
  55465. };
  55466. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  55467. get: function () {
  55468. return this._sourceMesh._positions;
  55469. },
  55470. enumerable: true,
  55471. configurable: true
  55472. });
  55473. /**
  55474. * Sets a new updated BoundingInfo to the mesh.
  55475. * Returns the mesh.
  55476. */
  55477. InstancedMesh.prototype.refreshBoundingInfo = function () {
  55478. var meshBB = this._sourceMesh.getBoundingInfo();
  55479. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  55480. this._updateBoundingInfo();
  55481. return this;
  55482. };
  55483. InstancedMesh.prototype._preActivate = function () {
  55484. if (this._currentLOD) {
  55485. this._currentLOD._preActivate();
  55486. }
  55487. return this;
  55488. };
  55489. InstancedMesh.prototype._activate = function (renderId) {
  55490. if (this._currentLOD) {
  55491. this._currentLOD._registerInstanceForRenderId(this, renderId);
  55492. }
  55493. return this;
  55494. };
  55495. /**
  55496. * Returns the current associated LOD AbstractMesh.
  55497. */
  55498. InstancedMesh.prototype.getLOD = function (camera) {
  55499. if (!camera) {
  55500. return this;
  55501. }
  55502. var boundingInfo = this.getBoundingInfo();
  55503. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  55504. if (this._currentLOD === this.sourceMesh) {
  55505. return this;
  55506. }
  55507. return this._currentLOD;
  55508. };
  55509. InstancedMesh.prototype._syncSubMeshes = function () {
  55510. this.releaseSubMeshes();
  55511. if (this._sourceMesh.subMeshes) {
  55512. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  55513. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  55514. }
  55515. }
  55516. return this;
  55517. };
  55518. InstancedMesh.prototype._generatePointsArray = function () {
  55519. return this._sourceMesh._generatePointsArray();
  55520. };
  55521. /**
  55522. * Creates a new InstancedMesh from the current mesh.
  55523. * - name (string) : the cloned mesh name
  55524. * - newParent (optional Node) : the optional Node to parent the clone to.
  55525. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  55526. *
  55527. * Returns the clone.
  55528. */
  55529. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  55530. var result = this._sourceMesh.createInstance(name);
  55531. // Deep copy
  55532. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  55533. // Bounding info
  55534. this.refreshBoundingInfo();
  55535. // Parent
  55536. if (newParent) {
  55537. result.parent = newParent;
  55538. }
  55539. if (!doNotCloneChildren) {
  55540. // Children
  55541. for (var index = 0; index < this.getScene().meshes.length; index++) {
  55542. var mesh = this.getScene().meshes[index];
  55543. if (mesh.parent === this) {
  55544. mesh.clone(mesh.name, result);
  55545. }
  55546. }
  55547. }
  55548. result.computeWorldMatrix(true);
  55549. return result;
  55550. };
  55551. /**
  55552. * Disposes the InstancedMesh.
  55553. * Returns nothing.
  55554. */
  55555. InstancedMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  55556. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  55557. // Remove from mesh
  55558. var index = this._sourceMesh.instances.indexOf(this);
  55559. this._sourceMesh.instances.splice(index, 1);
  55560. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  55561. };
  55562. return InstancedMesh;
  55563. }(BABYLON.AbstractMesh));
  55564. BABYLON.InstancedMesh = InstancedMesh;
  55565. })(BABYLON || (BABYLON = {}));
  55566. //# sourceMappingURL=babylon.instancedMesh.js.map
  55567. var BABYLON;
  55568. (function (BABYLON) {
  55569. var LinesMesh = /** @class */ (function (_super) {
  55570. __extends(LinesMesh, _super);
  55571. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  55572. if (scene === void 0) { scene = null; }
  55573. if (parent === void 0) { parent = null; }
  55574. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  55575. _this.useVertexColor = useVertexColor;
  55576. _this.useVertexAlpha = useVertexAlpha;
  55577. _this.color = new BABYLON.Color3(1, 1, 1);
  55578. _this.alpha = 1;
  55579. if (source) {
  55580. _this.color = source.color.clone();
  55581. _this.alpha = source.alpha;
  55582. _this.useVertexColor = source.useVertexColor;
  55583. _this.useVertexAlpha = source.useVertexAlpha;
  55584. }
  55585. _this._intersectionThreshold = 0.1;
  55586. var defines = [];
  55587. var options = {
  55588. attributes: [BABYLON.VertexBuffer.PositionKind],
  55589. uniforms: ["world", "viewProjection"],
  55590. needAlphaBlending: true,
  55591. defines: defines
  55592. };
  55593. if (useVertexAlpha === false) {
  55594. options.needAlphaBlending = false;
  55595. }
  55596. if (!useVertexColor) {
  55597. options.uniforms.push("color");
  55598. }
  55599. else {
  55600. options.defines.push("#define VERTEXCOLOR");
  55601. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  55602. }
  55603. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  55604. return _this;
  55605. }
  55606. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  55607. /**
  55608. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  55609. * This margin is expressed in world space coordinates, so its value may vary.
  55610. * Default value is 0.1
  55611. * @returns the intersection Threshold value.
  55612. */
  55613. get: function () {
  55614. return this._intersectionThreshold;
  55615. },
  55616. /**
  55617. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  55618. * This margin is expressed in world space coordinates, so its value may vary.
  55619. * @param value the new threshold to apply
  55620. */
  55621. set: function (value) {
  55622. if (this._intersectionThreshold === value) {
  55623. return;
  55624. }
  55625. this._intersectionThreshold = value;
  55626. if (this.geometry) {
  55627. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  55628. }
  55629. },
  55630. enumerable: true,
  55631. configurable: true
  55632. });
  55633. /**
  55634. * Returns the string "LineMesh"
  55635. */
  55636. LinesMesh.prototype.getClassName = function () {
  55637. return "LinesMesh";
  55638. };
  55639. Object.defineProperty(LinesMesh.prototype, "material", {
  55640. get: function () {
  55641. return this._colorShader;
  55642. },
  55643. set: function (value) {
  55644. // Do nothing
  55645. },
  55646. enumerable: true,
  55647. configurable: true
  55648. });
  55649. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  55650. get: function () {
  55651. return false;
  55652. },
  55653. enumerable: true,
  55654. configurable: true
  55655. });
  55656. LinesMesh.prototype.createInstance = function (name) {
  55657. throw new Error("LinesMeshes do not support createInstance.");
  55658. };
  55659. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  55660. if (!this._geometry) {
  55661. return this;
  55662. }
  55663. // VBOs
  55664. this._geometry._bind(this._colorShader.getEffect());
  55665. // Color
  55666. if (!this.useVertexColor) {
  55667. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  55668. }
  55669. return this;
  55670. };
  55671. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  55672. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  55673. return this;
  55674. }
  55675. var engine = this.getScene().getEngine();
  55676. // Draw order
  55677. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  55678. return this;
  55679. };
  55680. LinesMesh.prototype.dispose = function (doNotRecurse) {
  55681. this._colorShader.dispose();
  55682. _super.prototype.dispose.call(this, doNotRecurse);
  55683. };
  55684. /**
  55685. * Returns a new LineMesh object cloned from the current one.
  55686. */
  55687. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  55688. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  55689. };
  55690. return LinesMesh;
  55691. }(BABYLON.Mesh));
  55692. BABYLON.LinesMesh = LinesMesh;
  55693. })(BABYLON || (BABYLON = {}));
  55694. //# sourceMappingURL=babylon.linesMesh.js.map
  55695. var BABYLON;
  55696. (function (BABYLON) {
  55697. var MeshBuilder = /** @class */ (function () {
  55698. function MeshBuilder() {
  55699. }
  55700. MeshBuilder.updateSideOrientation = function (orientation) {
  55701. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  55702. return BABYLON.Mesh.DOUBLESIDE;
  55703. }
  55704. if (orientation === undefined || orientation === null) {
  55705. return BABYLON.Mesh.FRONTSIDE;
  55706. }
  55707. return orientation;
  55708. };
  55709. /**
  55710. * Creates a box mesh.
  55711. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  55712. * The parameter `size` sets the size (float) of each box side (default 1).
  55713. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  55714. * You can set different colors and different images to each box side by using the parameters `faceColors` (an array of 6 Color3 elements) and `faceUV` (an array of 6 Vector4 elements).
  55715. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  55716. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55717. * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4).
  55718. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55719. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55720. */
  55721. MeshBuilder.CreateBox = function (name, options, scene) {
  55722. if (scene === void 0) { scene = null; }
  55723. var box = new BABYLON.Mesh(name, scene);
  55724. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55725. box._originalBuilderSideOrientation = options.sideOrientation;
  55726. var vertexData = BABYLON.VertexData.CreateBox(options);
  55727. vertexData.applyToMesh(box, options.updatable);
  55728. return box;
  55729. };
  55730. /**
  55731. * Creates a sphere mesh.
  55732. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  55733. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  55734. * You can set some different sphere dimensions, for instance to build an ellipsoid, by using the parameters `diameterX`, `diameterY` and `diameterZ` (all by default have the same value than `diameter`).
  55735. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  55736. * You can create an unclosed sphere with the parameter `arc` (positive float, default 1), valued between 0 and 1, what is the ratio of the circumference (latitude) : 2 x PI x ratio
  55737. * You can create an unclosed sphere on its height with the parameter `slice` (positive float, default1), valued between 0 and 1, what is the height ratio (longitude).
  55738. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55739. * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4).
  55740. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55741. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55742. */
  55743. MeshBuilder.CreateSphere = function (name, options, scene) {
  55744. var sphere = new BABYLON.Mesh(name, scene);
  55745. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55746. sphere._originalBuilderSideOrientation = options.sideOrientation;
  55747. var vertexData = BABYLON.VertexData.CreateSphere(options);
  55748. vertexData.applyToMesh(sphere, options.updatable);
  55749. return sphere;
  55750. };
  55751. /**
  55752. * Creates a plane polygonal mesh. By default, this is a disc.
  55753. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  55754. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  55755. * The parameter `tessellation` sets the number of polygon sides (positive integer, default 64). So a tessellation valued to 3 will build a triangle, to 4 a square, etc.
  55756. * You can create an unclosed polygon with the parameter `arc` (positive float, default 1), valued between 0 and 1, what is the ratio of the circumference : 2 x PI x ratio
  55757. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55758. * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4).
  55759. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55760. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55761. */
  55762. MeshBuilder.CreateDisc = function (name, options, scene) {
  55763. if (scene === void 0) { scene = null; }
  55764. var disc = new BABYLON.Mesh(name, scene);
  55765. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55766. disc._originalBuilderSideOrientation = options.sideOrientation;
  55767. var vertexData = BABYLON.VertexData.CreateDisc(options);
  55768. vertexData.applyToMesh(disc, options.updatable);
  55769. return disc;
  55770. };
  55771. /**
  55772. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  55773. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  55774. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  55775. * You can set some different icosphere dimensions, for instance to build an ellipsoid, by using the parameters `radiusX`, `radiusY` and `radiusZ` (all by default have the same value than `radius`).
  55776. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  55777. * The parameter `flat` (boolean, default true) gives each side its own normals. Set it to false to get a smooth continuous light reflection on the surface.
  55778. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55779. * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4).
  55780. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55781. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55782. */
  55783. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  55784. var sphere = new BABYLON.Mesh(name, scene);
  55785. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55786. sphere._originalBuilderSideOrientation = options.sideOrientation;
  55787. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  55788. vertexData.applyToMesh(sphere, options.updatable);
  55789. return sphere;
  55790. };
  55791. ;
  55792. /**
  55793. * Creates a ribbon mesh.
  55794. * The ribbon is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  55795. *
  55796. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  55797. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  55798. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  55799. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  55800. * The parameter `offset` (positive integer, default : rounded half size of the pathArray length), is taken in account only if the `pathArray` is containing a single path.
  55801. * It's the offset to join the points from the same path. Ex : offset = 10 means the point 1 is joined to the point 11.
  55802. * The optional parameter `instance` is an instance of an existing Ribbon object to be updated with the passed `pathArray` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#ribbon
  55803. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55804. * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4).
  55805. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55806. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  55807. * The parameter `uvs` is an optional flat array of `Vector2` to update/set each ribbon vertex with its own custom UV values instead of the computed ones.
  55808. * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values.
  55809. * Note that if you use the parameters `uvs` or `colors`, the passed arrays must be populated with the right number of elements, it is to say the number of ribbon vertices. Remember that
  55810. * if you set `closePath` to `true`, there's one extra vertex per path in the geometry.
  55811. * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time.
  55812. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55813. */
  55814. MeshBuilder.CreateRibbon = function (name, options, scene) {
  55815. if (scene === void 0) { scene = null; }
  55816. var pathArray = options.pathArray;
  55817. var closeArray = options.closeArray;
  55818. var closePath = options.closePath;
  55819. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55820. var instance = options.instance;
  55821. var updatable = options.updatable;
  55822. if (instance) {
  55823. // positionFunction : ribbon case
  55824. // only pathArray and sideOrientation parameters are taken into account for positions update
  55825. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  55826. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  55827. var positionFunction = function (positions) {
  55828. var minlg = pathArray[0].length;
  55829. var i = 0;
  55830. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  55831. for (var si = 1; si <= ns; si++) {
  55832. for (var p = 0; p < pathArray.length; p++) {
  55833. var path = pathArray[p];
  55834. var l = path.length;
  55835. minlg = (minlg < l) ? minlg : l;
  55836. var j = 0;
  55837. while (j < minlg) {
  55838. positions[i] = path[j].x;
  55839. positions[i + 1] = path[j].y;
  55840. positions[i + 2] = path[j].z;
  55841. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  55842. BABYLON.Tmp.Vector3[0].x = path[j].x;
  55843. }
  55844. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  55845. BABYLON.Tmp.Vector3[1].x = path[j].x;
  55846. }
  55847. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  55848. BABYLON.Tmp.Vector3[0].y = path[j].y;
  55849. }
  55850. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  55851. BABYLON.Tmp.Vector3[1].y = path[j].y;
  55852. }
  55853. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  55854. BABYLON.Tmp.Vector3[0].z = path[j].z;
  55855. }
  55856. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  55857. BABYLON.Tmp.Vector3[1].z = path[j].z;
  55858. }
  55859. j++;
  55860. i += 3;
  55861. }
  55862. if (instance._closePath) {
  55863. positions[i] = path[0].x;
  55864. positions[i + 1] = path[0].y;
  55865. positions[i + 2] = path[0].z;
  55866. i += 3;
  55867. }
  55868. }
  55869. }
  55870. };
  55871. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  55872. positionFunction(positions);
  55873. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  55874. instance._boundingInfo.update(instance._worldMatrix);
  55875. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  55876. if (options.colors) {
  55877. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  55878. for (var c = 0; c < options.colors.length; c++) {
  55879. colors[c * 4] = options.colors[c].r;
  55880. colors[c * 4 + 1] = options.colors[c].g;
  55881. colors[c * 4 + 2] = options.colors[c].b;
  55882. colors[c * 4 + 3] = options.colors[c].a;
  55883. }
  55884. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  55885. }
  55886. if (options.uvs) {
  55887. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  55888. for (var i = 0; i < options.uvs.length; i++) {
  55889. uvs[i * 2] = options.uvs[i].x;
  55890. uvs[i * 2 + 1] = options.uvs[i].y;
  55891. }
  55892. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  55893. }
  55894. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  55895. var indices = instance.getIndices();
  55896. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  55897. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  55898. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  55899. if (instance._closePath) {
  55900. var indexFirst = 0;
  55901. var indexLast = 0;
  55902. for (var p = 0; p < pathArray.length; p++) {
  55903. indexFirst = instance._idx[p] * 3;
  55904. if (p + 1 < pathArray.length) {
  55905. indexLast = (instance._idx[p + 1] - 1) * 3;
  55906. }
  55907. else {
  55908. indexLast = normals.length - 3;
  55909. }
  55910. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  55911. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  55912. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  55913. normals[indexLast] = normals[indexFirst];
  55914. normals[indexLast + 1] = normals[indexFirst + 1];
  55915. normals[indexLast + 2] = normals[indexFirst + 2];
  55916. }
  55917. }
  55918. if (!(instance.areNormalsFrozen)) {
  55919. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  55920. }
  55921. }
  55922. return instance;
  55923. }
  55924. else {
  55925. var ribbon = new BABYLON.Mesh(name, scene);
  55926. ribbon._originalBuilderSideOrientation = sideOrientation;
  55927. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  55928. if (closePath) {
  55929. ribbon._idx = vertexData._idx;
  55930. }
  55931. ribbon._closePath = closePath;
  55932. ribbon._closeArray = closeArray;
  55933. vertexData.applyToMesh(ribbon, updatable);
  55934. return ribbon;
  55935. }
  55936. };
  55937. /**
  55938. * Creates a cylinder or a cone mesh.
  55939. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  55940. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  55941. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  55942. * The parameters `diameterTop` and `diameterBottom` overwrite the parameter `diameter` and set respectively the top cap and bottom cap diameter (floats, default 1). The parameter "diameterBottom" can't be zero.
  55943. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  55944. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  55945. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  55946. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  55947. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  55948. * You can set different colors and different images to each box side by using the parameters `faceColors` (an array of n Color3 elements) and `faceUV` (an array of n Vector4 elements).
  55949. * The value of n is the number of cylinder faces. If the cylinder has only 1 subdivisions, n equals : top face + cylinder surface + bottom face = 3
  55950. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  55951. * Finally, if the cylinder has 5 independent subdivisions and is enclose, n equals : top face + 5 x (stripe surface + 2 closing faces) + bottom face = 2 + 5 * 3 = 17
  55952. * Each array (color or UVs) is always ordered the same way : the first element is the bottom cap, the last element is the top cap. The other elements are each a ring surface.
  55953. * If `enclose` is false, a ring surface is one element.
  55954. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  55955. * Example how to set colors and textures on a sliced cylinder : http://www.html5gamedevs.com/topic/17945-creating-a-closed-slice-of-a-cylinder/#comment-106379
  55956. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55957. * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4).
  55958. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55959. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55960. */
  55961. MeshBuilder.CreateCylinder = function (name, options, scene) {
  55962. var cylinder = new BABYLON.Mesh(name, scene);
  55963. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55964. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  55965. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  55966. vertexData.applyToMesh(cylinder, options.updatable);
  55967. return cylinder;
  55968. };
  55969. /**
  55970. * Creates a torus mesh.
  55971. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  55972. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  55973. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  55974. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  55975. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55976. * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4).
  55977. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55978. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55979. */
  55980. MeshBuilder.CreateTorus = function (name, options, scene) {
  55981. var torus = new BABYLON.Mesh(name, scene);
  55982. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55983. torus._originalBuilderSideOrientation = options.sideOrientation;
  55984. var vertexData = BABYLON.VertexData.CreateTorus(options);
  55985. vertexData.applyToMesh(torus, options.updatable);
  55986. return torus;
  55987. };
  55988. /**
  55989. * Creates a torus knot mesh.
  55990. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  55991. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  55992. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  55993. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  55994. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  55995. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55996. * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4).
  55997. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55998. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55999. */
  56000. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  56001. var torusKnot = new BABYLON.Mesh(name, scene);
  56002. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56003. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  56004. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  56005. vertexData.applyToMesh(torusKnot, options.updatable);
  56006. return torusKnot;
  56007. };
  56008. /**
  56009. * Creates a line system mesh.
  56010. * A line system is a pool of many lines gathered in a single mesh.
  56011. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  56012. * A line system mesh is considered as a parametric shape since it has no predefined original shape. Its shape is determined by the passed array of lines as an input parameter.
  56013. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  56014. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  56015. * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter. The way to update it is the same than for
  56016. * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point.
  56017. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need the alpha blending (faster).
  56018. * updating a simple Line mesh, you just need to update every line in the `lines` array : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#lines-and-dashedlines
  56019. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  56020. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56021. */
  56022. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  56023. var instance = options.instance;
  56024. var lines = options.lines;
  56025. var colors = options.colors;
  56026. if (instance) {
  56027. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  56028. var vertexColor;
  56029. var lineColors;
  56030. if (colors) {
  56031. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  56032. }
  56033. var i = 0;
  56034. var c = 0;
  56035. for (var l = 0; l < lines.length; l++) {
  56036. var points = lines[l];
  56037. for (var p = 0; p < points.length; p++) {
  56038. positions[i] = points[p].x;
  56039. positions[i + 1] = points[p].y;
  56040. positions[i + 2] = points[p].z;
  56041. if (colors && vertexColor) {
  56042. lineColors = colors[l];
  56043. vertexColor[c] = lineColors[p].r;
  56044. vertexColor[c + 1] = lineColors[p].g;
  56045. vertexColor[c + 2] = lineColors[p].b;
  56046. vertexColor[c + 3] = lineColors[p].a;
  56047. c += 4;
  56048. }
  56049. i += 3;
  56050. }
  56051. }
  56052. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  56053. if (colors && vertexColor) {
  56054. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  56055. }
  56056. return instance;
  56057. }
  56058. // line system creation
  56059. var useVertexColor = (colors) ? true : false;
  56060. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  56061. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  56062. vertexData.applyToMesh(lineSystem, options.updatable);
  56063. return lineSystem;
  56064. };
  56065. /**
  56066. * Creates a line mesh.
  56067. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  56068. * A line mesh is considered as a parametric shape since it has no predefined original shape. Its shape is determined by the passed array of points as an input parameter.
  56069. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  56070. * The parameter `points` is an array successive Vector3.
  56071. * The optional parameter `instance` is an instance of an existing LineMesh object to be updated with the passed `points` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#lines-and-dashedlines
  56072. * The optional parameter `colors` is an array of successive Color4, one per line point.
  56073. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need alpha blending (faster).
  56074. * When updating an instance, remember that only point positions can change, not the number of points.
  56075. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56076. */
  56077. MeshBuilder.CreateLines = function (name, options, scene) {
  56078. if (scene === void 0) { scene = null; }
  56079. var colors = (options.colors) ? [options.colors] : null;
  56080. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  56081. return lines;
  56082. };
  56083. /**
  56084. * Creates a dashed line mesh.
  56085. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  56086. * A dashed line mesh is considered as a parametric shape since it has no predefined original shape. Its shape is determined by the passed array of points as an input parameter.
  56087. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  56088. * The parameter `points` is an array successive Vector3.
  56089. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  56090. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  56091. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  56092. * The optional parameter `instance` is an instance of an existing LineMesh object to be updated with the passed `points` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#lines-and-dashedlines
  56093. * When updating an instance, remember that only point positions can change, not the number of points.
  56094. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56095. */
  56096. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  56097. if (scene === void 0) { scene = null; }
  56098. var points = options.points;
  56099. var instance = options.instance;
  56100. var gapSize = options.gapSize || 1;
  56101. var dashSize = options.dashSize || 3;
  56102. if (instance) {
  56103. var positionFunction = function (positions) {
  56104. var curvect = BABYLON.Vector3.Zero();
  56105. var nbSeg = positions.length / 6;
  56106. var lg = 0;
  56107. var nb = 0;
  56108. var shft = 0;
  56109. var dashshft = 0;
  56110. var curshft = 0;
  56111. var p = 0;
  56112. var i = 0;
  56113. var j = 0;
  56114. for (i = 0; i < points.length - 1; i++) {
  56115. points[i + 1].subtractToRef(points[i], curvect);
  56116. lg += curvect.length();
  56117. }
  56118. shft = lg / nbSeg;
  56119. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  56120. for (i = 0; i < points.length - 1; i++) {
  56121. points[i + 1].subtractToRef(points[i], curvect);
  56122. nb = Math.floor(curvect.length() / shft);
  56123. curvect.normalize();
  56124. j = 0;
  56125. while (j < nb && p < positions.length) {
  56126. curshft = shft * j;
  56127. positions[p] = points[i].x + curshft * curvect.x;
  56128. positions[p + 1] = points[i].y + curshft * curvect.y;
  56129. positions[p + 2] = points[i].z + curshft * curvect.z;
  56130. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  56131. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  56132. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  56133. p += 6;
  56134. j++;
  56135. }
  56136. }
  56137. while (p < positions.length) {
  56138. positions[p] = points[i].x;
  56139. positions[p + 1] = points[i].y;
  56140. positions[p + 2] = points[i].z;
  56141. p += 3;
  56142. }
  56143. };
  56144. instance.updateMeshPositions(positionFunction, false);
  56145. return instance;
  56146. }
  56147. // dashed lines creation
  56148. var dashedLines = new BABYLON.LinesMesh(name, scene);
  56149. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  56150. vertexData.applyToMesh(dashedLines, options.updatable);
  56151. dashedLines.dashSize = dashSize;
  56152. dashedLines.gapSize = gapSize;
  56153. return dashedLines;
  56154. };
  56155. /**
  56156. * Creates an extruded shape mesh.
  56157. * The extrusion is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  56158. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  56159. *
  56160. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  56161. * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be extruded in its local space : the shape must be designed in the xOy plane and will be
  56162. * extruded along the Z axis.
  56163. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  56164. * The parameter `rotation` (float, default 0 radians) is the angle value to rotate the shape each step (each path point), from the former step (so rotation added each step) along the curve.
  56165. * The parameter `scale` (float, default 1) is the value to scale the shape.
  56166. * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL
  56167. * The optional parameter `instance` is an instance of an existing ExtrudedShape object to be updated with the passed `shape`, `path`, `scale` or `rotation` parameters : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#extruded-shape
  56168. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  56169. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56170. * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4).
  56171. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56172. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  56173. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56174. */
  56175. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  56176. if (scene === void 0) { scene = null; }
  56177. var path = options.path;
  56178. var shape = options.shape;
  56179. var scale = options.scale || 1;
  56180. var rotation = options.rotation || 0;
  56181. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  56182. var updatable = options.updatable;
  56183. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56184. var instance = options.instance || null;
  56185. var invertUV = options.invertUV || false;
  56186. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable ? true : false, sideOrientation, instance, invertUV, options.frontUVs || null, options.backUVs || null);
  56187. };
  56188. /**
  56189. * Creates an custom extruded shape mesh.
  56190. * The custom extrusion is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  56191. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  56192. *
  56193. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  56194. * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be extruded in its local space : the shape must be designed in the xOy plane and will be
  56195. * extruded along the Z axis.
  56196. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  56197. * The parameter `rotationFunction` (JS function) is a custom Javascript function called on each path point. This function is passed the position i of the point in the path
  56198. * and the distance of this point from the begining of the path :
  56199. * ```javascript
  56200. * var rotationFunction = function(i, distance) {
  56201. * // do things
  56202. * return rotationValue; }
  56203. * ```
  56204. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  56205. * The parameter `scaleFunction` (JS function) is a custom Javascript function called on each path point. This function is passed the position i of the point in the path
  56206. * and the distance of this point from the begining of the path :
  56207. * ```javascript
  56208. * var scaleFunction = function(i, distance) {
  56209. * // do things
  56210. * return scaleValue;}
  56211. * ```
  56212. * It must returns a float value that will be the scale value applied to the shape on each path point.
  56213. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  56214. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  56215. * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL
  56216. * The optional parameter `instance` is an instance of an existing ExtrudedShape object to be updated with the passed `shape`, `path`, `scale` or `rotation` parameters : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#extruded-shape
  56217. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  56218. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56219. * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4).
  56220. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56221. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  56222. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56223. */
  56224. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  56225. var path = options.path;
  56226. var shape = options.shape;
  56227. var scaleFunction = options.scaleFunction || (function () { return 1; });
  56228. var rotationFunction = options.rotationFunction || (function () { return 0; });
  56229. var ribbonCloseArray = options.ribbonCloseArray || false;
  56230. var ribbonClosePath = options.ribbonClosePath || false;
  56231. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  56232. var updatable = options.updatable;
  56233. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56234. var instance = options.instance;
  56235. var invertUV = options.invertUV || false;
  56236. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable ? true : false, sideOrientation, instance || null, invertUV, options.frontUVs || null, options.backUVs || null);
  56237. };
  56238. /**
  56239. * Creates lathe mesh.
  56240. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  56241. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  56242. *
  56243. * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be rotated in its local space : the shape must be designed in the xOy plane and will be
  56244. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  56245. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  56246. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  56247. * The parameter `arc` (positive float, default 1) is the ratio of the lathe. 0.5 builds for instance half a lathe, so an opened shape.
  56248. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  56249. * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL
  56250. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56251. * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4).
  56252. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56253. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  56254. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56255. */
  56256. MeshBuilder.CreateLathe = function (name, options, scene) {
  56257. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  56258. var closed = (options.closed === undefined) ? true : options.closed;
  56259. var shape = options.shape;
  56260. var radius = options.radius || 1;
  56261. var tessellation = options.tessellation || 64;
  56262. var updatable = options.updatable;
  56263. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56264. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  56265. var pi2 = Math.PI * 2;
  56266. var paths = new Array();
  56267. var invertUV = options.invertUV || false;
  56268. var i = 0;
  56269. var p = 0;
  56270. var step = pi2 / tessellation * arc;
  56271. var rotated;
  56272. var path = new Array();
  56273. ;
  56274. for (i = 0; i <= tessellation; i++) {
  56275. var path = [];
  56276. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  56277. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  56278. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  56279. }
  56280. for (p = 0; p < shape.length; p++) {
  56281. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  56282. path.push(rotated);
  56283. }
  56284. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  56285. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[shape.length - 1].x * radius, shape[shape.length - 1].y, Math.sin(i * step) * shape[shape.length - 1].x * radius));
  56286. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  56287. }
  56288. paths.push(path);
  56289. }
  56290. // lathe ribbon
  56291. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  56292. return lathe;
  56293. };
  56294. /**
  56295. * Creates a plane mesh.
  56296. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  56297. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  56298. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  56299. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  56300. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56301. * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4).
  56302. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56303. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56304. */
  56305. MeshBuilder.CreatePlane = function (name, options, scene) {
  56306. var plane = new BABYLON.Mesh(name, scene);
  56307. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56308. plane._originalBuilderSideOrientation = options.sideOrientation;
  56309. var vertexData = BABYLON.VertexData.CreatePlane(options);
  56310. vertexData.applyToMesh(plane, options.updatable);
  56311. if (options.sourcePlane) {
  56312. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  56313. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  56314. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  56315. plane.rotate(vectorProduct, product);
  56316. }
  56317. return plane;
  56318. };
  56319. /**
  56320. * Creates a ground mesh.
  56321. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  56322. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  56323. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  56324. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56325. */
  56326. MeshBuilder.CreateGround = function (name, options, scene) {
  56327. var ground = new BABYLON.GroundMesh(name, scene);
  56328. ground._setReady(false);
  56329. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  56330. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  56331. ground._width = options.width || 1;
  56332. ground._height = options.height || 1;
  56333. ground._maxX = ground._width / 2;
  56334. ground._maxZ = ground._height / 2;
  56335. ground._minX = -ground._maxX;
  56336. ground._minZ = -ground._maxZ;
  56337. var vertexData = BABYLON.VertexData.CreateGround(options);
  56338. vertexData.applyToMesh(ground, options.updatable);
  56339. ground._setReady(true);
  56340. return ground;
  56341. };
  56342. /**
  56343. * Creates a tiled ground mesh.
  56344. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  56345. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  56346. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  56347. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  56348. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  56349. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  56350. * numbers of subdivisions on the ground width and height of each tile.
  56351. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56352. */
  56353. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  56354. var tiledGround = new BABYLON.Mesh(name, scene);
  56355. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  56356. vertexData.applyToMesh(tiledGround, options.updatable);
  56357. return tiledGround;
  56358. };
  56359. /**
  56360. * Creates a ground mesh from a height map.
  56361. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  56362. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  56363. * The parameter `url` sets the URL of the height map image resource.
  56364. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  56365. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  56366. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  56367. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  56368. * The parameter `colorFilter` (optional Color3, default (0.3, 0.59, 0.11) ) is the filter to apply to the image pixel colors to compute the height.
  56369. * The parameter `onReady` is a javascript callback function that will be called once the mesh is just built (the height map download can last some time).
  56370. * This function is passed the newly built mesh :
  56371. * ```javascript
  56372. * function(mesh) { // do things
  56373. * return; }
  56374. * ```
  56375. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56376. */
  56377. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  56378. var width = options.width || 10.0;
  56379. var height = options.height || 10.0;
  56380. var subdivisions = options.subdivisions || 1 | 0;
  56381. var minHeight = options.minHeight || 0.0;
  56382. var maxHeight = options.maxHeight || 1.0;
  56383. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  56384. var updatable = options.updatable;
  56385. var onReady = options.onReady;
  56386. var ground = new BABYLON.GroundMesh(name, scene);
  56387. ground._subdivisionsX = subdivisions;
  56388. ground._subdivisionsY = subdivisions;
  56389. ground._width = width;
  56390. ground._height = height;
  56391. ground._maxX = ground._width / 2.0;
  56392. ground._maxZ = ground._height / 2.0;
  56393. ground._minX = -ground._maxX;
  56394. ground._minZ = -ground._maxZ;
  56395. ground._setReady(false);
  56396. var onload = function (img) {
  56397. // Getting height map data
  56398. var canvas = document.createElement("canvas");
  56399. var context = canvas.getContext("2d");
  56400. if (!context) {
  56401. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  56402. }
  56403. if (scene.isDisposed) {
  56404. return;
  56405. }
  56406. var bufferWidth = img.width;
  56407. var bufferHeight = img.height;
  56408. canvas.width = bufferWidth;
  56409. canvas.height = bufferHeight;
  56410. context.drawImage(img, 0, 0);
  56411. // Create VertexData from map data
  56412. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  56413. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  56414. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  56415. width: width, height: height,
  56416. subdivisions: subdivisions,
  56417. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  56418. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  56419. });
  56420. vertexData.applyToMesh(ground, updatable);
  56421. ground._setReady(true);
  56422. //execute ready callback, if set
  56423. if (onReady) {
  56424. onReady(ground);
  56425. }
  56426. };
  56427. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  56428. return ground;
  56429. };
  56430. /**
  56431. * Creates a polygon mesh.
  56432. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  56433. * The parameter `shape` is a required array of successive Vector3 representing the corners of the polygon in th XoZ plane, that is y = 0 for all vectors.
  56434. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56435. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56436. * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4).
  56437. * Remember you can only change the shape positions, not their number when updating a polygon.
  56438. */
  56439. MeshBuilder.CreatePolygon = function (name, options, scene) {
  56440. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56441. var shape = options.shape;
  56442. var holes = options.holes || [];
  56443. var depth = options.depth || 0;
  56444. var contours = [];
  56445. var hole = [];
  56446. for (var i = 0; i < shape.length; i++) {
  56447. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  56448. }
  56449. var epsilon = 0.00000001;
  56450. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  56451. contours.pop();
  56452. }
  56453. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  56454. for (var hNb = 0; hNb < holes.length; hNb++) {
  56455. hole = [];
  56456. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  56457. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  56458. }
  56459. polygonTriangulation.addHole(hole);
  56460. }
  56461. var polygon = polygonTriangulation.build(options.updatable, depth);
  56462. polygon._originalBuilderSideOrientation = options.sideOrientation;
  56463. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  56464. vertexData.applyToMesh(polygon, options.updatable);
  56465. return polygon;
  56466. };
  56467. ;
  56468. /**
  56469. * Creates an extruded polygon mesh, with depth in the Y direction.
  56470. * You can set different colors and different images to the top, bottom and extruded side by using the parameters `faceColors` (an array of 3 Color3 elements) and `faceUV` (an array of 3 Vector4 elements).
  56471. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  56472. */
  56473. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  56474. return MeshBuilder.CreatePolygon(name, options, scene);
  56475. };
  56476. ;
  56477. /**
  56478. * Creates a tube mesh.
  56479. * The tube is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  56480. *
  56481. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  56482. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  56483. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  56484. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  56485. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  56486. * This function is called on each point of the tube path and is passed the index `i` of the i-th point and the distance of this point from the first point of the path.
  56487. * It must return a radius value (positive float) :
  56488. * ```javascript
  56489. * var radiusFunction = function(i, distance) {
  56490. * // do things
  56491. * return radius; }
  56492. * ```
  56493. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  56494. * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL
  56495. * The optional parameter `instance` is an instance of an existing Tube object to be updated with the passed `pathArray` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#tube
  56496. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56497. * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4).
  56498. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56499. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  56500. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56501. */
  56502. MeshBuilder.CreateTube = function (name, options, scene) {
  56503. var path = options.path;
  56504. var instance = options.instance;
  56505. var radius = 1.0;
  56506. if (instance) {
  56507. radius = instance.radius;
  56508. }
  56509. if (options.radius !== undefined) {
  56510. radius = options.radius;
  56511. }
  56512. ;
  56513. var tessellation = options.tessellation || 64 | 0;
  56514. var radiusFunction = options.radiusFunction || null;
  56515. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  56516. var invertUV = options.invertUV || false;
  56517. var updatable = options.updatable;
  56518. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56519. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  56520. // tube geometry
  56521. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  56522. var tangents = path3D.getTangents();
  56523. var normals = path3D.getNormals();
  56524. var distances = path3D.getDistances();
  56525. var pi2 = Math.PI * 2;
  56526. var step = pi2 / tessellation * arc;
  56527. var returnRadius = function () { return radius; };
  56528. var radiusFunctionFinal = radiusFunction || returnRadius;
  56529. var circlePath;
  56530. var rad;
  56531. var normal;
  56532. var rotated;
  56533. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  56534. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  56535. for (var i = 0; i < path.length; i++) {
  56536. rad = radiusFunctionFinal(i, distances[i]); // current radius
  56537. circlePath = Array(); // current circle array
  56538. normal = normals[i]; // current normal
  56539. for (var t = 0; t < tessellation; t++) {
  56540. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  56541. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  56542. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  56543. rotated.scaleInPlace(rad).addInPlace(path[i]);
  56544. circlePath[t] = rotated;
  56545. }
  56546. circlePaths[index] = circlePath;
  56547. index++;
  56548. }
  56549. // cap
  56550. var capPath = function (nbPoints, pathIndex) {
  56551. var pointCap = Array();
  56552. for (var i = 0; i < nbPoints; i++) {
  56553. pointCap.push(path[pathIndex]);
  56554. }
  56555. return pointCap;
  56556. };
  56557. switch (cap) {
  56558. case BABYLON.Mesh.NO_CAP:
  56559. break;
  56560. case BABYLON.Mesh.CAP_START:
  56561. circlePaths[0] = capPath(tessellation, 0);
  56562. circlePaths[1] = circlePaths[2].slice(0);
  56563. break;
  56564. case BABYLON.Mesh.CAP_END:
  56565. circlePaths[index] = circlePaths[index - 1].slice(0);
  56566. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  56567. break;
  56568. case BABYLON.Mesh.CAP_ALL:
  56569. circlePaths[0] = capPath(tessellation, 0);
  56570. circlePaths[1] = circlePaths[2].slice(0);
  56571. circlePaths[index] = circlePaths[index - 1].slice(0);
  56572. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  56573. break;
  56574. default:
  56575. break;
  56576. }
  56577. return circlePaths;
  56578. };
  56579. var path3D;
  56580. var pathArray;
  56581. if (instance) {
  56582. var arc = options.arc || instance.arc;
  56583. path3D = (instance.path3D).update(path);
  56584. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  56585. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  56586. instance.path3D = path3D;
  56587. instance.pathArray = pathArray;
  56588. instance.arc = arc;
  56589. instance.radius = radius;
  56590. return instance;
  56591. }
  56592. // tube creation
  56593. path3D = new BABYLON.Path3D(path);
  56594. var newPathArray = new Array();
  56595. cap = (cap < 0 || cap > 3) ? 0 : cap;
  56596. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  56597. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  56598. tube.pathArray = pathArray;
  56599. tube.path3D = path3D;
  56600. tube.tessellation = tessellation;
  56601. tube.cap = cap;
  56602. tube.arc = options.arc;
  56603. tube.radius = radius;
  56604. return tube;
  56605. };
  56606. /**
  56607. * Creates a polyhedron mesh.
  56608. *
  56609. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  56610. * The parameter `type` (positive integer, max 14, default 0) sets the polyhedron type to build among the 15 embbeded types. Please refer to the type sheet in the tutorial
  56611. * to choose the wanted type.
  56612. * The parameter `size` (positive float, default 1) sets the polygon size.
  56613. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  56614. * You can build other polyhedron types than the 15 embbeded ones by setting the parameter `custom` (`polyhedronObject`, default null). If you set the parameter `custom`, this overwrittes the parameter `type`.
  56615. * A `polyhedronObject` is a formatted javascript object. You'll find a full file with pre-set polyhedra here : https://github.com/BabylonJS/Extensions/tree/master/Polyhedron
  56616. * You can set the color and the UV of each side of the polyhedron with the parameters `faceColors` (Color4, default `(1, 1, 1, 1)`) and faceUV (Vector4, default `(0, 0, 1, 1)`).
  56617. * To understand how to set `faceUV` or `faceColors`, please read this by considering the right number of faces of your polyhedron, instead of only 6 for the box : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  56618. * The parameter `flat` (boolean, default true). If set to false, it gives the polyhedron a single global face, so less vertices and shared normals. In this case, `faceColors` and `faceUV` are ignored.
  56619. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56620. * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4).
  56621. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56622. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56623. */
  56624. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  56625. var polyhedron = new BABYLON.Mesh(name, scene);
  56626. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56627. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  56628. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  56629. vertexData.applyToMesh(polyhedron, options.updatable);
  56630. return polyhedron;
  56631. };
  56632. /**
  56633. * Creates a decal mesh.
  56634. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  56635. * A decal is a mesh usually applied as a model onto the surface of another mesh. So don't forget the parameter `sourceMesh` depicting the decal.
  56636. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  56637. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  56638. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  56639. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  56640. */
  56641. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  56642. var indices = sourceMesh.getIndices();
  56643. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  56644. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  56645. var position = options.position || BABYLON.Vector3.Zero();
  56646. var normal = options.normal || BABYLON.Vector3.Up();
  56647. var size = options.size || BABYLON.Vector3.One();
  56648. var angle = options.angle || 0;
  56649. // Getting correct rotation
  56650. if (!normal) {
  56651. var target = new BABYLON.Vector3(0, 0, 1);
  56652. var camera = sourceMesh.getScene().activeCamera;
  56653. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  56654. normal = camera.globalPosition.subtract(cameraWorldTarget);
  56655. }
  56656. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  56657. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  56658. var pitch = Math.atan2(normal.y, len);
  56659. // Matrix
  56660. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  56661. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  56662. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  56663. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  56664. var vertexData = new BABYLON.VertexData();
  56665. vertexData.indices = [];
  56666. vertexData.positions = [];
  56667. vertexData.normals = [];
  56668. vertexData.uvs = [];
  56669. var currentVertexDataIndex = 0;
  56670. var extractDecalVector3 = function (indexId) {
  56671. var result = new BABYLON.PositionNormalVertex();
  56672. if (!indices || !positions || !normals) {
  56673. return result;
  56674. }
  56675. var vertexId = indices[indexId];
  56676. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  56677. // Send vector to decal local world
  56678. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  56679. // Get normal
  56680. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  56681. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  56682. return result;
  56683. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  56684. var clip = function (vertices, axis) {
  56685. if (vertices.length === 0) {
  56686. return vertices;
  56687. }
  56688. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  56689. var clipVertices = function (v0, v1) {
  56690. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  56691. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  56692. };
  56693. var result = new Array();
  56694. for (var index = 0; index < vertices.length; index += 3) {
  56695. var v1Out;
  56696. var v2Out;
  56697. var v3Out;
  56698. var total = 0;
  56699. var nV1 = null;
  56700. var nV2 = null;
  56701. var nV3 = null;
  56702. var nV4 = null;
  56703. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  56704. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  56705. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  56706. v1Out = d1 > 0;
  56707. v2Out = d2 > 0;
  56708. v3Out = d3 > 0;
  56709. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  56710. switch (total) {
  56711. case 0:
  56712. result.push(vertices[index]);
  56713. result.push(vertices[index + 1]);
  56714. result.push(vertices[index + 2]);
  56715. break;
  56716. case 1:
  56717. if (v1Out) {
  56718. nV1 = vertices[index + 1];
  56719. nV2 = vertices[index + 2];
  56720. nV3 = clipVertices(vertices[index], nV1);
  56721. nV4 = clipVertices(vertices[index], nV2);
  56722. }
  56723. if (v2Out) {
  56724. nV1 = vertices[index];
  56725. nV2 = vertices[index + 2];
  56726. nV3 = clipVertices(vertices[index + 1], nV1);
  56727. nV4 = clipVertices(vertices[index + 1], nV2);
  56728. result.push(nV3);
  56729. result.push(nV2.clone());
  56730. result.push(nV1.clone());
  56731. result.push(nV2.clone());
  56732. result.push(nV3.clone());
  56733. result.push(nV4);
  56734. break;
  56735. }
  56736. if (v3Out) {
  56737. nV1 = vertices[index];
  56738. nV2 = vertices[index + 1];
  56739. nV3 = clipVertices(vertices[index + 2], nV1);
  56740. nV4 = clipVertices(vertices[index + 2], nV2);
  56741. }
  56742. if (nV1 && nV2 && nV3 && nV4) {
  56743. result.push(nV1.clone());
  56744. result.push(nV2.clone());
  56745. result.push(nV3);
  56746. result.push(nV4);
  56747. result.push(nV3.clone());
  56748. result.push(nV2.clone());
  56749. }
  56750. break;
  56751. case 2:
  56752. if (!v1Out) {
  56753. nV1 = vertices[index].clone();
  56754. nV2 = clipVertices(nV1, vertices[index + 1]);
  56755. nV3 = clipVertices(nV1, vertices[index + 2]);
  56756. result.push(nV1);
  56757. result.push(nV2);
  56758. result.push(nV3);
  56759. }
  56760. if (!v2Out) {
  56761. nV1 = vertices[index + 1].clone();
  56762. nV2 = clipVertices(nV1, vertices[index + 2]);
  56763. nV3 = clipVertices(nV1, vertices[index]);
  56764. result.push(nV1);
  56765. result.push(nV2);
  56766. result.push(nV3);
  56767. }
  56768. if (!v3Out) {
  56769. nV1 = vertices[index + 2].clone();
  56770. nV2 = clipVertices(nV1, vertices[index]);
  56771. nV3 = clipVertices(nV1, vertices[index + 1]);
  56772. result.push(nV1);
  56773. result.push(nV2);
  56774. result.push(nV3);
  56775. }
  56776. break;
  56777. case 3:
  56778. break;
  56779. }
  56780. }
  56781. return result;
  56782. };
  56783. for (var index = 0; index < indices.length; index += 3) {
  56784. var faceVertices = new Array();
  56785. faceVertices.push(extractDecalVector3(index));
  56786. faceVertices.push(extractDecalVector3(index + 1));
  56787. faceVertices.push(extractDecalVector3(index + 2));
  56788. // Clip
  56789. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  56790. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  56791. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  56792. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  56793. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  56794. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  56795. if (faceVertices.length === 0) {
  56796. continue;
  56797. }
  56798. // Add UVs and get back to world
  56799. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  56800. var vertex = faceVertices[vIndex];
  56801. //TODO check for Int32Array | Uint32Array | Uint16Array
  56802. vertexData.indices.push(currentVertexDataIndex);
  56803. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  56804. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  56805. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  56806. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  56807. currentVertexDataIndex++;
  56808. }
  56809. }
  56810. // Return mesh
  56811. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  56812. vertexData.applyToMesh(decal);
  56813. decal.position = position.clone();
  56814. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  56815. return decal;
  56816. };
  56817. // Privates
  56818. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  56819. // extrusion geometry
  56820. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  56821. var tangents = path3D.getTangents();
  56822. var normals = path3D.getNormals();
  56823. var binormals = path3D.getBinormals();
  56824. var distances = path3D.getDistances();
  56825. var angle = 0;
  56826. var returnScale = function () { return scale !== null ? scale : 1; };
  56827. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  56828. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  56829. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  56830. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  56831. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  56832. for (var i = 0; i < curve.length; i++) {
  56833. var shapePath = new Array();
  56834. var angleStep = rotate(i, distances[i]);
  56835. var scaleRatio = scl(i, distances[i]);
  56836. for (var p = 0; p < shape.length; p++) {
  56837. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  56838. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  56839. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  56840. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  56841. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  56842. shapePath[p] = rotated;
  56843. }
  56844. shapePaths[index] = shapePath;
  56845. angle += angleStep;
  56846. index++;
  56847. }
  56848. // cap
  56849. var capPath = function (shapePath) {
  56850. var pointCap = Array();
  56851. var barycenter = BABYLON.Vector3.Zero();
  56852. var i;
  56853. for (i = 0; i < shapePath.length; i++) {
  56854. barycenter.addInPlace(shapePath[i]);
  56855. }
  56856. barycenter.scaleInPlace(1.0 / shapePath.length);
  56857. for (i = 0; i < shapePath.length; i++) {
  56858. pointCap.push(barycenter);
  56859. }
  56860. return pointCap;
  56861. };
  56862. switch (cap) {
  56863. case BABYLON.Mesh.NO_CAP:
  56864. break;
  56865. case BABYLON.Mesh.CAP_START:
  56866. shapePaths[0] = capPath(shapePaths[2]);
  56867. shapePaths[1] = shapePaths[2];
  56868. break;
  56869. case BABYLON.Mesh.CAP_END:
  56870. shapePaths[index] = shapePaths[index - 1];
  56871. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  56872. break;
  56873. case BABYLON.Mesh.CAP_ALL:
  56874. shapePaths[0] = capPath(shapePaths[2]);
  56875. shapePaths[1] = shapePaths[2];
  56876. shapePaths[index] = shapePaths[index - 1];
  56877. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  56878. break;
  56879. default:
  56880. break;
  56881. }
  56882. return shapePaths;
  56883. };
  56884. var path3D;
  56885. var pathArray;
  56886. if (instance) {
  56887. path3D = (instance.path3D).update(curve);
  56888. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  56889. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  56890. return instance;
  56891. }
  56892. // extruded shape creation
  56893. path3D = new BABYLON.Path3D(curve);
  56894. var newShapePaths = new Array();
  56895. cap = (cap < 0 || cap > 3) ? 0 : cap;
  56896. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  56897. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  56898. extrudedGeneric.pathArray = pathArray;
  56899. extrudedGeneric.path3D = path3D;
  56900. extrudedGeneric.cap = cap;
  56901. return extrudedGeneric;
  56902. };
  56903. return MeshBuilder;
  56904. }());
  56905. BABYLON.MeshBuilder = MeshBuilder;
  56906. })(BABYLON || (BABYLON = {}));
  56907. //# sourceMappingURL=babylon.meshBuilder.js.map
  56908. var BABYLON;
  56909. (function (BABYLON) {
  56910. /**
  56911. * Draco compression (https://google.github.io/draco/)
  56912. */
  56913. var DracoCompression = /** @class */ (function () {
  56914. /**
  56915. * Constructor
  56916. * @param numWorkers The number of workers for async operations
  56917. */
  56918. function DracoCompression(numWorkers) {
  56919. if (numWorkers === void 0) { numWorkers = (navigator.hardwareConcurrency || 4); }
  56920. var workerBlobUrl = URL && URL.createObjectURL && URL.createObjectURL(new Blob(["(" + DracoCompression._Worker.toString() + ")()"], { type: "application/javascript" }));
  56921. if (!workerBlobUrl || !Worker) {
  56922. BABYLON.Tools.Error("Draco Compression disabled. The current context doesn't support worker creation or URL.createObjectURL");
  56923. return;
  56924. }
  56925. var workers = new Array(numWorkers);
  56926. for (var i = 0; i < workers.length; i++) {
  56927. var worker = new Worker(workerBlobUrl);
  56928. worker.postMessage({ id: "initDecoder", url: DracoCompression.DecoderUrl });
  56929. workers[i] = worker;
  56930. }
  56931. this._workerPool = new BABYLON.WorkerPool(workers);
  56932. }
  56933. /**
  56934. * Stop all async operations and release resources.
  56935. */
  56936. DracoCompression.prototype.dispose = function () {
  56937. this._workerPool.dispose();
  56938. delete this._workerPool;
  56939. };
  56940. /**
  56941. * Decode Draco compressed mesh data to vertex data.
  56942. * @param data The array buffer view for the Draco compression data
  56943. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  56944. * @returns A promise that resolves with the decoded vertex data
  56945. */
  56946. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  56947. var _this = this;
  56948. return new Promise(function (resolve, reject) {
  56949. _this._workerPool.push(function (worker, onComplete) {
  56950. var vertexData = new BABYLON.VertexData();
  56951. var onError = function (error) {
  56952. worker.removeEventListener("error", onError);
  56953. worker.removeEventListener("message", onMessage);
  56954. reject(error);
  56955. onComplete();
  56956. };
  56957. var onMessage = function (message) {
  56958. if (message.data === "done") {
  56959. worker.removeEventListener("error", onError);
  56960. worker.removeEventListener("message", onMessage);
  56961. resolve(vertexData);
  56962. onComplete();
  56963. }
  56964. else if (message.data.id === "indices") {
  56965. vertexData.indices = message.data.value;
  56966. }
  56967. else {
  56968. vertexData.set(message.data.value, message.data.id);
  56969. }
  56970. };
  56971. worker.addEventListener("error", onError);
  56972. worker.addEventListener("message", onMessage);
  56973. var dataCopy = new Uint8Array(data.byteLength);
  56974. dataCopy.set(new Uint8Array(data.buffer, data.byteOffset, data.byteLength));
  56975. worker.postMessage({ id: "decodeMesh", data: dataCopy, attributes: attributes }, [dataCopy.buffer]);
  56976. });
  56977. });
  56978. };
  56979. /**
  56980. * The worker function that gets converted to a blob url to pass into a worker.
  56981. */
  56982. DracoCompression._Worker = function () {
  56983. // self is actually a DedicatedWorkerGlobalScope
  56984. var _self = self;
  56985. var decodeMesh = function (data, attributes) {
  56986. var dracoModule = new DracoDecoderModule();
  56987. var buffer = new dracoModule.DecoderBuffer();
  56988. buffer.Init(data, data.byteLength);
  56989. var decoder = new dracoModule.Decoder();
  56990. var geometry;
  56991. var status;
  56992. try {
  56993. var type = decoder.GetEncodedGeometryType(buffer);
  56994. switch (type) {
  56995. case dracoModule.TRIANGULAR_MESH:
  56996. geometry = new dracoModule.Mesh();
  56997. status = decoder.DecodeBufferToMesh(buffer, geometry);
  56998. break;
  56999. case dracoModule.POINT_CLOUD:
  57000. geometry = new dracoModule.PointCloud();
  57001. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  57002. break;
  57003. default:
  57004. throw new Error("Invalid geometry type " + type);
  57005. }
  57006. if (!status.ok() || !geometry.ptr) {
  57007. throw new Error(status.error_msg());
  57008. }
  57009. var numPoints = geometry.num_points();
  57010. if (type === dracoModule.TRIANGULAR_MESH) {
  57011. var numFaces = geometry.num_faces();
  57012. var faceIndices = new dracoModule.DracoInt32Array();
  57013. try {
  57014. var indices = new Uint32Array(numFaces * 3);
  57015. for (var i = 0; i < numFaces; i++) {
  57016. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  57017. var offset = i * 3;
  57018. indices[offset + 0] = faceIndices.GetValue(0);
  57019. indices[offset + 1] = faceIndices.GetValue(1);
  57020. indices[offset + 2] = faceIndices.GetValue(2);
  57021. }
  57022. _self.postMessage({ id: "indices", value: indices }, [indices.buffer]);
  57023. }
  57024. finally {
  57025. dracoModule.destroy(faceIndices);
  57026. }
  57027. }
  57028. for (var kind in attributes) {
  57029. var uniqueId = attributes[kind];
  57030. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  57031. var dracoData = new dracoModule.DracoFloat32Array();
  57032. try {
  57033. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  57034. var babylonData = new Float32Array(numPoints * attribute.num_components());
  57035. for (var i = 0; i < babylonData.length; i++) {
  57036. babylonData[i] = dracoData.GetValue(i);
  57037. }
  57038. _self.postMessage({ id: kind, value: babylonData }, [babylonData.buffer]);
  57039. }
  57040. finally {
  57041. dracoModule.destroy(dracoData);
  57042. }
  57043. }
  57044. }
  57045. finally {
  57046. if (geometry) {
  57047. dracoModule.destroy(geometry);
  57048. }
  57049. dracoModule.destroy(decoder);
  57050. dracoModule.destroy(buffer);
  57051. }
  57052. _self.postMessage("done");
  57053. };
  57054. _self.onmessage = function (event) {
  57055. switch (event.data.id) {
  57056. case "initDecoder": {
  57057. importScripts(event.data.url);
  57058. break;
  57059. }
  57060. case "decodeMesh": {
  57061. decodeMesh(event.data.data, event.data.attributes);
  57062. break;
  57063. }
  57064. }
  57065. };
  57066. };
  57067. DracoCompression._GetDefaultDecoderUrl = function () {
  57068. if (!BABYLON.Tools.IsWindowObjectExist) {
  57069. return null;
  57070. }
  57071. for (var i = 0; i < document.scripts.length; i++) {
  57072. if (document.scripts[i].type === "text/x-draco-decoder") {
  57073. return document.scripts[i].src;
  57074. }
  57075. }
  57076. return null;
  57077. };
  57078. /**
  57079. * Gets the url to the draco decoder if available.
  57080. */
  57081. DracoCompression.DecoderUrl = DracoCompression._GetDefaultDecoderUrl();
  57082. return DracoCompression;
  57083. }());
  57084. BABYLON.DracoCompression = DracoCompression;
  57085. })(BABYLON || (BABYLON = {}));
  57086. //# sourceMappingURL=babylon.dracoCompression.js.map
  57087. var BABYLON;
  57088. (function (BABYLON) {
  57089. var AudioEngine = /** @class */ (function () {
  57090. function AudioEngine() {
  57091. this._audioContext = null;
  57092. this._audioContextInitialized = false;
  57093. this.canUseWebAudio = false;
  57094. this.WarnedWebAudioUnsupported = false;
  57095. this.unlocked = false;
  57096. this.isMP3supported = false;
  57097. this.isOGGsupported = false;
  57098. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  57099. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  57100. this.canUseWebAudio = true;
  57101. }
  57102. var audioElem = document.createElement('audio');
  57103. try {
  57104. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  57105. this.isMP3supported = true;
  57106. }
  57107. }
  57108. catch (e) {
  57109. // protect error during capability check.
  57110. }
  57111. try {
  57112. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  57113. this.isOGGsupported = true;
  57114. }
  57115. }
  57116. catch (e) {
  57117. // protect error during capability check.
  57118. }
  57119. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  57120. this._unlockiOSaudio();
  57121. }
  57122. else {
  57123. this.unlocked = true;
  57124. }
  57125. }
  57126. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  57127. get: function () {
  57128. if (!this._audioContextInitialized) {
  57129. this._initializeAudioContext();
  57130. }
  57131. return this._audioContext;
  57132. },
  57133. enumerable: true,
  57134. configurable: true
  57135. });
  57136. AudioEngine.prototype._unlockiOSaudio = function () {
  57137. var _this = this;
  57138. var unlockaudio = function () {
  57139. if (!_this.audioContext) {
  57140. return;
  57141. }
  57142. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  57143. var source = _this.audioContext.createBufferSource();
  57144. source.buffer = buffer;
  57145. source.connect(_this.audioContext.destination);
  57146. source.start(0);
  57147. setTimeout(function () {
  57148. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  57149. _this.unlocked = true;
  57150. window.removeEventListener('touchend', unlockaudio, false);
  57151. if (_this.onAudioUnlocked) {
  57152. _this.onAudioUnlocked();
  57153. }
  57154. }
  57155. }, 0);
  57156. };
  57157. window.addEventListener('touchend', unlockaudio, false);
  57158. };
  57159. AudioEngine.prototype._initializeAudioContext = function () {
  57160. try {
  57161. if (this.canUseWebAudio) {
  57162. this._audioContext = new AudioContext();
  57163. // create a global volume gain node
  57164. this.masterGain = this._audioContext.createGain();
  57165. this.masterGain.gain.value = 1;
  57166. this.masterGain.connect(this._audioContext.destination);
  57167. this._audioContextInitialized = true;
  57168. }
  57169. }
  57170. catch (e) {
  57171. this.canUseWebAudio = false;
  57172. BABYLON.Tools.Error("Web Audio: " + e.message);
  57173. }
  57174. };
  57175. AudioEngine.prototype.dispose = function () {
  57176. if (this.canUseWebAudio && this._audioContextInitialized) {
  57177. if (this._connectedAnalyser && this._audioContext) {
  57178. this._connectedAnalyser.stopDebugCanvas();
  57179. this._connectedAnalyser.dispose();
  57180. this.masterGain.disconnect();
  57181. this.masterGain.connect(this._audioContext.destination);
  57182. this._connectedAnalyser = null;
  57183. }
  57184. this.masterGain.gain.value = 1;
  57185. }
  57186. this.WarnedWebAudioUnsupported = false;
  57187. };
  57188. AudioEngine.prototype.getGlobalVolume = function () {
  57189. if (this.canUseWebAudio && this._audioContextInitialized) {
  57190. return this.masterGain.gain.value;
  57191. }
  57192. else {
  57193. return -1;
  57194. }
  57195. };
  57196. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  57197. if (this.canUseWebAudio && this._audioContextInitialized) {
  57198. this.masterGain.gain.value = newVolume;
  57199. }
  57200. };
  57201. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  57202. if (this._connectedAnalyser) {
  57203. this._connectedAnalyser.stopDebugCanvas();
  57204. }
  57205. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  57206. this._connectedAnalyser = analyser;
  57207. this.masterGain.disconnect();
  57208. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  57209. }
  57210. };
  57211. return AudioEngine;
  57212. }());
  57213. BABYLON.AudioEngine = AudioEngine;
  57214. })(BABYLON || (BABYLON = {}));
  57215. //# sourceMappingURL=babylon.audioEngine.js.map
  57216. var BABYLON;
  57217. (function (BABYLON) {
  57218. var Sound = /** @class */ (function () {
  57219. /**
  57220. * Create a sound and attach it to a scene
  57221. * @param name Name of your sound
  57222. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  57223. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  57224. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  57225. */
  57226. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  57227. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  57228. var _this = this;
  57229. this.autoplay = false;
  57230. this.loop = false;
  57231. this.useCustomAttenuation = false;
  57232. this.spatialSound = false;
  57233. this.refDistance = 1;
  57234. this.rolloffFactor = 1;
  57235. this.maxDistance = 100;
  57236. this.distanceModel = "linear";
  57237. this._panningModel = "equalpower";
  57238. this._playbackRate = 1;
  57239. this._streaming = false;
  57240. this._startTime = 0;
  57241. this._startOffset = 0;
  57242. this._position = BABYLON.Vector3.Zero();
  57243. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  57244. this._volume = 1;
  57245. this._isReadyToPlay = false;
  57246. this.isPlaying = false;
  57247. this.isPaused = false;
  57248. this._isDirectional = false;
  57249. // Used if you'd like to create a directional sound.
  57250. // If not set, the sound will be omnidirectional
  57251. this._coneInnerAngle = 360;
  57252. this._coneOuterAngle = 360;
  57253. this._coneOuterGain = 0;
  57254. this._isOutputConnected = false;
  57255. this._urlType = "Unknown";
  57256. this.name = name;
  57257. this._scene = scene;
  57258. this._readyToPlayCallback = readyToPlayCallback;
  57259. // Default custom attenuation function is a linear attenuation
  57260. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  57261. if (currentDistance < maxDistance) {
  57262. return currentVolume * (1 - currentDistance / maxDistance);
  57263. }
  57264. else {
  57265. return 0;
  57266. }
  57267. };
  57268. if (options) {
  57269. this.autoplay = options.autoplay || false;
  57270. this.loop = options.loop || false;
  57271. // if volume === 0, we need another way to check this option
  57272. if (options.volume !== undefined) {
  57273. this._volume = options.volume;
  57274. }
  57275. this.spatialSound = options.spatialSound || false;
  57276. this.maxDistance = options.maxDistance || 100;
  57277. this.useCustomAttenuation = options.useCustomAttenuation || false;
  57278. this.rolloffFactor = options.rolloffFactor || 1;
  57279. this.refDistance = options.refDistance || 1;
  57280. this.distanceModel = options.distanceModel || "linear";
  57281. this._playbackRate = options.playbackRate || 1;
  57282. this._streaming = options.streaming || false;
  57283. }
  57284. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  57285. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  57286. this._soundGain.gain.value = this._volume;
  57287. this._inputAudioNode = this._soundGain;
  57288. this._ouputAudioNode = this._soundGain;
  57289. if (this.spatialSound) {
  57290. this._createSpatialParameters();
  57291. }
  57292. this._scene.mainSoundTrack.AddSound(this);
  57293. var validParameter = true;
  57294. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  57295. if (urlOrArrayBuffer) {
  57296. if (typeof (urlOrArrayBuffer) === "string")
  57297. this._urlType = "String";
  57298. if (Array.isArray(urlOrArrayBuffer))
  57299. this._urlType = "Array";
  57300. if (urlOrArrayBuffer instanceof ArrayBuffer)
  57301. this._urlType = "ArrayBuffer";
  57302. var urls = [];
  57303. var codecSupportedFound = false;
  57304. switch (this._urlType) {
  57305. case "ArrayBuffer":
  57306. if (urlOrArrayBuffer.byteLength > 0) {
  57307. codecSupportedFound = true;
  57308. this._soundLoaded(urlOrArrayBuffer);
  57309. }
  57310. break;
  57311. case "String":
  57312. urls.push(urlOrArrayBuffer);
  57313. case "Array":
  57314. if (urls.length === 0)
  57315. urls = urlOrArrayBuffer;
  57316. // If we found a supported format, we load it immediately and stop the loop
  57317. for (var i = 0; i < urls.length; i++) {
  57318. var url = urls[i];
  57319. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  57320. codecSupportedFound = true;
  57321. }
  57322. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  57323. codecSupportedFound = true;
  57324. }
  57325. if (url.indexOf(".wav", url.length - 4) !== -1) {
  57326. codecSupportedFound = true;
  57327. }
  57328. if (url.indexOf("blob:") !== -1) {
  57329. codecSupportedFound = true;
  57330. }
  57331. if (codecSupportedFound) {
  57332. // Loading sound using XHR2
  57333. if (!this._streaming) {
  57334. this._scene._loadFile(url, function (data) { _this._soundLoaded(data); }, undefined, true, true);
  57335. }
  57336. else {
  57337. this._htmlAudioElement = new Audio(url);
  57338. this._htmlAudioElement.controls = false;
  57339. this._htmlAudioElement.loop = this.loop;
  57340. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  57341. this._htmlAudioElement.preload = "auto";
  57342. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  57343. _this._isReadyToPlay = true;
  57344. if (_this.autoplay) {
  57345. _this.play();
  57346. }
  57347. if (_this._readyToPlayCallback) {
  57348. _this._readyToPlayCallback();
  57349. }
  57350. });
  57351. document.body.appendChild(this._htmlAudioElement);
  57352. }
  57353. break;
  57354. }
  57355. }
  57356. break;
  57357. default:
  57358. validParameter = false;
  57359. break;
  57360. }
  57361. if (!validParameter) {
  57362. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  57363. }
  57364. else {
  57365. if (!codecSupportedFound) {
  57366. this._isReadyToPlay = true;
  57367. // Simulating a ready to play event to avoid breaking code path
  57368. if (this._readyToPlayCallback) {
  57369. window.setTimeout(function () {
  57370. if (_this._readyToPlayCallback) {
  57371. _this._readyToPlayCallback();
  57372. }
  57373. }, 1000);
  57374. }
  57375. }
  57376. }
  57377. }
  57378. }
  57379. else {
  57380. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  57381. this._scene.mainSoundTrack.AddSound(this);
  57382. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  57383. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  57384. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  57385. }
  57386. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  57387. if (this._readyToPlayCallback) {
  57388. window.setTimeout(function () {
  57389. if (_this._readyToPlayCallback) {
  57390. _this._readyToPlayCallback();
  57391. }
  57392. }, 1000);
  57393. }
  57394. }
  57395. }
  57396. Sound.prototype.dispose = function () {
  57397. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  57398. if (this.isPlaying) {
  57399. this.stop();
  57400. }
  57401. this._isReadyToPlay = false;
  57402. if (this.soundTrackId === -1) {
  57403. this._scene.mainSoundTrack.RemoveSound(this);
  57404. }
  57405. else {
  57406. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  57407. }
  57408. if (this._soundGain) {
  57409. this._soundGain.disconnect();
  57410. this._soundGain = null;
  57411. }
  57412. if (this._soundPanner) {
  57413. this._soundPanner.disconnect();
  57414. this._soundPanner = null;
  57415. }
  57416. if (this._soundSource) {
  57417. this._soundSource.disconnect();
  57418. this._soundSource = null;
  57419. }
  57420. this._audioBuffer = null;
  57421. if (this._htmlAudioElement) {
  57422. this._htmlAudioElement.pause();
  57423. this._htmlAudioElement.src = "";
  57424. document.body.removeChild(this._htmlAudioElement);
  57425. }
  57426. if (this._connectedMesh && this._registerFunc) {
  57427. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  57428. this._connectedMesh = null;
  57429. }
  57430. }
  57431. };
  57432. Sound.prototype.isReady = function () {
  57433. return this._isReadyToPlay;
  57434. };
  57435. Sound.prototype._soundLoaded = function (audioData) {
  57436. var _this = this;
  57437. if (!BABYLON.Engine.audioEngine.audioContext) {
  57438. return;
  57439. }
  57440. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  57441. _this._audioBuffer = buffer;
  57442. _this._isReadyToPlay = true;
  57443. if (_this.autoplay) {
  57444. _this.play();
  57445. }
  57446. if (_this._readyToPlayCallback) {
  57447. _this._readyToPlayCallback();
  57448. }
  57449. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  57450. };
  57451. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  57452. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  57453. this._audioBuffer = audioBuffer;
  57454. this._isReadyToPlay = true;
  57455. }
  57456. };
  57457. Sound.prototype.updateOptions = function (options) {
  57458. if (options) {
  57459. this.loop = options.loop || this.loop;
  57460. this.maxDistance = options.maxDistance || this.maxDistance;
  57461. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  57462. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  57463. this.refDistance = options.refDistance || this.refDistance;
  57464. this.distanceModel = options.distanceModel || this.distanceModel;
  57465. this._playbackRate = options.playbackRate || this._playbackRate;
  57466. this._updateSpatialParameters();
  57467. if (this.isPlaying) {
  57468. if (this._streaming) {
  57469. this._htmlAudioElement.playbackRate = this._playbackRate;
  57470. }
  57471. else {
  57472. if (this._soundSource) {
  57473. this._soundSource.playbackRate.value = this._playbackRate;
  57474. }
  57475. }
  57476. }
  57477. }
  57478. };
  57479. Sound.prototype._createSpatialParameters = function () {
  57480. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  57481. if (this._scene.headphone) {
  57482. this._panningModel = "HRTF";
  57483. }
  57484. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  57485. this._updateSpatialParameters();
  57486. this._soundPanner.connect(this._ouputAudioNode);
  57487. this._inputAudioNode = this._soundPanner;
  57488. }
  57489. };
  57490. Sound.prototype._updateSpatialParameters = function () {
  57491. if (this.spatialSound && this._soundPanner) {
  57492. if (this.useCustomAttenuation) {
  57493. // Tricks to disable in a way embedded Web Audio attenuation
  57494. this._soundPanner.distanceModel = "linear";
  57495. this._soundPanner.maxDistance = Number.MAX_VALUE;
  57496. this._soundPanner.refDistance = 1;
  57497. this._soundPanner.rolloffFactor = 1;
  57498. this._soundPanner.panningModel = this._panningModel;
  57499. }
  57500. else {
  57501. this._soundPanner.distanceModel = this.distanceModel;
  57502. this._soundPanner.maxDistance = this.maxDistance;
  57503. this._soundPanner.refDistance = this.refDistance;
  57504. this._soundPanner.rolloffFactor = this.rolloffFactor;
  57505. this._soundPanner.panningModel = this._panningModel;
  57506. }
  57507. }
  57508. };
  57509. Sound.prototype.switchPanningModelToHRTF = function () {
  57510. this._panningModel = "HRTF";
  57511. this._switchPanningModel();
  57512. };
  57513. Sound.prototype.switchPanningModelToEqualPower = function () {
  57514. this._panningModel = "equalpower";
  57515. this._switchPanningModel();
  57516. };
  57517. Sound.prototype._switchPanningModel = function () {
  57518. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  57519. this._soundPanner.panningModel = this._panningModel;
  57520. }
  57521. };
  57522. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  57523. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  57524. if (this._isOutputConnected) {
  57525. this._ouputAudioNode.disconnect();
  57526. }
  57527. this._ouputAudioNode.connect(soundTrackAudioNode);
  57528. this._isOutputConnected = true;
  57529. }
  57530. };
  57531. /**
  57532. * Transform this sound into a directional source
  57533. * @param coneInnerAngle Size of the inner cone in degree
  57534. * @param coneOuterAngle Size of the outer cone in degree
  57535. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  57536. */
  57537. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  57538. if (coneOuterAngle < coneInnerAngle) {
  57539. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  57540. return;
  57541. }
  57542. this._coneInnerAngle = coneInnerAngle;
  57543. this._coneOuterAngle = coneOuterAngle;
  57544. this._coneOuterGain = coneOuterGain;
  57545. this._isDirectional = true;
  57546. if (this.isPlaying && this.loop) {
  57547. this.stop();
  57548. this.play();
  57549. }
  57550. };
  57551. Sound.prototype.setPosition = function (newPosition) {
  57552. this._position = newPosition;
  57553. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  57554. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  57555. }
  57556. };
  57557. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  57558. this._localDirection = newLocalDirection;
  57559. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  57560. this._updateDirection();
  57561. }
  57562. };
  57563. Sound.prototype._updateDirection = function () {
  57564. if (!this._connectedMesh || !this._soundPanner) {
  57565. return;
  57566. }
  57567. var mat = this._connectedMesh.getWorldMatrix();
  57568. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  57569. direction.normalize();
  57570. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  57571. };
  57572. Sound.prototype.updateDistanceFromListener = function () {
  57573. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  57574. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  57575. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  57576. }
  57577. };
  57578. Sound.prototype.setAttenuationFunction = function (callback) {
  57579. this._customAttenuationFunction = callback;
  57580. };
  57581. /**
  57582. * Play the sound
  57583. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  57584. * @param offset (optional) Start the sound setting it at a specific time
  57585. */
  57586. Sound.prototype.play = function (time, offset) {
  57587. var _this = this;
  57588. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  57589. try {
  57590. if (this._startOffset < 0) {
  57591. time = -this._startOffset;
  57592. this._startOffset = 0;
  57593. }
  57594. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  57595. if (!this._soundSource || !this._streamingSource) {
  57596. if (this.spatialSound && this._soundPanner) {
  57597. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  57598. if (this._isDirectional) {
  57599. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  57600. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  57601. this._soundPanner.coneOuterGain = this._coneOuterGain;
  57602. if (this._connectedMesh) {
  57603. this._updateDirection();
  57604. }
  57605. else {
  57606. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  57607. }
  57608. }
  57609. }
  57610. }
  57611. if (this._streaming) {
  57612. if (!this._streamingSource) {
  57613. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  57614. this._htmlAudioElement.onended = function () { _this._onended(); };
  57615. this._htmlAudioElement.playbackRate = this._playbackRate;
  57616. }
  57617. this._streamingSource.disconnect();
  57618. this._streamingSource.connect(this._inputAudioNode);
  57619. this._htmlAudioElement.play();
  57620. }
  57621. else {
  57622. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  57623. this._soundSource.buffer = this._audioBuffer;
  57624. this._soundSource.connect(this._inputAudioNode);
  57625. this._soundSource.loop = this.loop;
  57626. this._soundSource.playbackRate.value = this._playbackRate;
  57627. this._soundSource.onended = function () { _this._onended(); };
  57628. if (this._soundSource.buffer) {
  57629. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  57630. }
  57631. }
  57632. this._startTime = startTime;
  57633. this.isPlaying = true;
  57634. this.isPaused = false;
  57635. }
  57636. catch (ex) {
  57637. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  57638. }
  57639. }
  57640. };
  57641. Sound.prototype._onended = function () {
  57642. this.isPlaying = false;
  57643. if (this.onended) {
  57644. this.onended();
  57645. }
  57646. };
  57647. /**
  57648. * Stop the sound
  57649. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  57650. */
  57651. Sound.prototype.stop = function (time) {
  57652. if (this.isPlaying) {
  57653. if (this._streaming) {
  57654. this._htmlAudioElement.pause();
  57655. // Test needed for Firefox or it will generate an Invalid State Error
  57656. if (this._htmlAudioElement.currentTime > 0) {
  57657. this._htmlAudioElement.currentTime = 0;
  57658. }
  57659. }
  57660. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  57661. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  57662. this._soundSource.stop(stopTime);
  57663. this._soundSource.onended = function () { };
  57664. if (!this.isPaused) {
  57665. this._startOffset = 0;
  57666. }
  57667. }
  57668. this.isPlaying = false;
  57669. }
  57670. };
  57671. Sound.prototype.pause = function () {
  57672. if (this.isPlaying) {
  57673. this.isPaused = true;
  57674. if (this._streaming) {
  57675. this._htmlAudioElement.pause();
  57676. }
  57677. else if (BABYLON.Engine.audioEngine.audioContext) {
  57678. this.stop(0);
  57679. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  57680. }
  57681. }
  57682. };
  57683. Sound.prototype.setVolume = function (newVolume, time) {
  57684. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  57685. if (time && BABYLON.Engine.audioEngine.audioContext) {
  57686. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  57687. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  57688. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  57689. }
  57690. else {
  57691. this._soundGain.gain.value = newVolume;
  57692. }
  57693. }
  57694. this._volume = newVolume;
  57695. };
  57696. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  57697. this._playbackRate = newPlaybackRate;
  57698. if (this.isPlaying) {
  57699. if (this._streaming) {
  57700. this._htmlAudioElement.playbackRate = this._playbackRate;
  57701. }
  57702. else if (this._soundSource) {
  57703. this._soundSource.playbackRate.value = this._playbackRate;
  57704. }
  57705. }
  57706. };
  57707. Sound.prototype.getVolume = function () {
  57708. return this._volume;
  57709. };
  57710. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  57711. var _this = this;
  57712. if (this._connectedMesh && this._registerFunc) {
  57713. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  57714. this._registerFunc = null;
  57715. }
  57716. this._connectedMesh = meshToConnectTo;
  57717. if (!this.spatialSound) {
  57718. this.spatialSound = true;
  57719. this._createSpatialParameters();
  57720. if (this.isPlaying && this.loop) {
  57721. this.stop();
  57722. this.play();
  57723. }
  57724. }
  57725. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  57726. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  57727. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  57728. };
  57729. Sound.prototype.detachFromMesh = function () {
  57730. if (this._connectedMesh && this._registerFunc) {
  57731. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  57732. this._registerFunc = null;
  57733. this._connectedMesh = null;
  57734. }
  57735. };
  57736. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  57737. if (!node.getBoundingInfo) {
  57738. return;
  57739. }
  57740. var mesh = node;
  57741. var boundingInfo = mesh.getBoundingInfo();
  57742. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  57743. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  57744. this._updateDirection();
  57745. }
  57746. };
  57747. Sound.prototype.clone = function () {
  57748. var _this = this;
  57749. if (!this._streaming) {
  57750. var setBufferAndRun = function () {
  57751. if (_this._isReadyToPlay) {
  57752. clonedSound._audioBuffer = _this.getAudioBuffer();
  57753. clonedSound._isReadyToPlay = true;
  57754. if (clonedSound.autoplay) {
  57755. clonedSound.play();
  57756. }
  57757. }
  57758. else {
  57759. window.setTimeout(setBufferAndRun, 300);
  57760. }
  57761. };
  57762. var currentOptions = {
  57763. autoplay: this.autoplay, loop: this.loop,
  57764. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  57765. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  57766. refDistance: this.refDistance, distanceModel: this.distanceModel
  57767. };
  57768. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  57769. if (this.useCustomAttenuation) {
  57770. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  57771. }
  57772. clonedSound.setPosition(this._position);
  57773. clonedSound.setPlaybackRate(this._playbackRate);
  57774. setBufferAndRun();
  57775. return clonedSound;
  57776. }
  57777. else {
  57778. return null;
  57779. }
  57780. };
  57781. Sound.prototype.getAudioBuffer = function () {
  57782. return this._audioBuffer;
  57783. };
  57784. Sound.prototype.serialize = function () {
  57785. var serializationObject = {
  57786. name: this.name,
  57787. url: this.name,
  57788. autoplay: this.autoplay,
  57789. loop: this.loop,
  57790. volume: this._volume,
  57791. spatialSound: this.spatialSound,
  57792. maxDistance: this.maxDistance,
  57793. rolloffFactor: this.rolloffFactor,
  57794. refDistance: this.refDistance,
  57795. distanceModel: this.distanceModel,
  57796. playbackRate: this._playbackRate,
  57797. panningModel: this._panningModel,
  57798. soundTrackId: this.soundTrackId
  57799. };
  57800. if (this.spatialSound) {
  57801. if (this._connectedMesh)
  57802. serializationObject.connectedMeshId = this._connectedMesh.id;
  57803. serializationObject.position = this._position.asArray();
  57804. serializationObject.refDistance = this.refDistance;
  57805. serializationObject.distanceModel = this.distanceModel;
  57806. serializationObject.isDirectional = this._isDirectional;
  57807. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  57808. serializationObject.coneInnerAngle = this._coneInnerAngle;
  57809. serializationObject.coneOuterAngle = this._coneOuterAngle;
  57810. serializationObject.coneOuterGain = this._coneOuterGain;
  57811. }
  57812. return serializationObject;
  57813. };
  57814. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  57815. var soundName = parsedSound.name;
  57816. var soundUrl;
  57817. if (parsedSound.url) {
  57818. soundUrl = rootUrl + parsedSound.url;
  57819. }
  57820. else {
  57821. soundUrl = rootUrl + soundName;
  57822. }
  57823. var options = {
  57824. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  57825. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  57826. rolloffFactor: parsedSound.rolloffFactor,
  57827. refDistance: parsedSound.refDistance,
  57828. distanceModel: parsedSound.distanceModel,
  57829. playbackRate: parsedSound.playbackRate
  57830. };
  57831. var newSound;
  57832. if (!sourceSound) {
  57833. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  57834. scene._addPendingData(newSound);
  57835. }
  57836. else {
  57837. var setBufferAndRun = function () {
  57838. if (sourceSound._isReadyToPlay) {
  57839. newSound._audioBuffer = sourceSound.getAudioBuffer();
  57840. newSound._isReadyToPlay = true;
  57841. if (newSound.autoplay) {
  57842. newSound.play();
  57843. }
  57844. }
  57845. else {
  57846. window.setTimeout(setBufferAndRun, 300);
  57847. }
  57848. };
  57849. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  57850. setBufferAndRun();
  57851. }
  57852. if (parsedSound.position) {
  57853. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  57854. newSound.setPosition(soundPosition);
  57855. }
  57856. if (parsedSound.isDirectional) {
  57857. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  57858. if (parsedSound.localDirectionToMesh) {
  57859. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  57860. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  57861. }
  57862. }
  57863. if (parsedSound.connectedMeshId) {
  57864. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  57865. if (connectedMesh) {
  57866. newSound.attachToMesh(connectedMesh);
  57867. }
  57868. }
  57869. return newSound;
  57870. };
  57871. return Sound;
  57872. }());
  57873. BABYLON.Sound = Sound;
  57874. })(BABYLON || (BABYLON = {}));
  57875. //# sourceMappingURL=babylon.sound.js.map
  57876. var BABYLON;
  57877. (function (BABYLON) {
  57878. var SoundTrack = /** @class */ (function () {
  57879. function SoundTrack(scene, options) {
  57880. this.id = -1;
  57881. this._isMainTrack = false;
  57882. this._isInitialized = false;
  57883. this._scene = scene;
  57884. this.soundCollection = new Array();
  57885. this._options = options;
  57886. if (!this._isMainTrack) {
  57887. this._scene.soundTracks.push(this);
  57888. this.id = this._scene.soundTracks.length - 1;
  57889. }
  57890. }
  57891. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  57892. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  57893. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  57894. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  57895. if (this._options) {
  57896. if (this._options.volume) {
  57897. this._outputAudioNode.gain.value = this._options.volume;
  57898. }
  57899. if (this._options.mainTrack) {
  57900. this._isMainTrack = this._options.mainTrack;
  57901. }
  57902. }
  57903. this._isInitialized = true;
  57904. }
  57905. };
  57906. SoundTrack.prototype.dispose = function () {
  57907. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  57908. if (this._connectedAnalyser) {
  57909. this._connectedAnalyser.stopDebugCanvas();
  57910. }
  57911. while (this.soundCollection.length) {
  57912. this.soundCollection[0].dispose();
  57913. }
  57914. if (this._outputAudioNode) {
  57915. this._outputAudioNode.disconnect();
  57916. }
  57917. this._outputAudioNode = null;
  57918. }
  57919. };
  57920. SoundTrack.prototype.AddSound = function (sound) {
  57921. if (!this._isInitialized) {
  57922. this._initializeSoundTrackAudioGraph();
  57923. }
  57924. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  57925. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  57926. }
  57927. if (sound.soundTrackId) {
  57928. if (sound.soundTrackId === -1) {
  57929. this._scene.mainSoundTrack.RemoveSound(sound);
  57930. }
  57931. else {
  57932. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  57933. }
  57934. }
  57935. this.soundCollection.push(sound);
  57936. sound.soundTrackId = this.id;
  57937. };
  57938. SoundTrack.prototype.RemoveSound = function (sound) {
  57939. var index = this.soundCollection.indexOf(sound);
  57940. if (index !== -1) {
  57941. this.soundCollection.splice(index, 1);
  57942. }
  57943. };
  57944. SoundTrack.prototype.setVolume = function (newVolume) {
  57945. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  57946. this._outputAudioNode.gain.value = newVolume;
  57947. }
  57948. };
  57949. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  57950. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  57951. for (var i = 0; i < this.soundCollection.length; i++) {
  57952. this.soundCollection[i].switchPanningModelToHRTF();
  57953. }
  57954. }
  57955. };
  57956. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  57957. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  57958. for (var i = 0; i < this.soundCollection.length; i++) {
  57959. this.soundCollection[i].switchPanningModelToEqualPower();
  57960. }
  57961. }
  57962. };
  57963. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  57964. if (this._connectedAnalyser) {
  57965. this._connectedAnalyser.stopDebugCanvas();
  57966. }
  57967. this._connectedAnalyser = analyser;
  57968. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  57969. this._outputAudioNode.disconnect();
  57970. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  57971. }
  57972. };
  57973. return SoundTrack;
  57974. }());
  57975. BABYLON.SoundTrack = SoundTrack;
  57976. })(BABYLON || (BABYLON = {}));
  57977. //# sourceMappingURL=babylon.soundtrack.js.map
  57978. var BABYLON;
  57979. (function (BABYLON) {
  57980. var Analyser = /** @class */ (function () {
  57981. function Analyser(scene) {
  57982. this.SMOOTHING = 0.75;
  57983. this.FFT_SIZE = 512;
  57984. this.BARGRAPHAMPLITUDE = 256;
  57985. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  57986. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  57987. this._scene = scene;
  57988. this._audioEngine = BABYLON.Engine.audioEngine;
  57989. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  57990. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  57991. this._webAudioAnalyser.minDecibels = -140;
  57992. this._webAudioAnalyser.maxDecibels = 0;
  57993. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  57994. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  57995. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  57996. }
  57997. }
  57998. Analyser.prototype.getFrequencyBinCount = function () {
  57999. if (this._audioEngine.canUseWebAudio) {
  58000. return this._webAudioAnalyser.frequencyBinCount;
  58001. }
  58002. else {
  58003. return 0;
  58004. }
  58005. };
  58006. Analyser.prototype.getByteFrequencyData = function () {
  58007. if (this._audioEngine.canUseWebAudio) {
  58008. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  58009. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  58010. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  58011. }
  58012. return this._byteFreqs;
  58013. };
  58014. Analyser.prototype.getByteTimeDomainData = function () {
  58015. if (this._audioEngine.canUseWebAudio) {
  58016. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  58017. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  58018. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  58019. }
  58020. return this._byteTime;
  58021. };
  58022. Analyser.prototype.getFloatFrequencyData = function () {
  58023. if (this._audioEngine.canUseWebAudio) {
  58024. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  58025. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  58026. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  58027. }
  58028. return this._floatFreqs;
  58029. };
  58030. Analyser.prototype.drawDebugCanvas = function () {
  58031. var _this = this;
  58032. if (this._audioEngine.canUseWebAudio) {
  58033. if (!this._debugCanvas) {
  58034. this._debugCanvas = document.createElement("canvas");
  58035. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  58036. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  58037. this._debugCanvas.style.position = "absolute";
  58038. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  58039. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  58040. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  58041. document.body.appendChild(this._debugCanvas);
  58042. this._registerFunc = function () {
  58043. _this.drawDebugCanvas();
  58044. };
  58045. this._scene.registerBeforeRender(this._registerFunc);
  58046. }
  58047. if (this._registerFunc && this._debugCanvasContext) {
  58048. var workingArray = this.getByteFrequencyData();
  58049. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  58050. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  58051. // Draw the frequency domain chart.
  58052. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  58053. var value = workingArray[i];
  58054. var percent = value / this.BARGRAPHAMPLITUDE;
  58055. var height = this.DEBUGCANVASSIZE.height * percent;
  58056. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  58057. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  58058. var hue = i / this.getFrequencyBinCount() * 360;
  58059. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  58060. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  58061. }
  58062. }
  58063. }
  58064. };
  58065. Analyser.prototype.stopDebugCanvas = function () {
  58066. if (this._debugCanvas) {
  58067. if (this._registerFunc) {
  58068. this._scene.unregisterBeforeRender(this._registerFunc);
  58069. this._registerFunc = null;
  58070. }
  58071. document.body.removeChild(this._debugCanvas);
  58072. this._debugCanvas = null;
  58073. this._debugCanvasContext = null;
  58074. }
  58075. };
  58076. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  58077. if (this._audioEngine.canUseWebAudio) {
  58078. inputAudioNode.connect(this._webAudioAnalyser);
  58079. this._webAudioAnalyser.connect(outputAudioNode);
  58080. }
  58081. };
  58082. Analyser.prototype.dispose = function () {
  58083. if (this._audioEngine.canUseWebAudio) {
  58084. this._webAudioAnalyser.disconnect();
  58085. }
  58086. };
  58087. return Analyser;
  58088. }());
  58089. BABYLON.Analyser = Analyser;
  58090. })(BABYLON || (BABYLON = {}));
  58091. //# sourceMappingURL=babylon.analyser.js.map
  58092. var BABYLON;
  58093. (function (BABYLON) {
  58094. var CubeTexture = /** @class */ (function (_super) {
  58095. __extends(CubeTexture, _super);
  58096. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension) {
  58097. if (extensions === void 0) { extensions = null; }
  58098. if (noMipmap === void 0) { noMipmap = false; }
  58099. if (files === void 0) { files = null; }
  58100. if (onLoad === void 0) { onLoad = null; }
  58101. if (onError === void 0) { onError = null; }
  58102. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  58103. if (prefiltered === void 0) { prefiltered = false; }
  58104. if (forcedExtension === void 0) { forcedExtension = null; }
  58105. var _this = _super.call(this, scene) || this;
  58106. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  58107. /**
  58108. * Gets or sets the center of the bounding box associated with the cube texture
  58109. * It must define where the camera used to render the texture was set
  58110. */
  58111. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  58112. _this.name = rootUrl;
  58113. _this.url = rootUrl;
  58114. _this._noMipmap = noMipmap;
  58115. _this.hasAlpha = false;
  58116. _this._format = format;
  58117. _this._prefiltered = prefiltered;
  58118. _this.isCube = true;
  58119. _this._textureMatrix = BABYLON.Matrix.Identity();
  58120. if (prefiltered) {
  58121. _this.gammaSpace = false;
  58122. }
  58123. if (!rootUrl && !files) {
  58124. return _this;
  58125. }
  58126. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  58127. var lastDot = rootUrl.lastIndexOf(".");
  58128. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  58129. var isDDS = (extension === ".dds");
  58130. if (!files) {
  58131. if (!isDDS && !extensions) {
  58132. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  58133. }
  58134. files = [];
  58135. if (extensions) {
  58136. for (var index = 0; index < extensions.length; index++) {
  58137. files.push(rootUrl + extensions[index]);
  58138. }
  58139. }
  58140. }
  58141. _this._files = files;
  58142. if (!_this._texture) {
  58143. if (!scene.useDelayedTextureLoading) {
  58144. if (prefiltered) {
  58145. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension);
  58146. }
  58147. else {
  58148. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  58149. }
  58150. }
  58151. else {
  58152. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  58153. }
  58154. }
  58155. else if (onLoad) {
  58156. if (_this._texture.isReady) {
  58157. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  58158. }
  58159. else {
  58160. _this._texture.onLoadedObservable.add(onLoad);
  58161. }
  58162. }
  58163. return _this;
  58164. }
  58165. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  58166. get: function () {
  58167. return this._boundingBoxSize;
  58168. },
  58169. /**
  58170. * Gets or sets the size of the bounding box associated with the cube texture
  58171. * When defined, the cubemap will switch to local mode
  58172. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  58173. * @example https://www.babylonjs-playground.com/#RNASML
  58174. */
  58175. set: function (value) {
  58176. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  58177. return;
  58178. }
  58179. this._boundingBoxSize = value;
  58180. var scene = this.getScene();
  58181. if (scene) {
  58182. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  58183. }
  58184. },
  58185. enumerable: true,
  58186. configurable: true
  58187. });
  58188. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  58189. var rootUrlKey = "";
  58190. files.forEach(function (url) { return rootUrlKey += url; });
  58191. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  58192. };
  58193. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension) {
  58194. if (forcedExtension === void 0) { forcedExtension = null; }
  58195. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension);
  58196. };
  58197. // Methods
  58198. CubeTexture.prototype.delayLoad = function () {
  58199. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  58200. return;
  58201. }
  58202. var scene = this.getScene();
  58203. if (!scene) {
  58204. return;
  58205. }
  58206. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  58207. this._texture = this._getFromCache(this.url, this._noMipmap);
  58208. if (!this._texture) {
  58209. if (this._prefiltered) {
  58210. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format);
  58211. }
  58212. else {
  58213. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  58214. }
  58215. }
  58216. };
  58217. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  58218. return this._textureMatrix;
  58219. };
  58220. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  58221. this._textureMatrix = value;
  58222. };
  58223. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  58224. var texture = BABYLON.SerializationHelper.Parse(function () {
  58225. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  58226. }, parsedTexture, scene);
  58227. // Local Cubemaps
  58228. if (parsedTexture.boundingBoxPosition) {
  58229. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  58230. }
  58231. if (parsedTexture.boundingBoxSize) {
  58232. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  58233. }
  58234. // Animations
  58235. if (parsedTexture.animations) {
  58236. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  58237. var parsedAnimation = parsedTexture.animations[animationIndex];
  58238. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  58239. }
  58240. }
  58241. return texture;
  58242. };
  58243. CubeTexture.prototype.clone = function () {
  58244. var _this = this;
  58245. return BABYLON.SerializationHelper.Clone(function () {
  58246. var scene = _this.getScene();
  58247. if (!scene) {
  58248. return _this;
  58249. }
  58250. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  58251. }, this);
  58252. };
  58253. return CubeTexture;
  58254. }(BABYLON.BaseTexture));
  58255. BABYLON.CubeTexture = CubeTexture;
  58256. })(BABYLON || (BABYLON = {}));
  58257. //# sourceMappingURL=babylon.cubeTexture.js.map
  58258. var BABYLON;
  58259. (function (BABYLON) {
  58260. var RenderTargetTexture = /** @class */ (function (_super) {
  58261. __extends(RenderTargetTexture, _super);
  58262. /**
  58263. * Instantiate a render target texture. This is mainly to render of screen the scene to for instance apply post processse
  58264. * or used a shadow, depth texture...
  58265. * @param name The friendly name of the texture
  58266. * @param size The size of the RTT (number if square, or {with: number, height:number} or {ratio:} to define a ratio from the main scene)
  58267. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  58268. * @param generateMipMaps True if mip maps need to be generated after render.
  58269. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  58270. * @param type The type of the buffer in the RTT (int, half float, float...)
  58271. * @param isCube True if a cube texture needs to be created
  58272. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  58273. * @param generateDepthBuffer True to generate a depth buffer
  58274. * @param generateStencilBuffer True to generate a stencil buffer
  58275. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  58276. */
  58277. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  58278. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  58279. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  58280. if (isCube === void 0) { isCube = false; }
  58281. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  58282. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  58283. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  58284. if (isMulti === void 0) { isMulti = false; }
  58285. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  58286. _this.isCube = isCube;
  58287. /**
  58288. * Use this list to define the list of mesh you want to render.
  58289. */
  58290. _this.renderList = new Array();
  58291. _this.renderParticles = true;
  58292. _this.renderSprites = false;
  58293. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  58294. _this.ignoreCameraViewport = false;
  58295. // Events
  58296. /**
  58297. * An event triggered when the texture is unbind.
  58298. * @type {BABYLON.Observable}
  58299. */
  58300. _this.onBeforeBindObservable = new BABYLON.Observable();
  58301. /**
  58302. * An event triggered when the texture is unbind.
  58303. * @type {BABYLON.Observable}
  58304. */
  58305. _this.onAfterUnbindObservable = new BABYLON.Observable();
  58306. /**
  58307. * An event triggered before rendering the texture
  58308. * @type {BABYLON.Observable}
  58309. */
  58310. _this.onBeforeRenderObservable = new BABYLON.Observable();
  58311. /**
  58312. * An event triggered after rendering the texture
  58313. * @type {BABYLON.Observable}
  58314. */
  58315. _this.onAfterRenderObservable = new BABYLON.Observable();
  58316. /**
  58317. * An event triggered after the texture clear
  58318. * @type {BABYLON.Observable}
  58319. */
  58320. _this.onClearObservable = new BABYLON.Observable();
  58321. _this._currentRefreshId = -1;
  58322. _this._refreshRate = 1;
  58323. _this._samples = 1;
  58324. /**
  58325. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  58326. * It must define where the camera used to render the texture is set
  58327. */
  58328. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  58329. scene = _this.getScene();
  58330. if (!scene) {
  58331. return _this;
  58332. }
  58333. _this._engine = scene.getEngine();
  58334. _this.name = name;
  58335. _this.isRenderTarget = true;
  58336. _this._initialSizeParameter = size;
  58337. _this._processSizeParameter(size);
  58338. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  58339. });
  58340. _this._generateMipMaps = generateMipMaps ? true : false;
  58341. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  58342. // Rendering groups
  58343. _this._renderingManager = new BABYLON.RenderingManager(scene);
  58344. if (isMulti) {
  58345. return _this;
  58346. }
  58347. _this._renderTargetOptions = {
  58348. generateMipMaps: generateMipMaps,
  58349. type: type,
  58350. samplingMode: samplingMode,
  58351. generateDepthBuffer: generateDepthBuffer,
  58352. generateStencilBuffer: generateStencilBuffer
  58353. };
  58354. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  58355. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58356. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58357. }
  58358. if (isCube) {
  58359. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  58360. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  58361. _this._textureMatrix = BABYLON.Matrix.Identity();
  58362. }
  58363. else {
  58364. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  58365. }
  58366. return _this;
  58367. }
  58368. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  58369. get: function () {
  58370. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  58371. },
  58372. enumerable: true,
  58373. configurable: true
  58374. });
  58375. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  58376. get: function () {
  58377. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  58378. },
  58379. enumerable: true,
  58380. configurable: true
  58381. });
  58382. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  58383. get: function () {
  58384. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  58385. },
  58386. enumerable: true,
  58387. configurable: true
  58388. });
  58389. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  58390. set: function (callback) {
  58391. if (this._onAfterUnbindObserver) {
  58392. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  58393. }
  58394. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  58395. },
  58396. enumerable: true,
  58397. configurable: true
  58398. });
  58399. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  58400. set: function (callback) {
  58401. if (this._onBeforeRenderObserver) {
  58402. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  58403. }
  58404. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  58405. },
  58406. enumerable: true,
  58407. configurable: true
  58408. });
  58409. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  58410. set: function (callback) {
  58411. if (this._onAfterRenderObserver) {
  58412. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  58413. }
  58414. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  58415. },
  58416. enumerable: true,
  58417. configurable: true
  58418. });
  58419. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  58420. set: function (callback) {
  58421. if (this._onClearObserver) {
  58422. this.onClearObservable.remove(this._onClearObserver);
  58423. }
  58424. this._onClearObserver = this.onClearObservable.add(callback);
  58425. },
  58426. enumerable: true,
  58427. configurable: true
  58428. });
  58429. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  58430. get: function () {
  58431. return this._renderTargetOptions;
  58432. },
  58433. enumerable: true,
  58434. configurable: true
  58435. });
  58436. RenderTargetTexture.prototype._onRatioRescale = function () {
  58437. if (this._sizeRatio) {
  58438. this.resize(this._initialSizeParameter);
  58439. }
  58440. };
  58441. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  58442. get: function () {
  58443. return this._boundingBoxSize;
  58444. },
  58445. /**
  58446. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  58447. * When defined, the cubemap will switch to local mode
  58448. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  58449. * @example https://www.babylonjs-playground.com/#RNASML
  58450. */
  58451. set: function (value) {
  58452. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  58453. return;
  58454. }
  58455. this._boundingBoxSize = value;
  58456. var scene = this.getScene();
  58457. if (scene) {
  58458. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  58459. }
  58460. },
  58461. enumerable: true,
  58462. configurable: true
  58463. });
  58464. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  58465. if (size.ratio) {
  58466. this._sizeRatio = size.ratio;
  58467. this._size = {
  58468. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  58469. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  58470. };
  58471. }
  58472. else {
  58473. this._size = size;
  58474. }
  58475. };
  58476. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  58477. get: function () {
  58478. return this._samples;
  58479. },
  58480. set: function (value) {
  58481. if (this._samples === value) {
  58482. return;
  58483. }
  58484. var scene = this.getScene();
  58485. if (!scene) {
  58486. return;
  58487. }
  58488. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  58489. },
  58490. enumerable: true,
  58491. configurable: true
  58492. });
  58493. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  58494. this._currentRefreshId = -1;
  58495. };
  58496. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  58497. get: function () {
  58498. return this._refreshRate;
  58499. },
  58500. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  58501. set: function (value) {
  58502. this._refreshRate = value;
  58503. this.resetRefreshCounter();
  58504. },
  58505. enumerable: true,
  58506. configurable: true
  58507. });
  58508. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  58509. if (!this._postProcessManager) {
  58510. var scene = this.getScene();
  58511. if (!scene) {
  58512. return;
  58513. }
  58514. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  58515. this._postProcesses = new Array();
  58516. }
  58517. this._postProcesses.push(postProcess);
  58518. this._postProcesses[0].autoClear = false;
  58519. };
  58520. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  58521. if (!this._postProcesses) {
  58522. return;
  58523. }
  58524. if (dispose) {
  58525. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  58526. var postProcess = _a[_i];
  58527. postProcess.dispose();
  58528. }
  58529. }
  58530. this._postProcesses = [];
  58531. };
  58532. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  58533. if (!this._postProcesses) {
  58534. return;
  58535. }
  58536. var index = this._postProcesses.indexOf(postProcess);
  58537. if (index === -1) {
  58538. return;
  58539. }
  58540. this._postProcesses.splice(index, 1);
  58541. if (this._postProcesses.length > 0) {
  58542. this._postProcesses[0].autoClear = false;
  58543. }
  58544. };
  58545. RenderTargetTexture.prototype._shouldRender = function () {
  58546. if (this._currentRefreshId === -1) {
  58547. this._currentRefreshId = 1;
  58548. return true;
  58549. }
  58550. if (this.refreshRate === this._currentRefreshId) {
  58551. this._currentRefreshId = 1;
  58552. return true;
  58553. }
  58554. this._currentRefreshId++;
  58555. return false;
  58556. };
  58557. RenderTargetTexture.prototype.getRenderSize = function () {
  58558. if (this._size.width) {
  58559. return this._size.width;
  58560. }
  58561. return this._size;
  58562. };
  58563. RenderTargetTexture.prototype.getRenderWidth = function () {
  58564. if (this._size.width) {
  58565. return this._size.width;
  58566. }
  58567. return this._size;
  58568. };
  58569. RenderTargetTexture.prototype.getRenderHeight = function () {
  58570. if (this._size.width) {
  58571. return this._size.height;
  58572. }
  58573. return this._size;
  58574. };
  58575. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  58576. get: function () {
  58577. return true;
  58578. },
  58579. enumerable: true,
  58580. configurable: true
  58581. });
  58582. RenderTargetTexture.prototype.scale = function (ratio) {
  58583. var newSize = this.getRenderSize() * ratio;
  58584. this.resize(newSize);
  58585. };
  58586. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  58587. if (this.isCube) {
  58588. return this._textureMatrix;
  58589. }
  58590. return _super.prototype.getReflectionTextureMatrix.call(this);
  58591. };
  58592. RenderTargetTexture.prototype.resize = function (size) {
  58593. this.releaseInternalTexture();
  58594. var scene = this.getScene();
  58595. if (!scene) {
  58596. return;
  58597. }
  58598. this._processSizeParameter(size);
  58599. if (this.isCube) {
  58600. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  58601. }
  58602. else {
  58603. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  58604. }
  58605. };
  58606. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  58607. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  58608. if (dumpForDebug === void 0) { dumpForDebug = false; }
  58609. var scene = this.getScene();
  58610. if (!scene) {
  58611. return;
  58612. }
  58613. var engine = scene.getEngine();
  58614. if (this.useCameraPostProcesses !== undefined) {
  58615. useCameraPostProcess = this.useCameraPostProcesses;
  58616. }
  58617. if (this._waitingRenderList) {
  58618. this.renderList = [];
  58619. for (var index = 0; index < this._waitingRenderList.length; index++) {
  58620. var id = this._waitingRenderList[index];
  58621. var mesh_1 = scene.getMeshByID(id);
  58622. if (mesh_1) {
  58623. this.renderList.push(mesh_1);
  58624. }
  58625. }
  58626. delete this._waitingRenderList;
  58627. }
  58628. // Is predicate defined?
  58629. if (this.renderListPredicate) {
  58630. if (this.renderList) {
  58631. this.renderList.splice(0); // Clear previous renderList
  58632. }
  58633. else {
  58634. this.renderList = [];
  58635. }
  58636. var scene = this.getScene();
  58637. if (!scene) {
  58638. return;
  58639. }
  58640. var sceneMeshes = scene.meshes;
  58641. for (var index = 0; index < sceneMeshes.length; index++) {
  58642. var mesh = sceneMeshes[index];
  58643. if (this.renderListPredicate(mesh)) {
  58644. this.renderList.push(mesh);
  58645. }
  58646. }
  58647. }
  58648. this.onBeforeBindObservable.notifyObservers(this);
  58649. // Set custom projection.
  58650. // Needs to be before binding to prevent changing the aspect ratio.
  58651. var camera;
  58652. if (this.activeCamera) {
  58653. camera = this.activeCamera;
  58654. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  58655. if (this.activeCamera !== scene.activeCamera) {
  58656. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  58657. }
  58658. }
  58659. else {
  58660. camera = scene.activeCamera;
  58661. if (camera) {
  58662. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  58663. }
  58664. }
  58665. // Prepare renderingManager
  58666. this._renderingManager.reset();
  58667. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  58668. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  58669. var sceneRenderId = scene.getRenderId();
  58670. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  58671. var mesh = currentRenderList[meshIndex];
  58672. if (mesh) {
  58673. if (!mesh.isReady(this.refreshRate === 0)) {
  58674. this.resetRefreshCounter();
  58675. continue;
  58676. }
  58677. mesh._preActivateForIntermediateRendering(sceneRenderId);
  58678. var isMasked = void 0;
  58679. if (!this.renderList && camera) {
  58680. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  58681. }
  58682. else {
  58683. isMasked = false;
  58684. }
  58685. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  58686. mesh._activate(sceneRenderId);
  58687. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  58688. var subMesh = mesh.subMeshes[subIndex];
  58689. scene._activeIndices.addCount(subMesh.indexCount, false);
  58690. this._renderingManager.dispatch(subMesh, mesh);
  58691. }
  58692. }
  58693. }
  58694. }
  58695. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  58696. var particleSystem = scene.particleSystems[particleIndex];
  58697. var emitter = particleSystem.emitter;
  58698. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  58699. continue;
  58700. }
  58701. if (currentRenderList.indexOf(emitter) >= 0) {
  58702. this._renderingManager.dispatchParticles(particleSystem);
  58703. }
  58704. }
  58705. if (this.isCube) {
  58706. for (var face = 0; face < 6; face++) {
  58707. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  58708. scene.incrementRenderId();
  58709. scene.resetCachedMaterial();
  58710. }
  58711. }
  58712. else {
  58713. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  58714. }
  58715. this.onAfterUnbindObservable.notifyObservers(this);
  58716. if (scene.activeCamera) {
  58717. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  58718. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  58719. }
  58720. engine.setViewport(scene.activeCamera.viewport);
  58721. }
  58722. scene.resetCachedMaterial();
  58723. };
  58724. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  58725. var minimum = 128;
  58726. var x = renderDimension * scale;
  58727. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  58728. // Ensure we don't exceed the render dimension (while staying POT)
  58729. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  58730. };
  58731. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  58732. var _this = this;
  58733. if (!this._texture) {
  58734. return;
  58735. }
  58736. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  58737. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  58738. });
  58739. };
  58740. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  58741. var scene = this.getScene();
  58742. if (!scene) {
  58743. return;
  58744. }
  58745. var engine = scene.getEngine();
  58746. if (!this._texture) {
  58747. return;
  58748. }
  58749. // Bind
  58750. if (this._postProcessManager) {
  58751. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  58752. }
  58753. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  58754. if (this._texture) {
  58755. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  58756. }
  58757. }
  58758. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  58759. // Clear
  58760. if (this.onClearObservable.hasObservers()) {
  58761. this.onClearObservable.notifyObservers(engine);
  58762. }
  58763. else {
  58764. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  58765. }
  58766. if (!this._doNotChangeAspectRatio) {
  58767. scene.updateTransformMatrix(true);
  58768. }
  58769. // Render
  58770. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  58771. if (this._postProcessManager) {
  58772. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  58773. }
  58774. else if (useCameraPostProcess) {
  58775. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  58776. }
  58777. if (!this._doNotChangeAspectRatio) {
  58778. scene.updateTransformMatrix(true);
  58779. }
  58780. // Dump ?
  58781. if (dumpForDebug) {
  58782. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  58783. }
  58784. // Unbind
  58785. if (!this.isCube || faceIndex === 5) {
  58786. if (this.isCube) {
  58787. if (faceIndex === 5) {
  58788. engine.generateMipMapsForCubemap(this._texture);
  58789. }
  58790. }
  58791. this.unbindFrameBuffer(engine, faceIndex);
  58792. }
  58793. else {
  58794. this.onAfterRenderObservable.notifyObservers(faceIndex);
  58795. }
  58796. };
  58797. /**
  58798. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  58799. * This allowed control for front to back rendering or reversly depending of the special needs.
  58800. *
  58801. * @param renderingGroupId The rendering group id corresponding to its index
  58802. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  58803. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  58804. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  58805. */
  58806. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  58807. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  58808. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  58809. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  58810. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  58811. };
  58812. /**
  58813. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  58814. *
  58815. * @param renderingGroupId The rendering group id corresponding to its index
  58816. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  58817. */
  58818. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  58819. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  58820. };
  58821. RenderTargetTexture.prototype.clone = function () {
  58822. var textureSize = this.getSize();
  58823. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._renderTargetOptions.generateMipMaps, this._doNotChangeAspectRatio, this._renderTargetOptions.type, this.isCube, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer, this._renderTargetOptions.generateStencilBuffer);
  58824. // Base texture
  58825. newTexture.hasAlpha = this.hasAlpha;
  58826. newTexture.level = this.level;
  58827. // RenderTarget Texture
  58828. newTexture.coordinatesMode = this.coordinatesMode;
  58829. if (this.renderList) {
  58830. newTexture.renderList = this.renderList.slice(0);
  58831. }
  58832. return newTexture;
  58833. };
  58834. RenderTargetTexture.prototype.serialize = function () {
  58835. if (!this.name) {
  58836. return null;
  58837. }
  58838. var serializationObject = _super.prototype.serialize.call(this);
  58839. serializationObject.renderTargetSize = this.getRenderSize();
  58840. serializationObject.renderList = [];
  58841. if (this.renderList) {
  58842. for (var index = 0; index < this.renderList.length; index++) {
  58843. serializationObject.renderList.push(this.renderList[index].id);
  58844. }
  58845. }
  58846. return serializationObject;
  58847. };
  58848. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  58849. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  58850. var objBuffer = this.getInternalTexture();
  58851. var scene = this.getScene();
  58852. if (objBuffer && scene) {
  58853. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  58854. }
  58855. };
  58856. RenderTargetTexture.prototype.dispose = function () {
  58857. if (this._postProcessManager) {
  58858. this._postProcessManager.dispose();
  58859. this._postProcessManager = null;
  58860. }
  58861. this.clearPostProcesses(true);
  58862. if (this._resizeObserver) {
  58863. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  58864. this._resizeObserver = null;
  58865. }
  58866. this.renderList = null;
  58867. // Remove from custom render targets
  58868. var scene = this.getScene();
  58869. if (!scene) {
  58870. return;
  58871. }
  58872. var index = scene.customRenderTargets.indexOf(this);
  58873. if (index >= 0) {
  58874. scene.customRenderTargets.splice(index, 1);
  58875. }
  58876. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  58877. var camera = _a[_i];
  58878. index = camera.customRenderTargets.indexOf(this);
  58879. if (index >= 0) {
  58880. camera.customRenderTargets.splice(index, 1);
  58881. }
  58882. }
  58883. _super.prototype.dispose.call(this);
  58884. };
  58885. RenderTargetTexture.prototype._rebuild = function () {
  58886. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  58887. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  58888. }
  58889. if (this._postProcessManager) {
  58890. this._postProcessManager._rebuild();
  58891. }
  58892. };
  58893. /**
  58894. * Clear the info related to rendering groups preventing retention point in material dispose.
  58895. */
  58896. RenderTargetTexture.prototype.freeRenderingGroups = function () {
  58897. if (this._renderingManager) {
  58898. this._renderingManager.freeRenderingGroups();
  58899. }
  58900. };
  58901. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  58902. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  58903. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  58904. return RenderTargetTexture;
  58905. }(BABYLON.Texture));
  58906. BABYLON.RenderTargetTexture = RenderTargetTexture;
  58907. })(BABYLON || (BABYLON = {}));
  58908. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  58909. var BABYLON;
  58910. (function (BABYLON) {
  58911. ;
  58912. var MultiRenderTarget = /** @class */ (function (_super) {
  58913. __extends(MultiRenderTarget, _super);
  58914. function MultiRenderTarget(name, size, count, scene, options) {
  58915. var _this = this;
  58916. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  58917. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  58918. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  58919. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  58920. _this._engine = scene.getEngine();
  58921. if (!_this.isSupported) {
  58922. _this.dispose();
  58923. return;
  58924. }
  58925. var types = [];
  58926. var samplingModes = [];
  58927. for (var i = 0; i < count; i++) {
  58928. if (options && options.types && options.types[i] !== undefined) {
  58929. types.push(options.types[i]);
  58930. }
  58931. else {
  58932. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  58933. }
  58934. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  58935. samplingModes.push(options.samplingModes[i]);
  58936. }
  58937. else {
  58938. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  58939. }
  58940. }
  58941. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  58942. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  58943. _this._size = size;
  58944. _this._multiRenderTargetOptions = {
  58945. samplingModes: samplingModes,
  58946. generateMipMaps: generateMipMaps,
  58947. generateDepthBuffer: generateDepthBuffer,
  58948. generateStencilBuffer: generateStencilBuffer,
  58949. generateDepthTexture: generateDepthTexture,
  58950. types: types,
  58951. textureCount: count
  58952. };
  58953. _this._createInternalTextures();
  58954. _this._createTextures();
  58955. return _this;
  58956. }
  58957. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  58958. get: function () {
  58959. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  58960. },
  58961. enumerable: true,
  58962. configurable: true
  58963. });
  58964. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  58965. get: function () {
  58966. return this._textures;
  58967. },
  58968. enumerable: true,
  58969. configurable: true
  58970. });
  58971. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  58972. get: function () {
  58973. return this._textures[this._textures.length - 1];
  58974. },
  58975. enumerable: true,
  58976. configurable: true
  58977. });
  58978. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  58979. set: function (wrap) {
  58980. if (this._textures) {
  58981. for (var i = 0; i < this._textures.length; i++) {
  58982. this._textures[i].wrapU = wrap;
  58983. }
  58984. }
  58985. },
  58986. enumerable: true,
  58987. configurable: true
  58988. });
  58989. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  58990. set: function (wrap) {
  58991. if (this._textures) {
  58992. for (var i = 0; i < this._textures.length; i++) {
  58993. this._textures[i].wrapV = wrap;
  58994. }
  58995. }
  58996. },
  58997. enumerable: true,
  58998. configurable: true
  58999. });
  59000. MultiRenderTarget.prototype._rebuild = function () {
  59001. this.releaseInternalTextures();
  59002. this._createInternalTextures();
  59003. for (var i = 0; i < this._internalTextures.length; i++) {
  59004. var texture = this._textures[i];
  59005. texture._texture = this._internalTextures[i];
  59006. }
  59007. // Keeps references to frame buffer and stencil/depth buffer
  59008. this._texture = this._internalTextures[0];
  59009. };
  59010. MultiRenderTarget.prototype._createInternalTextures = function () {
  59011. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  59012. };
  59013. MultiRenderTarget.prototype._createTextures = function () {
  59014. this._textures = [];
  59015. for (var i = 0; i < this._internalTextures.length; i++) {
  59016. var texture = new BABYLON.Texture(null, this.getScene());
  59017. texture._texture = this._internalTextures[i];
  59018. this._textures.push(texture);
  59019. }
  59020. // Keeps references to frame buffer and stencil/depth buffer
  59021. this._texture = this._internalTextures[0];
  59022. };
  59023. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  59024. get: function () {
  59025. return this._samples;
  59026. },
  59027. set: function (value) {
  59028. if (this._samples === value) {
  59029. return;
  59030. }
  59031. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  59032. },
  59033. enumerable: true,
  59034. configurable: true
  59035. });
  59036. MultiRenderTarget.prototype.resize = function (size) {
  59037. this.releaseInternalTextures();
  59038. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  59039. this._createInternalTextures();
  59040. };
  59041. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  59042. var _this = this;
  59043. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  59044. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  59045. });
  59046. };
  59047. MultiRenderTarget.prototype.dispose = function () {
  59048. this.releaseInternalTextures();
  59049. _super.prototype.dispose.call(this);
  59050. };
  59051. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  59052. if (!this._internalTextures) {
  59053. return;
  59054. }
  59055. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  59056. if (this._internalTextures[i] !== undefined) {
  59057. this._internalTextures[i].dispose();
  59058. this._internalTextures.splice(i, 1);
  59059. }
  59060. }
  59061. };
  59062. return MultiRenderTarget;
  59063. }(BABYLON.RenderTargetTexture));
  59064. BABYLON.MultiRenderTarget = MultiRenderTarget;
  59065. })(BABYLON || (BABYLON = {}));
  59066. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  59067. var BABYLON;
  59068. (function (BABYLON) {
  59069. var MirrorTexture = /** @class */ (function (_super) {
  59070. __extends(MirrorTexture, _super);
  59071. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  59072. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  59073. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  59074. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  59075. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  59076. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  59077. _this._transformMatrix = BABYLON.Matrix.Zero();
  59078. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  59079. _this._adaptiveBlurKernel = 0;
  59080. _this._blurKernelX = 0;
  59081. _this._blurKernelY = 0;
  59082. _this._blurRatio = 1.0;
  59083. _this.ignoreCameraViewport = true;
  59084. _this.onBeforeRenderObservable.add(function () {
  59085. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  59086. _this._savedViewMatrix = scene.getViewMatrix();
  59087. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  59088. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  59089. scene.clipPlane = _this.mirrorPlane;
  59090. scene.getEngine().cullBackFaces = false;
  59091. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  59092. });
  59093. _this.onAfterRenderObservable.add(function () {
  59094. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  59095. scene.getEngine().cullBackFaces = true;
  59096. scene._mirroredCameraPosition = null;
  59097. delete scene.clipPlane;
  59098. });
  59099. return _this;
  59100. }
  59101. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  59102. get: function () {
  59103. return this._blurRatio;
  59104. },
  59105. set: function (value) {
  59106. if (this._blurRatio === value) {
  59107. return;
  59108. }
  59109. this._blurRatio = value;
  59110. this._preparePostProcesses();
  59111. },
  59112. enumerable: true,
  59113. configurable: true
  59114. });
  59115. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  59116. set: function (value) {
  59117. this._adaptiveBlurKernel = value;
  59118. this._autoComputeBlurKernel();
  59119. },
  59120. enumerable: true,
  59121. configurable: true
  59122. });
  59123. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  59124. set: function (value) {
  59125. this.blurKernelX = value;
  59126. this.blurKernelY = value;
  59127. },
  59128. enumerable: true,
  59129. configurable: true
  59130. });
  59131. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  59132. get: function () {
  59133. return this._blurKernelX;
  59134. },
  59135. set: function (value) {
  59136. if (this._blurKernelX === value) {
  59137. return;
  59138. }
  59139. this._blurKernelX = value;
  59140. this._preparePostProcesses();
  59141. },
  59142. enumerable: true,
  59143. configurable: true
  59144. });
  59145. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  59146. get: function () {
  59147. return this._blurKernelY;
  59148. },
  59149. set: function (value) {
  59150. if (this._blurKernelY === value) {
  59151. return;
  59152. }
  59153. this._blurKernelY = value;
  59154. this._preparePostProcesses();
  59155. },
  59156. enumerable: true,
  59157. configurable: true
  59158. });
  59159. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  59160. var engine = this.getScene().getEngine();
  59161. var dw = this.getRenderWidth() / engine.getRenderWidth();
  59162. var dh = this.getRenderHeight() / engine.getRenderHeight();
  59163. this.blurKernelX = this._adaptiveBlurKernel * dw;
  59164. this.blurKernelY = this._adaptiveBlurKernel * dh;
  59165. };
  59166. MirrorTexture.prototype._onRatioRescale = function () {
  59167. if (this._sizeRatio) {
  59168. this.resize(this._initialSizeParameter);
  59169. if (!this._adaptiveBlurKernel) {
  59170. this._preparePostProcesses();
  59171. }
  59172. }
  59173. if (this._adaptiveBlurKernel) {
  59174. this._autoComputeBlurKernel();
  59175. }
  59176. };
  59177. MirrorTexture.prototype._preparePostProcesses = function () {
  59178. this.clearPostProcesses(true);
  59179. if (this._blurKernelX && this._blurKernelY) {
  59180. var engine = this.getScene().getEngine();
  59181. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  59182. this._blurX = new BABYLON.BlurPostProcess("horizontal blur", new BABYLON.Vector2(1.0, 0), this._blurKernelX, this._blurRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, textureType);
  59183. this._blurX.autoClear = false;
  59184. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  59185. this._blurX.inputTexture = this._texture;
  59186. }
  59187. else {
  59188. this._blurX.alwaysForcePOT = true;
  59189. }
  59190. this._blurY = new BABYLON.BlurPostProcess("vertical blur", new BABYLON.Vector2(0, 1.0), this._blurKernelY, this._blurRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, textureType);
  59191. this._blurY.autoClear = false;
  59192. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  59193. this.addPostProcess(this._blurX);
  59194. this.addPostProcess(this._blurY);
  59195. }
  59196. else {
  59197. if (this._blurY) {
  59198. this.removePostProcess(this._blurY);
  59199. this._blurY.dispose();
  59200. this._blurY = null;
  59201. }
  59202. if (this._blurX) {
  59203. this.removePostProcess(this._blurX);
  59204. this._blurX.dispose();
  59205. this._blurX = null;
  59206. }
  59207. }
  59208. };
  59209. MirrorTexture.prototype.clone = function () {
  59210. var scene = this.getScene();
  59211. if (!scene) {
  59212. return this;
  59213. }
  59214. var textureSize = this.getSize();
  59215. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  59216. // Base texture
  59217. newTexture.hasAlpha = this.hasAlpha;
  59218. newTexture.level = this.level;
  59219. // Mirror Texture
  59220. newTexture.mirrorPlane = this.mirrorPlane.clone();
  59221. if (this.renderList) {
  59222. newTexture.renderList = this.renderList.slice(0);
  59223. }
  59224. return newTexture;
  59225. };
  59226. MirrorTexture.prototype.serialize = function () {
  59227. if (!this.name) {
  59228. return null;
  59229. }
  59230. var serializationObject = _super.prototype.serialize.call(this);
  59231. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  59232. return serializationObject;
  59233. };
  59234. return MirrorTexture;
  59235. }(BABYLON.RenderTargetTexture));
  59236. BABYLON.MirrorTexture = MirrorTexture;
  59237. })(BABYLON || (BABYLON = {}));
  59238. //# sourceMappingURL=babylon.mirrorTexture.js.map
  59239. var BABYLON;
  59240. (function (BABYLON) {
  59241. /**
  59242. * Creates a refraction texture used by refraction channel of the standard material.
  59243. * @param name the texture name
  59244. * @param size size of the underlying texture
  59245. * @param scene root scene
  59246. */
  59247. var RefractionTexture = /** @class */ (function (_super) {
  59248. __extends(RefractionTexture, _super);
  59249. function RefractionTexture(name, size, scene, generateMipMaps) {
  59250. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  59251. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  59252. _this.depth = 2.0;
  59253. _this.onBeforeRenderObservable.add(function () {
  59254. scene.clipPlane = _this.refractionPlane;
  59255. });
  59256. _this.onAfterRenderObservable.add(function () {
  59257. delete scene.clipPlane;
  59258. });
  59259. return _this;
  59260. }
  59261. RefractionTexture.prototype.clone = function () {
  59262. var scene = this.getScene();
  59263. if (!scene) {
  59264. return this;
  59265. }
  59266. var textureSize = this.getSize();
  59267. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  59268. // Base texture
  59269. newTexture.hasAlpha = this.hasAlpha;
  59270. newTexture.level = this.level;
  59271. // Refraction Texture
  59272. newTexture.refractionPlane = this.refractionPlane.clone();
  59273. if (this.renderList) {
  59274. newTexture.renderList = this.renderList.slice(0);
  59275. }
  59276. newTexture.depth = this.depth;
  59277. return newTexture;
  59278. };
  59279. RefractionTexture.prototype.serialize = function () {
  59280. if (!this.name) {
  59281. return null;
  59282. }
  59283. var serializationObject = _super.prototype.serialize.call(this);
  59284. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  59285. serializationObject.depth = this.depth;
  59286. return serializationObject;
  59287. };
  59288. return RefractionTexture;
  59289. }(BABYLON.RenderTargetTexture));
  59290. BABYLON.RefractionTexture = RefractionTexture;
  59291. })(BABYLON || (BABYLON = {}));
  59292. //# sourceMappingURL=babylon.refractionTexture.js.map
  59293. var BABYLON;
  59294. (function (BABYLON) {
  59295. var DynamicTexture = /** @class */ (function (_super) {
  59296. __extends(DynamicTexture, _super);
  59297. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  59298. if (scene === void 0) { scene = null; }
  59299. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  59300. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  59301. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  59302. _this.name = name;
  59303. _this._engine = _this.getScene().getEngine();
  59304. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59305. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59306. _this._generateMipMaps = generateMipMaps;
  59307. if (options.getContext) {
  59308. _this._canvas = options;
  59309. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  59310. }
  59311. else {
  59312. _this._canvas = document.createElement("canvas");
  59313. if (options.width) {
  59314. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  59315. }
  59316. else {
  59317. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  59318. }
  59319. }
  59320. var textureSize = _this.getSize();
  59321. _this._canvas.width = textureSize.width;
  59322. _this._canvas.height = textureSize.height;
  59323. _this._context = _this._canvas.getContext("2d");
  59324. return _this;
  59325. }
  59326. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  59327. get: function () {
  59328. return true;
  59329. },
  59330. enumerable: true,
  59331. configurable: true
  59332. });
  59333. DynamicTexture.prototype._recreate = function (textureSize) {
  59334. this._canvas.width = textureSize.width;
  59335. this._canvas.height = textureSize.height;
  59336. this.releaseInternalTexture();
  59337. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  59338. };
  59339. DynamicTexture.prototype.scale = function (ratio) {
  59340. var textureSize = this.getSize();
  59341. textureSize.width *= ratio;
  59342. textureSize.height *= ratio;
  59343. this._recreate(textureSize);
  59344. };
  59345. DynamicTexture.prototype.scaleTo = function (width, height) {
  59346. var textureSize = this.getSize();
  59347. textureSize.width = width;
  59348. textureSize.height = height;
  59349. this._recreate(textureSize);
  59350. };
  59351. DynamicTexture.prototype.getContext = function () {
  59352. return this._context;
  59353. };
  59354. DynamicTexture.prototype.clear = function () {
  59355. var size = this.getSize();
  59356. this._context.fillRect(0, 0, size.width, size.height);
  59357. };
  59358. DynamicTexture.prototype.update = function (invertY) {
  59359. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format || undefined);
  59360. };
  59361. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  59362. if (update === void 0) { update = true; }
  59363. var size = this.getSize();
  59364. if (clearColor) {
  59365. this._context.fillStyle = clearColor;
  59366. this._context.fillRect(0, 0, size.width, size.height);
  59367. }
  59368. this._context.font = font;
  59369. if (x === null || x === undefined) {
  59370. var textSize = this._context.measureText(text);
  59371. x = (size.width - textSize.width) / 2;
  59372. }
  59373. if (y === null || y === undefined) {
  59374. var fontSize = parseInt((font.replace(/\D/g, '')));
  59375. ;
  59376. y = (size.height / 2) + (fontSize / 3.65);
  59377. }
  59378. this._context.fillStyle = color;
  59379. this._context.fillText(text, x, y);
  59380. if (update) {
  59381. this.update(invertY);
  59382. }
  59383. };
  59384. DynamicTexture.prototype.clone = function () {
  59385. var scene = this.getScene();
  59386. if (!scene) {
  59387. return this;
  59388. }
  59389. var textureSize = this.getSize();
  59390. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  59391. // Base texture
  59392. newTexture.hasAlpha = this.hasAlpha;
  59393. newTexture.level = this.level;
  59394. // Dynamic Texture
  59395. newTexture.wrapU = this.wrapU;
  59396. newTexture.wrapV = this.wrapV;
  59397. return newTexture;
  59398. };
  59399. DynamicTexture.prototype._rebuild = function () {
  59400. this.update();
  59401. };
  59402. return DynamicTexture;
  59403. }(BABYLON.Texture));
  59404. BABYLON.DynamicTexture = DynamicTexture;
  59405. })(BABYLON || (BABYLON = {}));
  59406. //# sourceMappingURL=babylon.dynamicTexture.js.map
  59407. var BABYLON;
  59408. (function (BABYLON) {
  59409. var VideoTexture = /** @class */ (function (_super) {
  59410. __extends(VideoTexture, _super);
  59411. /**
  59412. * Creates a video texture.
  59413. * Sample : https://doc.babylonjs.com/how_to/video_texture
  59414. * @param {string | null} name optional name, will detect from video source, if not defined
  59415. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  59416. * @param {BABYLON.Scene} scene is obviously the current scene.
  59417. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  59418. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  59419. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  59420. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  59421. */
  59422. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  59423. if (generateMipMaps === void 0) { generateMipMaps = false; }
  59424. if (invertY === void 0) { invertY = false; }
  59425. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  59426. if (settings === void 0) { settings = {
  59427. autoPlay: true,
  59428. loop: true,
  59429. autoUpdateTexture: true,
  59430. }; }
  59431. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  59432. _this._createInternalTexture = function () {
  59433. if (_this._texture != null) {
  59434. return;
  59435. }
  59436. if (!_this._engine.needPOTTextures ||
  59437. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  59438. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  59439. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  59440. }
  59441. else {
  59442. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59443. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59444. _this._generateMipMaps = false;
  59445. }
  59446. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  59447. _this._texture.isReady = true;
  59448. _this._updateInternalTexture();
  59449. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  59450. _this.onLoadObservable.notifyObservers(_this);
  59451. }
  59452. };
  59453. _this.reset = function () {
  59454. if (_this._texture == null) {
  59455. return;
  59456. }
  59457. _this._texture.dispose();
  59458. _this._texture = null;
  59459. };
  59460. _this._updateInternalTexture = function (e) {
  59461. if (_this._texture == null || !_this._texture.isReady) {
  59462. return;
  59463. }
  59464. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  59465. return;
  59466. }
  59467. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  59468. };
  59469. _this._engine = _this.getScene().getEngine();
  59470. _this._generateMipMaps = generateMipMaps;
  59471. _this._samplingMode = samplingMode;
  59472. _this.autoUpdateTexture = settings.autoUpdateTexture;
  59473. _this.name = name || _this._getName(src);
  59474. _this.video = _this._getVideo(src);
  59475. if (settings.autoPlay !== undefined) {
  59476. _this.video.autoplay = settings.autoPlay;
  59477. }
  59478. if (settings.loop !== undefined) {
  59479. _this.video.loop = settings.loop;
  59480. }
  59481. _this.video.addEventListener("canplay", _this._createInternalTexture);
  59482. _this.video.addEventListener("paused", _this._updateInternalTexture);
  59483. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  59484. _this.video.addEventListener("emptied", _this.reset);
  59485. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  59486. _this._createInternalTexture();
  59487. }
  59488. return _this;
  59489. }
  59490. VideoTexture.prototype._getName = function (src) {
  59491. if (src instanceof HTMLVideoElement) {
  59492. return src.currentSrc;
  59493. }
  59494. if (typeof src === "object") {
  59495. return src.toString();
  59496. }
  59497. return src;
  59498. };
  59499. ;
  59500. VideoTexture.prototype._getVideo = function (src) {
  59501. if (src instanceof HTMLVideoElement) {
  59502. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  59503. return src;
  59504. }
  59505. var video = document.createElement("video");
  59506. if (typeof src === "string") {
  59507. BABYLON.Tools.SetCorsBehavior(src, video);
  59508. video.src = src;
  59509. }
  59510. else {
  59511. BABYLON.Tools.SetCorsBehavior(src[0], video);
  59512. src.forEach(function (url) {
  59513. var source = document.createElement("source");
  59514. source.src = url;
  59515. video.appendChild(source);
  59516. });
  59517. }
  59518. return video;
  59519. };
  59520. ;
  59521. /**
  59522. * Internal method to initiate `update`.
  59523. */
  59524. VideoTexture.prototype._rebuild = function () {
  59525. this.update();
  59526. };
  59527. /**
  59528. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  59529. */
  59530. VideoTexture.prototype.update = function () {
  59531. if (!this.autoUpdateTexture) {
  59532. // Expecting user to call `updateTexture` manually
  59533. return;
  59534. }
  59535. this.updateTexture(true);
  59536. };
  59537. /**
  59538. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  59539. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  59540. */
  59541. VideoTexture.prototype.updateTexture = function (isVisible) {
  59542. if (!isVisible) {
  59543. return;
  59544. }
  59545. if (this.video.paused) {
  59546. return;
  59547. }
  59548. this._updateInternalTexture();
  59549. };
  59550. /**
  59551. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  59552. * @param url New url.
  59553. */
  59554. VideoTexture.prototype.updateURL = function (url) {
  59555. this.video.src = url;
  59556. };
  59557. VideoTexture.prototype.dispose = function () {
  59558. _super.prototype.dispose.call(this);
  59559. this.video.removeEventListener("canplay", this._createInternalTexture);
  59560. this.video.removeEventListener("paused", this._updateInternalTexture);
  59561. this.video.removeEventListener("seeked", this._updateInternalTexture);
  59562. this.video.removeEventListener("emptied", this.reset);
  59563. this.video.pause();
  59564. };
  59565. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  59566. var video = document.createElement("video");
  59567. var constraintsDeviceId;
  59568. if (constraints && constraints.deviceId) {
  59569. constraintsDeviceId = {
  59570. exact: constraints.deviceId,
  59571. };
  59572. }
  59573. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  59574. if (navigator.mediaDevices) {
  59575. navigator.mediaDevices.getUserMedia({ video: constraints })
  59576. .then(function (stream) {
  59577. if (video.mozSrcObject !== undefined) {
  59578. // hack for Firefox < 19
  59579. video.mozSrcObject = stream;
  59580. }
  59581. else {
  59582. video.srcObject = stream;
  59583. }
  59584. var onPlaying = function () {
  59585. if (onReady) {
  59586. onReady(new VideoTexture("video", video, scene, true, true));
  59587. }
  59588. video.removeEventListener("playing", onPlaying);
  59589. };
  59590. video.addEventListener("playing", onPlaying);
  59591. video.play();
  59592. })
  59593. .catch(function (err) {
  59594. BABYLON.Tools.Error(err.name);
  59595. });
  59596. }
  59597. else {
  59598. navigator.getUserMedia =
  59599. navigator.getUserMedia ||
  59600. navigator.webkitGetUserMedia ||
  59601. navigator.mozGetUserMedia ||
  59602. navigator.msGetUserMedia;
  59603. if (navigator.getUserMedia) {
  59604. navigator.getUserMedia({
  59605. video: {
  59606. deviceId: constraintsDeviceId,
  59607. width: {
  59608. min: (constraints && constraints.minWidth) || 256,
  59609. max: (constraints && constraints.maxWidth) || 640,
  59610. },
  59611. height: {
  59612. min: (constraints && constraints.minHeight) || 256,
  59613. max: (constraints && constraints.maxHeight) || 480,
  59614. },
  59615. },
  59616. }, function (stream) {
  59617. if (video.mozSrcObject !== undefined) {
  59618. // hack for Firefox < 19
  59619. video.mozSrcObject = stream;
  59620. }
  59621. else {
  59622. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  59623. }
  59624. video.play();
  59625. if (onReady) {
  59626. onReady(new VideoTexture("video", video, scene, true, true));
  59627. }
  59628. }, function (e) {
  59629. BABYLON.Tools.Error(e.name);
  59630. });
  59631. }
  59632. }
  59633. };
  59634. return VideoTexture;
  59635. }(BABYLON.Texture));
  59636. BABYLON.VideoTexture = VideoTexture;
  59637. })(BABYLON || (BABYLON = {}));
  59638. //# sourceMappingURL=babylon.videoTexture.js.map
  59639. var BABYLON;
  59640. (function (BABYLON) {
  59641. var RawTexture = /** @class */ (function (_super) {
  59642. __extends(RawTexture, _super);
  59643. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  59644. if (generateMipMaps === void 0) { generateMipMaps = true; }
  59645. if (invertY === void 0) { invertY = false; }
  59646. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  59647. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  59648. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  59649. _this.format = format;
  59650. _this._engine = scene.getEngine();
  59651. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  59652. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59653. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59654. return _this;
  59655. }
  59656. RawTexture.prototype.update = function (data) {
  59657. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  59658. };
  59659. // Statics
  59660. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  59661. if (generateMipMaps === void 0) { generateMipMaps = true; }
  59662. if (invertY === void 0) { invertY = false; }
  59663. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  59664. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  59665. };
  59666. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  59667. if (generateMipMaps === void 0) { generateMipMaps = true; }
  59668. if (invertY === void 0) { invertY = false; }
  59669. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  59670. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  59671. };
  59672. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  59673. if (generateMipMaps === void 0) { generateMipMaps = true; }
  59674. if (invertY === void 0) { invertY = false; }
  59675. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  59676. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  59677. };
  59678. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  59679. if (generateMipMaps === void 0) { generateMipMaps = true; }
  59680. if (invertY === void 0) { invertY = false; }
  59681. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  59682. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  59683. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  59684. };
  59685. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  59686. if (generateMipMaps === void 0) { generateMipMaps = true; }
  59687. if (invertY === void 0) { invertY = false; }
  59688. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  59689. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  59690. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  59691. };
  59692. return RawTexture;
  59693. }(BABYLON.Texture));
  59694. BABYLON.RawTexture = RawTexture;
  59695. })(BABYLON || (BABYLON = {}));
  59696. //# sourceMappingURL=babylon.rawTexture.js.map
  59697. var BABYLON;
  59698. (function (BABYLON) {
  59699. /**
  59700. * PostProcess can be used to apply a shader to a texture after it has been rendered
  59701. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  59702. */
  59703. var PostProcess = /** @class */ (function () {
  59704. /**
  59705. * Creates a new instance of @see PostProcess
  59706. * @param name The name of the PostProcess.
  59707. * @param fragmentUrl The url of the fragment shader to be used.
  59708. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  59709. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  59710. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  59711. * @param camera The camera to apply the render pass to.
  59712. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  59713. * @param engine The engine which the post process will be applied. (default: current engine)
  59714. * @param reusable If the post process can be reused on the same frame. (default: false)
  59715. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  59716. * @param textureType Type of textures used when performing the post process. (default: 0)
  59717. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  59718. * @param indexParameters The index parameters to be used for babylons include syntax "#include<kernelBlurVaryingDeclaration>[0..varyingCount]". (default: undefined) See usage in babylon.blurPostProcess.ts and kernelBlur.vertex.fx
  59719. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  59720. */
  59721. function PostProcess(/** Name of the PostProcess. */ name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  59722. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  59723. if (defines === void 0) { defines = null; }
  59724. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  59725. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  59726. if (blockCompilation === void 0) { blockCompilation = false; }
  59727. this.name = name;
  59728. /**
  59729. * Width of the texture to apply the post process on
  59730. */
  59731. this.width = -1;
  59732. /**
  59733. * Height of the texture to apply the post process on
  59734. */
  59735. this.height = -1;
  59736. /**
  59737. * If the buffer needs to be cleared before applying the post process. (default: true)
  59738. * Should be set to false if shader will overwrite all previous pixels.
  59739. */
  59740. this.autoClear = true;
  59741. /**
  59742. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  59743. */
  59744. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  59745. /**
  59746. * Animations to be used for the post processing
  59747. */
  59748. this.animations = new Array();
  59749. /**
  59750. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  59751. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  59752. */
  59753. this.enablePixelPerfectMode = false;
  59754. /**
  59755. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  59756. */
  59757. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  59758. /**
  59759. * Force textures to be a power of two (default: false)
  59760. */
  59761. this.alwaysForcePOT = false;
  59762. /**
  59763. * Number of sample textures (default: 1)
  59764. */
  59765. this.samples = 1;
  59766. /**
  59767. * Modify the scale of the post process to be the same as the viewport (default: false)
  59768. */
  59769. this.adaptScaleToCurrentViewport = false;
  59770. this._reusable = false;
  59771. /**
  59772. * Smart array of input and output textures for the post process.
  59773. */
  59774. this._textures = new BABYLON.SmartArray(2);
  59775. /**
  59776. * The index in _textures that corresponds to the output texture.
  59777. */
  59778. this._currentRenderTextureInd = 0;
  59779. this._scaleRatio = new BABYLON.Vector2(1, 1);
  59780. this._texelSize = BABYLON.Vector2.Zero();
  59781. // Events
  59782. /**
  59783. * An event triggered when the postprocess is activated.
  59784. * @type {BABYLON.Observable}
  59785. */
  59786. this.onActivateObservable = new BABYLON.Observable();
  59787. /**
  59788. * An event triggered when the postprocess changes its size.
  59789. * @type {BABYLON.Observable}
  59790. */
  59791. this.onSizeChangedObservable = new BABYLON.Observable();
  59792. /**
  59793. * An event triggered when the postprocess applies its effect.
  59794. * @type {BABYLON.Observable}
  59795. */
  59796. this.onApplyObservable = new BABYLON.Observable();
  59797. /**
  59798. * An event triggered before rendering the postprocess
  59799. * @type {BABYLON.Observable}
  59800. */
  59801. this.onBeforeRenderObservable = new BABYLON.Observable();
  59802. /**
  59803. * An event triggered after rendering the postprocess
  59804. * @type {BABYLON.Observable}
  59805. */
  59806. this.onAfterRenderObservable = new BABYLON.Observable();
  59807. if (camera != null) {
  59808. this._camera = camera;
  59809. this._scene = camera.getScene();
  59810. camera.attachPostProcess(this);
  59811. this._engine = this._scene.getEngine();
  59812. this._scene.postProcesses.push(this);
  59813. }
  59814. else if (engine) {
  59815. this._engine = engine;
  59816. this._engine.postProcesses.push(this);
  59817. }
  59818. this._options = options;
  59819. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  59820. this._reusable = reusable || false;
  59821. this._textureType = textureType;
  59822. this._samplers = samplers || [];
  59823. this._samplers.push("textureSampler");
  59824. this._fragmentUrl = fragmentUrl;
  59825. this._vertexUrl = vertexUrl;
  59826. this._parameters = parameters || [];
  59827. this._parameters.push("scale");
  59828. this._indexParameters = indexParameters;
  59829. if (!blockCompilation) {
  59830. this.updateEffect(defines);
  59831. }
  59832. }
  59833. Object.defineProperty(PostProcess.prototype, "onActivate", {
  59834. /**
  59835. * A function that is added to the onActivateObservable
  59836. */
  59837. set: function (callback) {
  59838. if (this._onActivateObserver) {
  59839. this.onActivateObservable.remove(this._onActivateObserver);
  59840. }
  59841. if (callback) {
  59842. this._onActivateObserver = this.onActivateObservable.add(callback);
  59843. }
  59844. },
  59845. enumerable: true,
  59846. configurable: true
  59847. });
  59848. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  59849. /**
  59850. * A function that is added to the onSizeChangedObservable
  59851. */
  59852. set: function (callback) {
  59853. if (this._onSizeChangedObserver) {
  59854. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  59855. }
  59856. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  59857. },
  59858. enumerable: true,
  59859. configurable: true
  59860. });
  59861. Object.defineProperty(PostProcess.prototype, "onApply", {
  59862. /**
  59863. * A function that is added to the onApplyObservable
  59864. */
  59865. set: function (callback) {
  59866. if (this._onApplyObserver) {
  59867. this.onApplyObservable.remove(this._onApplyObserver);
  59868. }
  59869. this._onApplyObserver = this.onApplyObservable.add(callback);
  59870. },
  59871. enumerable: true,
  59872. configurable: true
  59873. });
  59874. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  59875. /**
  59876. * A function that is added to the onBeforeRenderObservable
  59877. */
  59878. set: function (callback) {
  59879. if (this._onBeforeRenderObserver) {
  59880. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  59881. }
  59882. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  59883. },
  59884. enumerable: true,
  59885. configurable: true
  59886. });
  59887. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  59888. /**
  59889. * A function that is added to the onAfterRenderObservable
  59890. */
  59891. set: function (callback) {
  59892. if (this._onAfterRenderObserver) {
  59893. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  59894. }
  59895. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  59896. },
  59897. enumerable: true,
  59898. configurable: true
  59899. });
  59900. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  59901. /**
  59902. * The input texture for this post process and the output texture of the previous post process. When added to a pipeline the previous post process will
  59903. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  59904. */
  59905. get: function () {
  59906. return this._textures.data[this._currentRenderTextureInd];
  59907. },
  59908. set: function (value) {
  59909. this._forcedOutputTexture = value;
  59910. },
  59911. enumerable: true,
  59912. configurable: true
  59913. });
  59914. /**
  59915. * Gets the camera which post process is applied to.
  59916. * @returns The camera the post process is applied to.
  59917. */
  59918. PostProcess.prototype.getCamera = function () {
  59919. return this._camera;
  59920. };
  59921. Object.defineProperty(PostProcess.prototype, "texelSize", {
  59922. /**
  59923. * Gets the texel size of the postprocess.
  59924. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  59925. */
  59926. get: function () {
  59927. if (this._shareOutputWithPostProcess) {
  59928. return this._shareOutputWithPostProcess.texelSize;
  59929. }
  59930. if (this._forcedOutputTexture) {
  59931. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  59932. }
  59933. return this._texelSize;
  59934. },
  59935. enumerable: true,
  59936. configurable: true
  59937. });
  59938. /**
  59939. * Gets the engine which this post process belongs to.
  59940. * @returns The engine the post process was enabled with.
  59941. */
  59942. PostProcess.prototype.getEngine = function () {
  59943. return this._engine;
  59944. };
  59945. /**
  59946. * The effect that is created when initializing the post process.
  59947. * @returns The created effect corrisponding the the postprocess.
  59948. */
  59949. PostProcess.prototype.getEffect = function () {
  59950. return this._effect;
  59951. };
  59952. /**
  59953. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  59954. * @param postProcess The post process to share the output with.
  59955. * @returns This post process.
  59956. */
  59957. PostProcess.prototype.shareOutputWith = function (postProcess) {
  59958. this._disposeTextures();
  59959. this._shareOutputWithPostProcess = postProcess;
  59960. return this;
  59961. };
  59962. /**
  59963. * Reverses the effect of calling shareOutputWith and returns the post process back to its original state.
  59964. * This should be called if the post process that shares output with this post process is disabled/disposed.
  59965. */
  59966. PostProcess.prototype.useOwnOutput = function () {
  59967. if (this._textures.length == 0) {
  59968. this._textures = new BABYLON.SmartArray(2);
  59969. }
  59970. this._shareOutputWithPostProcess = null;
  59971. };
  59972. /**
  59973. * Updates the effect with the current post process compile time values and recompiles the shader.
  59974. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  59975. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  59976. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  59977. * @param indexParameters The index parameters to be used for babylons include syntax "#include<kernelBlurVaryingDeclaration>[0..varyingCount]". (default: undefined) See usage in babylon.blurPostProcess.ts and kernelBlur.vertex.fx
  59978. * @param onCompiled Called when the shader has been compiled.
  59979. * @param onError Called if there is an error when compiling a shader.
  59980. */
  59981. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  59982. if (defines === void 0) { defines = null; }
  59983. if (uniforms === void 0) { uniforms = null; }
  59984. if (samplers === void 0) { samplers = null; }
  59985. this._effect = this._engine.createEffect({ vertex: this._vertexUrl, fragment: this._fragmentUrl }, ["position"], uniforms || this._parameters, samplers || this._samplers, defines !== null ? defines : "", undefined, onCompiled, onError, indexParameters || this._indexParameters);
  59986. };
  59987. /**
  59988. * The post process is reusable if it can be used multiple times within one frame.
  59989. * @returns If the post process is reusable
  59990. */
  59991. PostProcess.prototype.isReusable = function () {
  59992. return this._reusable;
  59993. };
  59994. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  59995. PostProcess.prototype.markTextureDirty = function () {
  59996. this.width = -1;
  59997. };
  59998. /**
  59999. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  60000. * When this post process is used in a pipeline, this is call will bind the input texture of this post process to the output of the previous.
  60001. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  60002. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  60003. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  60004. */
  60005. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  60006. var _this = this;
  60007. if (sourceTexture === void 0) { sourceTexture = null; }
  60008. camera = camera || this._camera;
  60009. var scene = camera.getScene();
  60010. var engine = scene.getEngine();
  60011. var maxSize = engine.getCaps().maxTextureSize;
  60012. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  60013. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  60014. // If rendering to a webvr camera's left or right eye only half the width should be used to avoid resize when rendered to screen
  60015. var webVRCamera = camera.parent;
  60016. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  60017. requiredWidth /= 2;
  60018. }
  60019. var desiredWidth = (this._options.width || requiredWidth);
  60020. var desiredHeight = this._options.height || requiredHeight;
  60021. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  60022. if (this.adaptScaleToCurrentViewport) {
  60023. var currentViewport = engine.currentViewport;
  60024. if (currentViewport) {
  60025. desiredWidth *= currentViewport.width;
  60026. desiredHeight *= currentViewport.height;
  60027. }
  60028. }
  60029. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  60030. if (!this._options.width) {
  60031. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  60032. }
  60033. if (!this._options.height) {
  60034. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  60035. }
  60036. }
  60037. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  60038. if (this._textures.length > 0) {
  60039. for (var i = 0; i < this._textures.length; i++) {
  60040. this._engine._releaseTexture(this._textures.data[i]);
  60041. }
  60042. this._textures.reset();
  60043. }
  60044. this.width = desiredWidth;
  60045. this.height = desiredHeight;
  60046. var textureSize = { width: this.width, height: this.height };
  60047. var textureOptions = {
  60048. generateMipMaps: false,
  60049. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  60050. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  60051. samplingMode: this.renderTargetSamplingMode,
  60052. type: this._textureType
  60053. };
  60054. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  60055. if (this._reusable) {
  60056. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  60057. }
  60058. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  60059. this.onSizeChangedObservable.notifyObservers(this);
  60060. }
  60061. this._textures.forEach(function (texture) {
  60062. if (texture.samples !== _this.samples) {
  60063. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  60064. }
  60065. });
  60066. }
  60067. var target;
  60068. if (this._shareOutputWithPostProcess) {
  60069. target = this._shareOutputWithPostProcess.inputTexture;
  60070. }
  60071. else if (this._forcedOutputTexture) {
  60072. target = this._forcedOutputTexture;
  60073. this.width = this._forcedOutputTexture.width;
  60074. this.height = this._forcedOutputTexture.height;
  60075. }
  60076. else {
  60077. target = this.inputTexture;
  60078. }
  60079. // Bind the input of this post process to be used as the output of the previous post process.
  60080. if (this.enablePixelPerfectMode) {
  60081. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  60082. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, true);
  60083. }
  60084. else {
  60085. this._scaleRatio.copyFromFloats(1, 1);
  60086. this._engine.bindFramebuffer(target, 0, undefined, undefined, true);
  60087. }
  60088. this.onActivateObservable.notifyObservers(camera);
  60089. // Clear
  60090. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  60091. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  60092. }
  60093. if (this._reusable) {
  60094. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  60095. }
  60096. };
  60097. Object.defineProperty(PostProcess.prototype, "isSupported", {
  60098. /**
  60099. * If the post process is supported.
  60100. */
  60101. get: function () {
  60102. return this._effect.isSupported;
  60103. },
  60104. enumerable: true,
  60105. configurable: true
  60106. });
  60107. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  60108. /**
  60109. * The aspect ratio of the output texture.
  60110. */
  60111. get: function () {
  60112. if (this._shareOutputWithPostProcess) {
  60113. return this._shareOutputWithPostProcess.aspectRatio;
  60114. }
  60115. if (this._forcedOutputTexture) {
  60116. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  60117. }
  60118. return this.width / this.height;
  60119. },
  60120. enumerable: true,
  60121. configurable: true
  60122. });
  60123. /**
  60124. * Get a value indicating if the post-process is ready to be used
  60125. * @returns true if the post-process is ready (shader is compiled)
  60126. */
  60127. PostProcess.prototype.isReady = function () {
  60128. return this._effect && this._effect.isReady();
  60129. };
  60130. /**
  60131. * Binds all textures and uniforms to the shader, this will be run on every pass.
  60132. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  60133. */
  60134. PostProcess.prototype.apply = function () {
  60135. // Check
  60136. if (!this._effect || !this._effect.isReady())
  60137. return null;
  60138. // States
  60139. this._engine.enableEffect(this._effect);
  60140. this._engine.setState(false);
  60141. this._engine.setDepthBuffer(false);
  60142. this._engine.setDepthWrite(false);
  60143. // Alpha
  60144. this._engine.setAlphaMode(this.alphaMode);
  60145. if (this.alphaConstants) {
  60146. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  60147. }
  60148. // Bind the output texture of the preivous post process as the input to this post process.
  60149. var source;
  60150. if (this._shareOutputWithPostProcess) {
  60151. source = this._shareOutputWithPostProcess.inputTexture;
  60152. }
  60153. else if (this._forcedOutputTexture) {
  60154. source = this._forcedOutputTexture;
  60155. }
  60156. else {
  60157. source = this.inputTexture;
  60158. }
  60159. this._effect._bindTexture("textureSampler", source);
  60160. // Parameters
  60161. this._effect.setVector2("scale", this._scaleRatio);
  60162. this.onApplyObservable.notifyObservers(this._effect);
  60163. return this._effect;
  60164. };
  60165. PostProcess.prototype._disposeTextures = function () {
  60166. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  60167. return;
  60168. }
  60169. if (this._textures.length > 0) {
  60170. for (var i = 0; i < this._textures.length; i++) {
  60171. this._engine._releaseTexture(this._textures.data[i]);
  60172. }
  60173. }
  60174. this._textures.dispose();
  60175. };
  60176. /**
  60177. * Disposes the post process.
  60178. * @param camera The camera to dispose the post process on.
  60179. */
  60180. PostProcess.prototype.dispose = function (camera) {
  60181. camera = camera || this._camera;
  60182. this._disposeTextures();
  60183. if (this._scene) {
  60184. var index_1 = this._scene.postProcesses.indexOf(this);
  60185. if (index_1 !== -1) {
  60186. this._scene.postProcesses.splice(index_1, 1);
  60187. }
  60188. }
  60189. else {
  60190. var index_2 = this._engine.postProcesses.indexOf(this);
  60191. if (index_2 !== -1) {
  60192. this._engine.postProcesses.splice(index_2, 1);
  60193. }
  60194. }
  60195. if (!camera) {
  60196. return;
  60197. }
  60198. camera.detachPostProcess(this);
  60199. var index = camera._postProcesses.indexOf(this);
  60200. if (index === 0 && camera._postProcesses.length > 0) {
  60201. var firstPostProcess = this._camera._getFirstPostProcess();
  60202. if (firstPostProcess) {
  60203. firstPostProcess.markTextureDirty();
  60204. }
  60205. }
  60206. this.onActivateObservable.clear();
  60207. this.onAfterRenderObservable.clear();
  60208. this.onApplyObservable.clear();
  60209. this.onBeforeRenderObservable.clear();
  60210. this.onSizeChangedObservable.clear();
  60211. };
  60212. return PostProcess;
  60213. }());
  60214. BABYLON.PostProcess = PostProcess;
  60215. })(BABYLON || (BABYLON = {}));
  60216. //# sourceMappingURL=babylon.postProcess.js.map
  60217. var BABYLON;
  60218. (function (BABYLON) {
  60219. var PassPostProcess = /** @class */ (function (_super) {
  60220. __extends(PassPostProcess, _super);
  60221. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  60222. if (camera === void 0) { camera = null; }
  60223. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  60224. if (blockCompilation === void 0) { blockCompilation = false; }
  60225. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType, undefined, null, blockCompilation) || this;
  60226. }
  60227. return PassPostProcess;
  60228. }(BABYLON.PostProcess));
  60229. BABYLON.PassPostProcess = PassPostProcess;
  60230. })(BABYLON || (BABYLON = {}));
  60231. //# sourceMappingURL=babylon.passPostProcess.js.map
  60232. var __assign = (this && this.__assign) || Object.assign || function(t) {
  60233. for (var s, i = 1, n = arguments.length; i < n; i++) {
  60234. s = arguments[i];
  60235. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  60236. t[p] = s[p];
  60237. }
  60238. return t;
  60239. };
  60240. var BABYLON;
  60241. (function (BABYLON) {
  60242. /**
  60243. * Default implementation of @see IShadowGenerator.
  60244. * This is the main object responsible of generating shadows in the framework.
  60245. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  60246. */
  60247. var ShadowGenerator = /** @class */ (function () {
  60248. /**
  60249. * Creates a ShadowGenerator object.
  60250. * A ShadowGenerator is the required tool to use the shadows.
  60251. * Each light casting shadows needs to use its own ShadowGenerator.
  60252. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  60253. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  60254. * @param light The light object generating the shadows.
  60255. * @param useFullFloatFirst By default the generator will try to use half float textures but if you need precision (for self shadowing for instance), you can use this option to enforce full float texture.
  60256. */
  60257. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  60258. this._bias = 0.00005;
  60259. this._blurBoxOffset = 1;
  60260. this._blurScale = 2;
  60261. this._blurKernel = 1;
  60262. this._useKernelBlur = false;
  60263. this._filter = ShadowGenerator.FILTER_NONE;
  60264. this._darkness = 0;
  60265. this._transparencyShadow = false;
  60266. /**
  60267. * Controls the extent to which the shadows fade out at the edge of the frustum
  60268. * Used only by directionals and spots
  60269. */
  60270. this.frustumEdgeFalloff = 0;
  60271. /**
  60272. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  60273. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  60274. * It might on the other hand introduce peter panning.
  60275. */
  60276. this.forceBackFacesOnly = false;
  60277. this._lightDirection = BABYLON.Vector3.Zero();
  60278. this._viewMatrix = BABYLON.Matrix.Zero();
  60279. this._projectionMatrix = BABYLON.Matrix.Zero();
  60280. this._transformMatrix = BABYLON.Matrix.Zero();
  60281. this._cachedPosition = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  60282. this._cachedDirection = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  60283. this._currentFaceIndex = 0;
  60284. this._currentFaceIndexCache = 0;
  60285. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  60286. this._mapSize = mapSize;
  60287. this._light = light;
  60288. this._scene = light.getScene();
  60289. light._shadowGenerator = this;
  60290. // Texture type fallback from float to int if not supported.
  60291. var caps = this._scene.getEngine().getCaps();
  60292. if (!useFullFloatFirst) {
  60293. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  60294. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  60295. }
  60296. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  60297. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  60298. }
  60299. else {
  60300. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  60301. }
  60302. }
  60303. else {
  60304. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  60305. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  60306. }
  60307. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  60308. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  60309. }
  60310. else {
  60311. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  60312. }
  60313. }
  60314. this._initializeGenerator();
  60315. }
  60316. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  60317. /**
  60318. * Shadow generator mode None: no filtering applied.
  60319. */
  60320. get: function () {
  60321. return ShadowGenerator._FILTER_NONE;
  60322. },
  60323. enumerable: true,
  60324. configurable: true
  60325. });
  60326. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  60327. /**
  60328. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  60329. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  60330. */
  60331. get: function () {
  60332. return ShadowGenerator._FILTER_POISSONSAMPLING;
  60333. },
  60334. enumerable: true,
  60335. configurable: true
  60336. });
  60337. Object.defineProperty(ShadowGenerator, "FILTER_EXPONENTIALSHADOWMAP", {
  60338. /**
  60339. * Shadow generator mode ESM: Exponential Shadow Mapping.
  60340. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  60341. */
  60342. get: function () {
  60343. return ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP;
  60344. },
  60345. enumerable: true,
  60346. configurable: true
  60347. });
  60348. Object.defineProperty(ShadowGenerator, "FILTER_BLUREXPONENTIALSHADOWMAP", {
  60349. /**
  60350. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  60351. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  60352. */
  60353. get: function () {
  60354. return ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP;
  60355. },
  60356. enumerable: true,
  60357. configurable: true
  60358. });
  60359. Object.defineProperty(ShadowGenerator, "FILTER_CLOSEEXPONENTIALSHADOWMAP", {
  60360. /**
  60361. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  60362. * edge artifacts on steep falloff.
  60363. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  60364. */
  60365. get: function () {
  60366. return ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP;
  60367. },
  60368. enumerable: true,
  60369. configurable: true
  60370. });
  60371. Object.defineProperty(ShadowGenerator, "FILTER_BLURCLOSEEXPONENTIALSHADOWMAP", {
  60372. /**
  60373. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  60374. * edge artifacts on steep falloff.
  60375. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  60376. */
  60377. get: function () {
  60378. return ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  60379. },
  60380. enumerable: true,
  60381. configurable: true
  60382. });
  60383. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  60384. /**
  60385. * Gets the bias: offset applied on the depth preventing acnea.
  60386. */
  60387. get: function () {
  60388. return this._bias;
  60389. },
  60390. /**
  60391. * Sets the bias: offset applied on the depth preventing acnea.
  60392. */
  60393. set: function (bias) {
  60394. this._bias = bias;
  60395. },
  60396. enumerable: true,
  60397. configurable: true
  60398. });
  60399. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  60400. /**
  60401. * Gets the blur box offset: offset applied during the blur pass.
  60402. * Only usefull if useKernelBlur = false
  60403. */
  60404. get: function () {
  60405. return this._blurBoxOffset;
  60406. },
  60407. /**
  60408. * Sets the blur box offset: offset applied during the blur pass.
  60409. * Only usefull if useKernelBlur = false
  60410. */
  60411. set: function (value) {
  60412. if (this._blurBoxOffset === value) {
  60413. return;
  60414. }
  60415. this._blurBoxOffset = value;
  60416. this._disposeBlurPostProcesses();
  60417. },
  60418. enumerable: true,
  60419. configurable: true
  60420. });
  60421. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  60422. /**
  60423. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  60424. * 2 means half of the size.
  60425. */
  60426. get: function () {
  60427. return this._blurScale;
  60428. },
  60429. /**
  60430. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  60431. * 2 means half of the size.
  60432. */
  60433. set: function (value) {
  60434. if (this._blurScale === value) {
  60435. return;
  60436. }
  60437. this._blurScale = value;
  60438. this._disposeBlurPostProcesses();
  60439. },
  60440. enumerable: true,
  60441. configurable: true
  60442. });
  60443. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  60444. /**
  60445. * Gets the blur kernel: kernel size of the blur pass.
  60446. * Only usefull if useKernelBlur = true
  60447. */
  60448. get: function () {
  60449. return this._blurKernel;
  60450. },
  60451. /**
  60452. * Sets the blur kernel: kernel size of the blur pass.
  60453. * Only usefull if useKernelBlur = true
  60454. */
  60455. set: function (value) {
  60456. if (this._blurKernel === value) {
  60457. return;
  60458. }
  60459. this._blurKernel = value;
  60460. this._disposeBlurPostProcesses();
  60461. },
  60462. enumerable: true,
  60463. configurable: true
  60464. });
  60465. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  60466. /**
  60467. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  60468. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  60469. */
  60470. get: function () {
  60471. return this._useKernelBlur;
  60472. },
  60473. /**
  60474. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  60475. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  60476. */
  60477. set: function (value) {
  60478. if (this._useKernelBlur === value) {
  60479. return;
  60480. }
  60481. this._useKernelBlur = value;
  60482. this._disposeBlurPostProcesses();
  60483. },
  60484. enumerable: true,
  60485. configurable: true
  60486. });
  60487. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  60488. /**
  60489. * Gets the depth scale used in ESM mode.
  60490. */
  60491. get: function () {
  60492. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  60493. },
  60494. /**
  60495. * Sets the depth scale used in ESM mode.
  60496. * This can override the scale stored on the light.
  60497. */
  60498. set: function (value) {
  60499. this._depthScale = value;
  60500. },
  60501. enumerable: true,
  60502. configurable: true
  60503. });
  60504. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  60505. /**
  60506. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  60507. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  60508. */
  60509. get: function () {
  60510. return this._filter;
  60511. },
  60512. /**
  60513. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  60514. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  60515. */
  60516. set: function (value) {
  60517. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  60518. if (this._light.needCube()) {
  60519. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  60520. this.useExponentialShadowMap = true;
  60521. return;
  60522. }
  60523. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  60524. this.useCloseExponentialShadowMap = true;
  60525. return;
  60526. }
  60527. }
  60528. if (this._filter === value) {
  60529. return;
  60530. }
  60531. this._filter = value;
  60532. this._disposeBlurPostProcesses();
  60533. this._applyFilterValues();
  60534. this._light._markMeshesAsLightDirty();
  60535. },
  60536. enumerable: true,
  60537. configurable: true
  60538. });
  60539. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  60540. /**
  60541. * Gets if the current filter is set to Poisson Sampling aka PCF.
  60542. */
  60543. get: function () {
  60544. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  60545. },
  60546. /**
  60547. * Sets the current filter to Poisson Sampling aka PCF.
  60548. */
  60549. set: function (value) {
  60550. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  60551. return;
  60552. }
  60553. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  60554. },
  60555. enumerable: true,
  60556. configurable: true
  60557. });
  60558. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  60559. /**
  60560. * Gets if the current filter is set to VSM.
  60561. * DEPRECATED. Should use useExponentialShadowMap instead.
  60562. */
  60563. get: function () {
  60564. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  60565. return this.useExponentialShadowMap;
  60566. },
  60567. /**
  60568. * Sets the current filter is to VSM.
  60569. * DEPRECATED. Should use useExponentialShadowMap instead.
  60570. */
  60571. set: function (value) {
  60572. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  60573. this.useExponentialShadowMap = value;
  60574. },
  60575. enumerable: true,
  60576. configurable: true
  60577. });
  60578. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  60579. /**
  60580. * Gets if the current filter is set to blurred VSM.
  60581. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  60582. */
  60583. get: function () {
  60584. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  60585. return this.useBlurExponentialShadowMap;
  60586. },
  60587. /**
  60588. * Sets the current filter is to blurred VSM.
  60589. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  60590. */
  60591. set: function (value) {
  60592. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  60593. this.useBlurExponentialShadowMap = value;
  60594. },
  60595. enumerable: true,
  60596. configurable: true
  60597. });
  60598. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  60599. /**
  60600. * Gets if the current filter is set to ESM.
  60601. */
  60602. get: function () {
  60603. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  60604. },
  60605. /**
  60606. * Sets the current filter is to ESM.
  60607. */
  60608. set: function (value) {
  60609. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  60610. return;
  60611. }
  60612. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  60613. },
  60614. enumerable: true,
  60615. configurable: true
  60616. });
  60617. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  60618. /**
  60619. * Gets if the current filter is set to filtered ESM.
  60620. */
  60621. get: function () {
  60622. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  60623. },
  60624. /**
  60625. * Gets if the current filter is set to filtered ESM.
  60626. */
  60627. set: function (value) {
  60628. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  60629. return;
  60630. }
  60631. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  60632. },
  60633. enumerable: true,
  60634. configurable: true
  60635. });
  60636. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  60637. /**
  60638. * Gets if the current filter is set to "close ESM" (using the inverse of the
  60639. * exponential to prevent steep falloff artifacts).
  60640. */
  60641. get: function () {
  60642. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  60643. },
  60644. /**
  60645. * Sets the current filter to "close ESM" (using the inverse of the
  60646. * exponential to prevent steep falloff artifacts).
  60647. */
  60648. set: function (value) {
  60649. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  60650. return;
  60651. }
  60652. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  60653. },
  60654. enumerable: true,
  60655. configurable: true
  60656. });
  60657. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  60658. /**
  60659. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  60660. * exponential to prevent steep falloff artifacts).
  60661. */
  60662. get: function () {
  60663. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  60664. },
  60665. /**
  60666. * Sets the current filter to fileterd "close ESM" (using the inverse of the
  60667. * exponential to prevent steep falloff artifacts).
  60668. */
  60669. set: function (value) {
  60670. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  60671. return;
  60672. }
  60673. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  60674. },
  60675. enumerable: true,
  60676. configurable: true
  60677. });
  60678. /**
  60679. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  60680. * 0 means strongest and 1 would means no shadow.
  60681. * @returns the darkness.
  60682. */
  60683. ShadowGenerator.prototype.getDarkness = function () {
  60684. return this._darkness;
  60685. };
  60686. /**
  60687. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  60688. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  60689. * @returns the shadow generator allowing fluent coding.
  60690. */
  60691. ShadowGenerator.prototype.setDarkness = function (darkness) {
  60692. if (darkness >= 1.0)
  60693. this._darkness = 1.0;
  60694. else if (darkness <= 0.0)
  60695. this._darkness = 0.0;
  60696. else
  60697. this._darkness = darkness;
  60698. return this;
  60699. };
  60700. /**
  60701. * Sets the ability to have transparent shadow (boolean).
  60702. * @param transparent True if transparent else False
  60703. * @returns the shadow generator allowing fluent coding
  60704. */
  60705. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  60706. this._transparencyShadow = transparent;
  60707. return this;
  60708. };
  60709. /**
  60710. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  60711. * @returns The render target texture if present otherwise, null
  60712. */
  60713. ShadowGenerator.prototype.getShadowMap = function () {
  60714. return this._shadowMap;
  60715. };
  60716. /**
  60717. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  60718. * @returns The render target texture if the shadow map is present otherwise, null
  60719. */
  60720. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  60721. if (this._shadowMap2) {
  60722. return this._shadowMap2;
  60723. }
  60724. return this._shadowMap;
  60725. };
  60726. /**
  60727. * Helper function to add a mesh and its descendants to the list of shadow casters.
  60728. * @param mesh Mesh to add
  60729. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  60730. * @returns the Shadow Generator itself
  60731. */
  60732. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  60733. if (includeDescendants === void 0) { includeDescendants = true; }
  60734. if (!this._shadowMap) {
  60735. return this;
  60736. }
  60737. if (!this._shadowMap.renderList) {
  60738. this._shadowMap.renderList = [];
  60739. }
  60740. this._shadowMap.renderList.push(mesh);
  60741. if (includeDescendants) {
  60742. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  60743. }
  60744. return this;
  60745. var _a;
  60746. };
  60747. /**
  60748. * Helper function to remove a mesh and its descendants from the list of shadow casters
  60749. * @param mesh Mesh to remove
  60750. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  60751. * @returns the Shadow Generator itself
  60752. */
  60753. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  60754. if (includeDescendants === void 0) { includeDescendants = true; }
  60755. if (!this._shadowMap || !this._shadowMap.renderList) {
  60756. return this;
  60757. }
  60758. var index = this._shadowMap.renderList.indexOf(mesh);
  60759. if (index !== -1) {
  60760. this._shadowMap.renderList.splice(index, 1);
  60761. }
  60762. if (includeDescendants) {
  60763. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  60764. var child = _a[_i];
  60765. this.removeShadowCaster(child);
  60766. }
  60767. }
  60768. return this;
  60769. };
  60770. /**
  60771. * Returns the associated light object.
  60772. * @returns the light generating the shadow
  60773. */
  60774. ShadowGenerator.prototype.getLight = function () {
  60775. return this._light;
  60776. };
  60777. ShadowGenerator.prototype._initializeGenerator = function () {
  60778. this._light._markMeshesAsLightDirty();
  60779. this._initializeShadowMap();
  60780. };
  60781. ShadowGenerator.prototype._initializeShadowMap = function () {
  60782. var _this = this;
  60783. // Render target
  60784. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  60785. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60786. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60787. this._shadowMap.anisotropicFilteringLevel = 1;
  60788. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  60789. this._shadowMap.renderParticles = false;
  60790. this._shadowMap.ignoreCameraViewport = true;
  60791. // Record Face Index before render.
  60792. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  60793. _this._currentFaceIndex = faceIndex;
  60794. });
  60795. // Custom render function.
  60796. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  60797. // Blur if required afer render.
  60798. this._shadowMap.onAfterUnbindObservable.add(function () {
  60799. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  60800. return;
  60801. }
  60802. var shadowMap = _this.getShadowMapForRendering();
  60803. if (shadowMap) {
  60804. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  60805. }
  60806. });
  60807. // Clear according to the chosen filter.
  60808. var zero = new BABYLON.Color4(0, 0, 0, 0);
  60809. var one = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  60810. this._shadowMap.onClearObservable.add(function (engine) {
  60811. if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  60812. engine.clear(zero, true, true, true);
  60813. }
  60814. else {
  60815. engine.clear(one, true, true, true);
  60816. }
  60817. });
  60818. };
  60819. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  60820. var _this = this;
  60821. var engine = this._scene.getEngine();
  60822. var targetSize = this._mapSize / this.blurScale;
  60823. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  60824. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  60825. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60826. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60827. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  60828. }
  60829. if (this.useKernelBlur) {
  60830. this._kernelBlurXPostprocess = new BABYLON.BlurPostProcess(this._light.name + "KernelBlurX", new BABYLON.Vector2(1, 0), this.blurKernel, 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._textureType);
  60831. this._kernelBlurXPostprocess.width = targetSize;
  60832. this._kernelBlurXPostprocess.height = targetSize;
  60833. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  60834. effect.setTexture("textureSampler", _this._shadowMap);
  60835. });
  60836. this._kernelBlurYPostprocess = new BABYLON.BlurPostProcess(this._light.name + "KernelBlurY", new BABYLON.Vector2(0, 1), this.blurKernel, 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._textureType);
  60837. this._kernelBlurXPostprocess.autoClear = false;
  60838. this._kernelBlurYPostprocess.autoClear = false;
  60839. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  60840. this._kernelBlurXPostprocess.packedFloat = true;
  60841. this._kernelBlurYPostprocess.packedFloat = true;
  60842. }
  60843. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  60844. }
  60845. else {
  60846. this._boxBlurPostprocess = new BABYLON.PostProcess(this._light.name + "DepthBoxBlur", "depthBoxBlur", ["screenSize", "boxOffset"], [], 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, "#define OFFSET " + this._blurBoxOffset, this._textureType);
  60847. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  60848. effect.setFloat2("screenSize", targetSize, targetSize);
  60849. effect.setTexture("textureSampler", _this._shadowMap);
  60850. });
  60851. this._boxBlurPostprocess.autoClear = false;
  60852. this._blurPostProcesses = [this._boxBlurPostprocess];
  60853. }
  60854. };
  60855. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  60856. var index;
  60857. var engine = this._scene.getEngine();
  60858. if (depthOnlySubMeshes.length) {
  60859. engine.setColorWrite(false);
  60860. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  60861. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  60862. }
  60863. engine.setColorWrite(true);
  60864. }
  60865. for (index = 0; index < opaqueSubMeshes.length; index++) {
  60866. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  60867. }
  60868. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  60869. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  60870. }
  60871. if (this._transparencyShadow) {
  60872. for (index = 0; index < transparentSubMeshes.length; index++) {
  60873. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  60874. }
  60875. }
  60876. };
  60877. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  60878. var _this = this;
  60879. var mesh = subMesh.getRenderingMesh();
  60880. var scene = this._scene;
  60881. var engine = scene.getEngine();
  60882. var material = subMesh.getMaterial();
  60883. if (!material) {
  60884. return;
  60885. }
  60886. // Culling
  60887. engine.setState(material.backFaceCulling);
  60888. // Managing instances
  60889. var batch = mesh._getInstancesRenderList(subMesh._id);
  60890. if (batch.mustReturn) {
  60891. return;
  60892. }
  60893. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  60894. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  60895. engine.enableEffect(this._effect);
  60896. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  60897. this._effect.setFloat2("biasAndScale", this.bias, this.depthScale);
  60898. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  60899. this._effect.setVector3("lightPosition", this.getLight().position);
  60900. if (scene.activeCamera) {
  60901. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  60902. }
  60903. // Alpha test
  60904. if (material && material.needAlphaTesting()) {
  60905. var alphaTexture = material.getAlphaTestTexture();
  60906. if (alphaTexture) {
  60907. this._effect.setTexture("diffuseSampler", alphaTexture);
  60908. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  60909. }
  60910. }
  60911. // Bones
  60912. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  60913. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  60914. }
  60915. if (this.forceBackFacesOnly) {
  60916. engine.setState(true, 0, false, true);
  60917. }
  60918. // Draw
  60919. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  60920. if (this.forceBackFacesOnly) {
  60921. engine.setState(true, 0, false, false);
  60922. }
  60923. }
  60924. else {
  60925. // Need to reset refresh rate of the shadowMap
  60926. if (this._shadowMap) {
  60927. this._shadowMap.resetRefreshCounter();
  60928. }
  60929. }
  60930. };
  60931. ShadowGenerator.prototype._applyFilterValues = function () {
  60932. if (!this._shadowMap) {
  60933. return;
  60934. }
  60935. if (this.filter === ShadowGenerator.FILTER_NONE) {
  60936. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  60937. }
  60938. else {
  60939. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  60940. }
  60941. };
  60942. /**
  60943. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  60944. * @param onCompiled Callback triggered at the and of the effects compilation
  60945. * @param options Sets of optional options forcing the compilation with different modes
  60946. */
  60947. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  60948. var _this = this;
  60949. var localOptions = __assign({ useInstances: false }, options);
  60950. var shadowMap = this.getShadowMap();
  60951. if (!shadowMap) {
  60952. if (onCompiled) {
  60953. onCompiled(this);
  60954. }
  60955. return;
  60956. }
  60957. var renderList = shadowMap.renderList;
  60958. if (!renderList) {
  60959. if (onCompiled) {
  60960. onCompiled(this);
  60961. }
  60962. return;
  60963. }
  60964. var subMeshes = new Array();
  60965. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  60966. var mesh = renderList_1[_i];
  60967. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  60968. }
  60969. if (subMeshes.length === 0) {
  60970. if (onCompiled) {
  60971. onCompiled(this);
  60972. }
  60973. return;
  60974. }
  60975. var currentIndex = 0;
  60976. var checkReady = function () {
  60977. if (!_this._scene || !_this._scene.getEngine()) {
  60978. return;
  60979. }
  60980. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  60981. currentIndex++;
  60982. if (currentIndex >= subMeshes.length) {
  60983. if (onCompiled) {
  60984. onCompiled(_this);
  60985. }
  60986. return;
  60987. }
  60988. }
  60989. setTimeout(checkReady, 16);
  60990. };
  60991. checkReady();
  60992. };
  60993. /**
  60994. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  60995. * @param options Sets of optional options forcing the compilation with different modes
  60996. * @returns A promise that resolves when the compilation completes
  60997. */
  60998. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  60999. var _this = this;
  61000. return new Promise(function (resolve) {
  61001. _this.forceCompilation(function () {
  61002. resolve();
  61003. }, options);
  61004. });
  61005. };
  61006. /**
  61007. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  61008. * @param subMesh The submesh we want to render in the shadow map
  61009. * @param useInstances Defines wether will draw in the map using instances
  61010. * @returns true if ready otherwise, false
  61011. */
  61012. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  61013. var defines = [];
  61014. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  61015. defines.push("#define FLOAT");
  61016. }
  61017. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  61018. defines.push("#define ESM");
  61019. }
  61020. var attribs = [BABYLON.VertexBuffer.PositionKind];
  61021. var mesh = subMesh.getMesh();
  61022. var material = subMesh.getMaterial();
  61023. // Alpha test
  61024. if (material && material.needAlphaTesting()) {
  61025. var alphaTexture = material.getAlphaTestTexture();
  61026. if (alphaTexture) {
  61027. defines.push("#define ALPHATEST");
  61028. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  61029. attribs.push(BABYLON.VertexBuffer.UVKind);
  61030. defines.push("#define UV1");
  61031. }
  61032. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  61033. if (alphaTexture.coordinatesIndex === 1) {
  61034. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  61035. defines.push("#define UV2");
  61036. }
  61037. }
  61038. }
  61039. }
  61040. // Bones
  61041. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  61042. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  61043. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  61044. if (mesh.numBoneInfluencers > 4) {
  61045. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  61046. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  61047. }
  61048. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  61049. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  61050. }
  61051. else {
  61052. defines.push("#define NUM_BONE_INFLUENCERS 0");
  61053. }
  61054. // Instances
  61055. if (useInstances) {
  61056. defines.push("#define INSTANCES");
  61057. attribs.push("world0");
  61058. attribs.push("world1");
  61059. attribs.push("world2");
  61060. attribs.push("world3");
  61061. }
  61062. // Get correct effect
  61063. var join = defines.join("\n");
  61064. if (this._cachedDefines !== join) {
  61065. this._cachedDefines = join;
  61066. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues", "biasAndScale"], ["diffuseSampler"], join);
  61067. }
  61068. if (!this._effect.isReady()) {
  61069. return false;
  61070. }
  61071. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  61072. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  61073. this._initializeBlurRTTAndPostProcesses();
  61074. }
  61075. }
  61076. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  61077. return false;
  61078. }
  61079. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  61080. return false;
  61081. }
  61082. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  61083. return false;
  61084. }
  61085. return true;
  61086. };
  61087. /**
  61088. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  61089. * @param defines Defines of the material we want to update
  61090. * @param lightIndex Index of the light in the enabled light list of the material
  61091. */
  61092. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  61093. var scene = this._scene;
  61094. var light = this._light;
  61095. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  61096. return;
  61097. }
  61098. defines["SHADOW" + lightIndex] = true;
  61099. if (this.usePoissonSampling) {
  61100. defines["SHADOWPCF" + lightIndex] = true;
  61101. }
  61102. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  61103. defines["SHADOWESM" + lightIndex] = true;
  61104. }
  61105. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  61106. defines["SHADOWCLOSEESM" + lightIndex] = true;
  61107. }
  61108. if (light.needCube()) {
  61109. defines["SHADOWCUBE" + lightIndex] = true;
  61110. }
  61111. };
  61112. /**
  61113. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  61114. * defined in the generator but impacting the effect).
  61115. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  61116. * @param effect The effect we are binfing the information for
  61117. */
  61118. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  61119. var light = this._light;
  61120. var scene = this._scene;
  61121. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  61122. return;
  61123. }
  61124. var camera = scene.activeCamera;
  61125. if (!camera) {
  61126. return;
  61127. }
  61128. var shadowMap = this.getShadowMap();
  61129. if (!shadowMap) {
  61130. return;
  61131. }
  61132. if (!light.needCube()) {
  61133. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  61134. }
  61135. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  61136. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  61137. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  61138. };
  61139. /**
  61140. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  61141. * (eq to shadow prjection matrix * light transform matrix)
  61142. * @returns The transform matrix used to create the shadow map
  61143. */
  61144. ShadowGenerator.prototype.getTransformMatrix = function () {
  61145. var scene = this._scene;
  61146. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  61147. return this._transformMatrix;
  61148. }
  61149. this._currentRenderID = scene.getRenderId();
  61150. this._currentFaceIndexCache = this._currentFaceIndex;
  61151. var lightPosition = this._light.position;
  61152. if (this._light.computeTransformedInformation()) {
  61153. lightPosition = this._light.transformedPosition;
  61154. }
  61155. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  61156. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  61157. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  61158. }
  61159. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  61160. this._cachedPosition.copyFrom(lightPosition);
  61161. this._cachedDirection.copyFrom(this._lightDirection);
  61162. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  61163. var shadowMap = this.getShadowMap();
  61164. if (shadowMap) {
  61165. var renderList = shadowMap.renderList;
  61166. if (renderList) {
  61167. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  61168. }
  61169. }
  61170. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  61171. }
  61172. return this._transformMatrix;
  61173. };
  61174. /**
  61175. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  61176. * Cube and 2D textures for instance.
  61177. */
  61178. ShadowGenerator.prototype.recreateShadowMap = function () {
  61179. var shadowMap = this._shadowMap;
  61180. if (!shadowMap) {
  61181. return;
  61182. }
  61183. // Track render list.
  61184. var renderList = shadowMap.renderList;
  61185. // Clean up existing data.
  61186. this._disposeRTTandPostProcesses();
  61187. // Reinitializes.
  61188. this._initializeGenerator();
  61189. // Reaffect the filter to ensure a correct fallback if necessary.
  61190. this.filter = this.filter;
  61191. // Reaffect the filter.
  61192. this._applyFilterValues();
  61193. // Reaffect Render List.
  61194. this._shadowMap.renderList = renderList;
  61195. };
  61196. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  61197. if (this._shadowMap2) {
  61198. this._shadowMap2.dispose();
  61199. this._shadowMap2 = null;
  61200. }
  61201. if (this._boxBlurPostprocess) {
  61202. this._boxBlurPostprocess.dispose();
  61203. this._boxBlurPostprocess = null;
  61204. }
  61205. if (this._kernelBlurXPostprocess) {
  61206. this._kernelBlurXPostprocess.dispose();
  61207. this._kernelBlurXPostprocess = null;
  61208. }
  61209. if (this._kernelBlurYPostprocess) {
  61210. this._kernelBlurYPostprocess.dispose();
  61211. this._kernelBlurYPostprocess = null;
  61212. }
  61213. this._blurPostProcesses = [];
  61214. };
  61215. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  61216. if (this._shadowMap) {
  61217. this._shadowMap.dispose();
  61218. this._shadowMap = null;
  61219. }
  61220. this._disposeBlurPostProcesses();
  61221. };
  61222. /**
  61223. * Disposes the ShadowGenerator.
  61224. * Returns nothing.
  61225. */
  61226. ShadowGenerator.prototype.dispose = function () {
  61227. this._disposeRTTandPostProcesses();
  61228. if (this._light) {
  61229. this._light._shadowGenerator = null;
  61230. this._light._markMeshesAsLightDirty();
  61231. }
  61232. };
  61233. /**
  61234. * Serializes the shadow generator setup to a json object.
  61235. * @returns The serialized JSON object
  61236. */
  61237. ShadowGenerator.prototype.serialize = function () {
  61238. var serializationObject = {};
  61239. var shadowMap = this.getShadowMap();
  61240. if (!shadowMap) {
  61241. return serializationObject;
  61242. }
  61243. serializationObject.lightId = this._light.id;
  61244. serializationObject.mapSize = shadowMap.getRenderSize();
  61245. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  61246. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  61247. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  61248. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  61249. serializationObject.usePoissonSampling = this.usePoissonSampling;
  61250. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  61251. serializationObject.depthScale = this.depthScale;
  61252. serializationObject.darkness = this.getDarkness();
  61253. serializationObject.blurBoxOffset = this.blurBoxOffset;
  61254. serializationObject.blurKernel = this.blurKernel;
  61255. serializationObject.blurScale = this.blurScale;
  61256. serializationObject.useKernelBlur = this.useKernelBlur;
  61257. serializationObject.transparencyShadow = this._transparencyShadow;
  61258. serializationObject.renderList = [];
  61259. if (shadowMap.renderList) {
  61260. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  61261. var mesh = shadowMap.renderList[meshIndex];
  61262. serializationObject.renderList.push(mesh.id);
  61263. }
  61264. }
  61265. return serializationObject;
  61266. };
  61267. /**
  61268. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  61269. * @param parsedShadowGenerator The JSON object to parse
  61270. * @param scene The scene to create the shadow map for
  61271. * @returns The parsed shadow generator
  61272. */
  61273. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  61274. //casting to point light, as light is missing the position attr and typescript complains.
  61275. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  61276. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  61277. var shadowMap = shadowGenerator.getShadowMap();
  61278. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  61279. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  61280. meshes.forEach(function (mesh) {
  61281. if (!shadowMap) {
  61282. return;
  61283. }
  61284. if (!shadowMap.renderList) {
  61285. shadowMap.renderList = [];
  61286. }
  61287. shadowMap.renderList.push(mesh);
  61288. });
  61289. }
  61290. if (parsedShadowGenerator.usePoissonSampling) {
  61291. shadowGenerator.usePoissonSampling = true;
  61292. }
  61293. else if (parsedShadowGenerator.useExponentialShadowMap) {
  61294. shadowGenerator.useExponentialShadowMap = true;
  61295. }
  61296. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  61297. shadowGenerator.useBlurExponentialShadowMap = true;
  61298. }
  61299. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  61300. shadowGenerator.useCloseExponentialShadowMap = true;
  61301. }
  61302. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  61303. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  61304. }
  61305. else if (parsedShadowGenerator.useVarianceShadowMap) {
  61306. shadowGenerator.useExponentialShadowMap = true;
  61307. }
  61308. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  61309. shadowGenerator.useBlurExponentialShadowMap = true;
  61310. }
  61311. if (parsedShadowGenerator.depthScale) {
  61312. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  61313. }
  61314. if (parsedShadowGenerator.blurScale) {
  61315. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  61316. }
  61317. if (parsedShadowGenerator.blurBoxOffset) {
  61318. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  61319. }
  61320. if (parsedShadowGenerator.useKernelBlur) {
  61321. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  61322. }
  61323. if (parsedShadowGenerator.blurKernel) {
  61324. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  61325. }
  61326. if (parsedShadowGenerator.bias !== undefined) {
  61327. shadowGenerator.bias = parsedShadowGenerator.bias;
  61328. }
  61329. if (parsedShadowGenerator.darkness) {
  61330. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  61331. }
  61332. if (parsedShadowGenerator.transparencyShadow) {
  61333. shadowGenerator.setTransparencyShadow(true);
  61334. }
  61335. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  61336. return shadowGenerator;
  61337. };
  61338. ShadowGenerator._FILTER_NONE = 0;
  61339. ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP = 1;
  61340. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  61341. ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  61342. ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  61343. ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  61344. return ShadowGenerator;
  61345. }());
  61346. BABYLON.ShadowGenerator = ShadowGenerator;
  61347. })(BABYLON || (BABYLON = {}));
  61348. //# sourceMappingURL=babylon.shadowGenerator.js.map
  61349. var BABYLON;
  61350. (function (BABYLON) {
  61351. var DefaultLoadingScreen = /** @class */ (function () {
  61352. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  61353. if (_loadingText === void 0) { _loadingText = ""; }
  61354. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  61355. var _this = this;
  61356. this._renderingCanvas = _renderingCanvas;
  61357. this._loadingText = _loadingText;
  61358. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  61359. // Resize
  61360. this._resizeLoadingUI = function () {
  61361. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  61362. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  61363. if (!_this._loadingDiv) {
  61364. return;
  61365. }
  61366. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  61367. _this._loadingDiv.style.left = canvasRect.left + "px";
  61368. _this._loadingDiv.style.top = canvasRect.top + "px";
  61369. _this._loadingDiv.style.width = canvasRect.width + "px";
  61370. _this._loadingDiv.style.height = canvasRect.height + "px";
  61371. };
  61372. }
  61373. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  61374. if (this._loadingDiv) {
  61375. // Do not add a loading screen if there is already one
  61376. return;
  61377. }
  61378. this._loadingDiv = document.createElement("div");
  61379. this._loadingDiv.id = "babylonjsLoadingDiv";
  61380. this._loadingDiv.style.opacity = "0";
  61381. this._loadingDiv.style.transition = "opacity 1.5s ease";
  61382. this._loadingDiv.style.pointerEvents = "none";
  61383. // Loading text
  61384. this._loadingTextDiv = document.createElement("div");
  61385. this._loadingTextDiv.style.position = "absolute";
  61386. this._loadingTextDiv.style.left = "0";
  61387. this._loadingTextDiv.style.top = "50%";
  61388. this._loadingTextDiv.style.marginTop = "80px";
  61389. this._loadingTextDiv.style.width = "100%";
  61390. this._loadingTextDiv.style.height = "20px";
  61391. this._loadingTextDiv.style.fontFamily = "Arial";
  61392. this._loadingTextDiv.style.fontSize = "14px";
  61393. this._loadingTextDiv.style.color = "white";
  61394. this._loadingTextDiv.style.textAlign = "center";
  61395. this._loadingTextDiv.innerHTML = "Loading";
  61396. this._loadingDiv.appendChild(this._loadingTextDiv);
  61397. //set the predefined text
  61398. this._loadingTextDiv.innerHTML = this._loadingText;
  61399. // Generating keyframes
  61400. var style = document.createElement('style');
  61401. style.type = 'text/css';
  61402. var keyFrames = "@-webkit-keyframes spin1 { 0% { -webkit-transform: rotate(0deg);}\n 100% { -webkit-transform: rotate(360deg);}\n } @keyframes spin1 { 0% { transform: rotate(0deg);}\n 100% { transform: rotate(360deg);}\n }";
  61403. style.innerHTML = keyFrames;
  61404. document.getElementsByTagName('head')[0].appendChild(style);
  61405. // Loading img
  61406. var imgBack = new Image();
  61407. imgBack.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAHgAAAB4CAYAAAA5ZDbSAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAAZdEVYdFNvZnR3YXJlAHBhaW50Lm5ldCA0LjAuMTZEaa/1AAAYq0lEQVR4Xu2dCZRcVZnHScAJUZSwjSOIbAJmEAZwQCCMoAInYRGIg8AwegQx7AFzUBBmzAFlE4EAwxz2GRk2w7AnAURZBiEOZgyEQDAQAjmEJqTpNd3V1V3Vmd+/6utKV7/1vnpVXd2p/zn3vOV+27vfu/fd/W3QQAPrBZqbm7fJZrN79vf3T+/r67uf4wO9vb37WXQDIwWtra0Tenp6voQTv5XP56/BkfcR3iLk1g6B7hEeI+zP5V+ZiAbqBZ2dnZ8lV+6Gg87CobfhpOc4byf0FjwYE9DneBkWcXrM2tmzNzTxDdQKJPyETCazI46YgiMuI9zJuXJltuChFIHsP/PSfIfTjU19A2mira1tcxy3ey6XO5vEnkV4kes11XBmENDVj97XOT2O03FmWgMuoNLzGRJva8IUnPkzjjcT/kLoKCZzfQB7XiX8M2G8md7AUJgzJ+Z6e88gZ1xGuj3HsY17PcVkrG9gp7CUF/F8PUvxqdZDrFq1ahNVfKjwTCYxZuDE2wjKlc2WViMePM+HPNsFPOdf22OPblD5OZQHvphnV65cjTMzxaQY3eA5V9OO/hmnm1lSjE7woFsQbiXki4++foHnXkW4mLC1JUl947333tsMY3emqfB9jtPJlXN5U0+bOXPmWCPxgOccSy4+AfqPio+9/oFnbyatbqVE28GSZfjQ1NT0KQzaHMcdyPfyaNoE12HcvdxT29K3Fkv8A2vWrPmcifAFZNtD91yRY+SBZ+9UsMtEgD+jTpeenp6JXI6xpKkuUDqRcA6Kr0Wpens+InQTnIpV6Fdi+BQT64ulS5eOIzefD62na7CeoGcnLCM8ykt5OWlzcPv772/BS/w3nP+K+xU11+DvQe5dcrQlTfWAwbNMb8XA8AyGX80xtLlA6TAJuteMbVhhia1v5VMcr+LWMeoZ4xiYw7q6urbhHbgG+paCkIRQehHu4pO3O5fVydEomF5Ulx548JfVD2wqfKE2I3R3ob/f2GoC1DWhdz7HG3i5j2pvb9+Z24m6HvVZQtYsZFWcowlzePEP4jJdR/OQhxTVpAs9NMXxmZxuZKo8IG4s+v8R2tUFphSBTBWzH+OAFwn/gS3TuN55xYoVqfc6dXd3fwHZ1xFaTX0iyGbwjJqXXAammxP00EXx6UMGEx7ram7+vKnzBZ/87Xiwp40tEdDTgYwlHG/CmadSjO7L+XiialOZAej7POFG2VK0Khngl6Pn8/LL0YEtlFh4n8oDAqvaAYH8tzH2iNDm1IIFn8Ax50G7xtgCAU07CfAG4RHOz+vLZL7e0dGxlYlKHaj8BHo25xgrsfV5wrYH4KmouxV+ZZDnCUdwmXxMGgFvFUVWD+jQuOot6rI0tb4gcfaG9v+MrcAn+wj38gL8C7cObmlp2ZRjOkWYD6ypuAf6zjFHLSJ0c/6YQ813DM/yZXgehreiVgP8cvSfsOeExYsXuzs6n8v9j8mqBRZQmdjXVPuira1NHSpn8UDf4Xu0vd2uCtDzacJOlDDf5ng94X8JTWarB8R1EK7ju7udiYgEz/v3pLFKm4oHUHhh3iZdfshpaEYpA4pvKLLXBujLYKRq71XLhUHg27z12rW9B6L/QhLrWWxRH7nzeDK8awi/5HRTEx0K6MZQ694LHk0DqrgfADkreIYz1q5c+UlTEQzesIuMryrggYQWjNL3RGO7p2tuFMeqjaOidgzyCz1yJMTJ6L6d66WEVCcHIO/dQkI75Chs2g97Hoc3jRz9Lge1ED5l4r0gckqRPB0gTw34t1B+h3IqxZkmrn2SULUa7ezZszdE5xfR9130Xsm5ilrnHrmkQOcKvrkncxqrIiY6wlewbw7BOUfDo/b84zzvj9C7J7eCS0NrUiRKCPjUE7ScMBdlF/B2HqBi0ERXBcuXL99YnQz9fX2ah3Up4UnsWGEmDRuUhoTn+Z5PfvbZZ2N/fuCZRJgnfhNVBu73EZoIKt7l0L2UBsYeDZg016nb5EUCWuXQewinUtTuyq2aTStF14a8SD+VDQVj6hDYxjuXf4Hjl83sSMCmTp8j4FtoMuRQ5dAZcii3kk/0s2bBhxIcBxjxUlib1hWInEDO/6qKV+y4geO5HAMntEE/pq+nZyo0ywsG1SmwL4Orf+0yqGCfmvR73LAn9lAeBjQTEhkA+1h49a08iRflcq4H5iuXFU9cz4lqihC/LXS/NZa6Bc+pz5gql5ub6VXD2tZWTSPeyS7XgeLhXrMnEhj6MSHSwaIhFGZH8oA/JzzFeexvJbRN2HW03moT6cEChx6w4QY2rurn85JWrxsiCy0FwjcIqos8w7GZNPulkawDEbFHlaBtjzODEDrVztuKXMmADPWA3RaljyJeNdKq98ilAez8iJdyGqfO31V4NoV/EvyaCqR54V2EshE5Lqcb+TrkstkTLD4WKB4PNNZQ8P05HAelMXNSPWChC8JsYvwthJo0jSoF6fIqjjqe08Aat+LIkd+AVjn09zxbZFqK3tjXAUbXUaWDjTUSyN4J45YZX2Igo4cEOVfFson2ALIxSjR0jog5YNgpfNHM90BxIjDyWIB8Z2NfB01HISJ20wPaw4w1FlavXq1v8aPGXhFw9JNRFTDItifU/RwwpfmKxYsDK180kU4x0lhAXvOSJUs+bezlIDL2N4xi4GpjK4MGCuzUA+SPxzn3m4iKgKyV2DCV08DeMWg0B+zHHOt2DpjS3Mz1BfFOM25C5ZH4LxldJBB0g7GVARkaXgv8VsKqZtIMPpN9RUnJgRzU5Wfp22vifcG3+2vQvmdsdQXsX2pm+oKX+GYjjQXkPWqsXshpRhcJ0RpbGShSHiSuheP37ZYHsGusVHOrU1lMxkO9od4eE+8LlSzQqfetpnPAooBN/2Um+gISp89MkF8K4G3RrMJYoOhbYGxlQEGhSOGogfoLwipExGtUZVVBYIVAluaAaUpuWA+YujlPF22Ra/iBLYEOsV6tV4w0FiitfmLsXiBMU0NiAVrfsp77Zd8MHPgbDoHtva6uLs1jiv1piAKy5tCG+4KJ9wVO/p6RDzvy+b5rzSwP9Okh/WKPERiCWzfk4K8bUSTiOljAyCdx5DZG4gE8W5Dov+NYUfsV/j50fUC4dmXIQDh0qQ6PVgJsOcLM8oA410Ggvo6Ojr81di+g2TKuQOiyJOKWxlpCJpM5zUjKAL3awTsamQfEbYhjtDGKa5tPsyn/wAuiURftlBO56h6aunEwCMxxvV1d+2Fr7Jce2vAu5LUtLeoGi/19gtbToCaR97BoD6BvUs+WkXqgbw6OuhC6wH5l4rRGaCFOvYnjYbyxnpcsCvDVhYOxo6+zszNwSNHVTtJEmSiwzlMAQmNPwIPW42Dds2hfEK/5WJo0Fth+5VNxFHSlkoTzFRh/N3wnq0OGWxXtdoO8enFwaI4jsyidYgNZTxhrMEjEJ4w+En65ESWRXZ7Q4K/COqDAPlhka87WedB8KawmngTIHREOJs5pMiRp+p/GGgxL1FiA9hxjK6G1tVVdhJGAV15+cPXq1f7dahVC20Wg4miCp0uTe3Xh4Hwu93rY1B7SR/t7xQbP5R1FGgpy8IlKe+MJhZ9Aa7u5jPm+pGLX2BMDOZ+hDXgQiXIJ5xoXHZg96anEEFcvOTi0SMUXS4w0FijSTzTWYEA3hkTSEtDI2qw6RoytDLA6jctCvzKqJ8oPFOO7kAhnYe9cZGiWiZ/N9ezguWaSL4h3TUfvKJIfoN0I4sjigYSdZyxlcDVMgEczEY41ER6oZFBOh2Yqegf2zYoziFC3DuZZrjSTPLDtMlxaNPmPP/54W2OPxksrVozP5fLPGr8vEOpbxJCr3jQSJyDvGRNRhv7iHh8vE5LMpKznHBz4zSTOaXwe+mXGGh9tbWvVQf+iyfCAON/ZlTj4v43ECfB94Le4CuMrWVpTtw7O9fZOM5M8oD7xVSOLBdLuNWN1g7bgJUF8+4qpBjf7Te9M6hD4tBDc0289Wh2MHbuaSR7gsHOMLBaQ9W/G6o5MJrNDPu9dcYdQ33Yc95I6OFV5hnp2cGCliDingX5KU+9MShd0dmqta/k8J4zwnV2JsuuNxAnI83VwNpO52kiSoC4djA255cuXBzYPycGzjTQWkPdNY00OfRcQVLafRnd39ySLLsG1i20AyPZ3cDb7AyNJgnp1cOhUHUhcFiL045v9jTUa8Gjlm29fsQQhb3DzJLUEhC+oiK7EISPOwapoEh+7JQJti5YfGXs0YNC62ouC1h9lsrlToClsjc/RM7uSe0kd3EmlzTO/Kqk8Q106mM/Yw2aOB9jnOg6sWTHxJ9FraSJMy6nGz7RbZUDYmN7e3BnQ5Gisez7u3J9c0JwA6Pb0aCFvNObgwKk6NoU59uJwaJ8y1viAT4vCtEFXYO8SFQGtCZpllyXQtNqL+4lmZ/BN/5qJKQFZozEHe9JtAGSaw4wsFnie4JmUQcjleh8yZq0Fnmq3y0D02IzPMgnonYqYIfA4pC+TcXrgIahLB+PEb5s5HrjaR0b7kbHGB0pK7TDO1/T39x1lUZGAPlUH0xTbz+KSoC4dDDx2DQCHzTCaWOB5zjbW+KCSpW0IS0BIJmy6zWCk7WDuxZ4r5oO6dHB7e/sBZo4H2OfUsYOv9jHW+ECJdkAtA/c6MpmMd+XaEKj7km9M4F5TEfBzSKovDLKG1cHobw+b6EDa3WOksYBPAhevBUJMxl8GJTRhFyMLBKSJFn5ls9nvmogS0DfaHOzb3h8AcUuNNBLQNiWa0gRv4MwMMyBwCqxAfCIH82JdYSJKQN+ocjA5NHD2I/e1aj/23iPyhbG6A+bAgXsZoUEII/UAkkQORu71JqIE7o22HBw4VaelpWU74mPPDc/39d1trO5Qb4vJ8QXxbwat06WofcTInMCzeToAtN4VXUn/l1AXDkan9tDSfmL6C81BZooHxDkN9CMveLFZFFAWWZtDwVta3G0sJcAbe3bmYEiniShBXabcL+wflQDD5mD0yKlvk0b/Tk33AG5F7idG+/ibRe54oEl1nLG6A+ZYe1jyAIuG/u2LB3MazxwAfL5vJFGJinxQUwcju6c/n3+FNPm5JhJyy2k/sQTp5nm+2HBJCGi1X1WpwzuBoQXAN+IcjDz8mdePKi/WhH1uxd7GcCjIVBcWpUYDfZ0VbclEJSr2akMBhVrdX6j+Jx3DpSh7vKB8CIiqKwcrcXGqdr05k3RKbU9ryTQVkUB3aHMrEshw7kGCXiv8xxG0h6Uzent6Fpn6MhA17A6GT/3yTxNO1coJbgWur3JFf1fXNuTes5AZe18xXobFHJKv04JZc3O7CtIcgGL9KW03u3QCfL4D4b292dhrpoYgsYOhEz4kaOuHqXKqiagYiN9QnUlyKgX84JUYsQFP9GKzMFRSe8XJb9upE9Dn62CK/KQT75wdTLz+NXgPNdrDuYzeUd0ByN4Wp07n+EdCRZuTY1/ymZQDwIjQye9pA32xdw6IiUgHc639mN8kzCLRjkxzQRzitUpkZ8LZBP1CILUd55EVvdgsCrzJl5i8mgCja+Zgjst4Pq3DUnMmtSWqyNIuQruRU3+CbO08n+pvBAZAjf1IU5kcGJc0YRMBfVV3MPd2RN4+YbvYukI/3sSpe+LUmbw0ryG/6ts1oSLeYrMw6C0xeaFAGc+Wq3hbfeRk582b55lrzf3UHJwWkD0Wp+6BQ3+BfXEXw6UCdHX4TVB0BoJi9Y1Cp59XbUWN8HW7lRjLli3zbINE+1hNiCRI1cGakIhT99ani/A6z1z1nDoUqNQfbO40kyqDfrCBwMg3E5rsCy+8sFlHR8dEnFzRTq/I8hQ9NFFOtGhXVOxgFeUqfknUK7Ctpjl1ANKJ/vmUkvrdwRZmWjpA4J9MTyja2toKY8TQa/ufxP/Whdd5c5cQJHIwfBsTvkKiaqd6/fRyOHKqavdL0H+V2sxmWvrQCAeKItfmQlNyDG/8SVwnetMHyxmA7lm0K2I7GFrlVBW/V6FPP9GqeU4V0Kt2+O2yhctUN6AJBEWD9ngMnessJxh5AfCoQe+8q+xQOYLuWbQrQh2MXP1XYh8S9DKC2sI1z6kCatW3/RCZ6Vj9fNPMqx2wQVNJQlcNEl/mGG5pv48bi7HxMVSOoHsW7QqPg5GlvnJtk6/B9+HMqYUfaXE6rampqWy4dVhgi8FfLprnBXEex+i/wCSkNiSNDSpUxxt7Ccj2nQQYAwUHc9yE3HEotuifDklnfFYMdGNC/lWCxotDf4PvB/jHZTs71c+f2n+ryqCPPcb5/pKdGrTvbH2MUjH4ByOLBDpON9YSFi5cuI1FOwFbbyTox5T6y+iwFL8CqvWvwVtolWgSv/N4sXbl5ZP3r8hRLT50d56KgYJDCYXVhYOhtqqReKDdZuGJtSQSOk8f67x581SspvH3lpoBe9Vefbg/lzveaXmnAf6tEDMNGRp3LnV3ch29o10lQIf+bOKZc+XnmMGARF2EK4vUwQiSw33n7ZlqDWwcaK9Ob29vd26vwj+OT8m3kKFxdd9tlILSJ1Wo8Y8RZT/YiKOY4le5P3SGZJAc7telg7FroL16Jc/n/a1cBBCxsSblwT8LOfofcCh4AQ4x1uoCXZtgVKnYDXLMUECnPSQD29VBcrhfVw7GHrVXb6WylGg0SvUZcrr+YPYuwWVfaE9ltmpA2Q6EQq2UY+yigzf2oqCH4v4MIysD94fdwdig9uqDnB4T5/d+gwHPGNVFcOopyJiPLOfmGTwa0Ek8qS8RKDKORLFWH95utwbDd94SRqqN/Cv4PDXbTFfXfUZWBvRUPJCRBJiIqfnnccy0Dz74wHkWoypY2D4ZGU8gK+kKjQKQ8RcTW1uQI2fmc7nH7LIMFEW+sw6xdyN4CgvNByNIDjp+ZyRVhzlV7dVLaZc7t1cRoW0w9of/No6ptbuRdZupqC3QPZY33HchMkbJiRPssgyaHkN82XaJXPtOJuN+JRuixQI6Cu1VXiZtJehcFGpeNPyXI6cqPWTIvsxU1R7o912akevre4OHfTHot3fEfRbD3y8+Qu0djO5Ce5UXNGl7dTt4z0RGqnOuhgLZgmcPk2FHrrd3jgwkAVQ58e1ioxjcHeMLPWQcq+5gZKm9+hJHjXo5z4xQBQsxxyDjEfir+nNq5GfQo/nYh6f9e4NUgGEFx3DEzvw1nPrOhSJ+kh6GUBUHw6//Kmls96dJ2qv6FxNF9z8g405kVLVXDfkaiFAd4JIkttYUGFpyDOf91Ch/YVEe8DA/gORpuywDfLNMjBOQt4qEupbTPTX4YeJig+/qrnoxkfMeIdH2UHGBfP0H6kFepElc1rY5lBQYXZbzuO7BWYH7b3V3d/+TX1FEG/JSExEJdOi7qsnrx3DuNM8Zdg2NqnN/BjK0EXlVhxORr56wP6Lv/DT+X1FzYLynaOWe2s1TjCQW4An9t6Jk4hBVdH6YpB9YNXoS+SRk/JaQZHd5J2CnesLuyGaze3KZ2hTemoNcpO+uB3pAQuzvC7SeJSfc0258Wo97aX9PT+TmMEMB73jsO0wJzXnVx4llL7pe5kWaFtSqGHHgu6rpPr5jsdx+hyI59G+hA4C25GDO1V69mbf/77h0+lZpzZX44B+Ye1X1cWKz92pKrYlcjtzc6gfN+ufhApd/ErcwTvuTRNI0m4c4Tg77u6gfbCHdTuQcrRFaRKiFU7Xl1O/RqX9RObevRxR43gmEBYUn9wEJIMeF/jk0yVKTta2tE0jg43kx1OatWifEYKDrHYKGDnfkMrU1xHUPaoh7k8i+030EvoV3c6i4aTCoc/9+9NVkFgh6BmZFaig08he3oxYkwBEkQGCzg7gfG6kzaDvuSyLfgIyqt1cF6SAspoS4iJf3c9xaf3JrGEgUzZcOGgvO4agzjTQUkI9V5z4851MuLhBvUUp1gR7tjXEHL+shXFZnduNIBomi6T73FVLLByQePu4N3CxMbVxyzfeQUTYZrdpA3yvoPVf/1jdTGggC6aXx0ieLSecFcWoj72vkhU4IcswU7gVORksb6FHnufbouJ4Xbv+gf1g0EADav9uSeO9YenpA3IfURFVZ0gqEms1rRg0qCzM4TuYy1T061jt0dXXpX0xJ96FMDXIqQXtJ3tSfze6OaY0KU1ogfTUgUJMK0lBIL06dS/F/LJeRe0k2kAAk7BgSWN2GVW/aCOjRuPCbBHVGBG6J3ECKIN3VlfjroguqA+RrMsFvCNqisf5mRox2qPlB4s8vuiMdIE/fVjVvLlRnhKlqYLig7QIpOiva40PAqR2E22neJFrN10AVgWMOIDgPuMOjmRFa+HVaR0fHliaugXoEOe80nBWrZg2dZkZoYffuaW5u1kCVkadmbT70AGdqJodWOhxHqP2eFg1UDvsLatnSFq41M+KKnp6eXbhsdB2OdGiCeX8+/2ecqgnmk/VXNYtqYLSAnNposzpjgw3+H/belpVa8J7TAAAAAElFTkSuQmCC";
  61408. imgBack.style.position = "absolute";
  61409. imgBack.style.left = "50%";
  61410. imgBack.style.top = "50%";
  61411. imgBack.style.marginLeft = "-60px";
  61412. imgBack.style.marginTop = "-60px";
  61413. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  61414. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  61415. imgBack.style.transformOrigin = "50% 50%";
  61416. imgBack.style.webkitTransformOrigin = "50% 50%";
  61417. this._loadingDiv.appendChild(imgBack);
  61418. this._resizeLoadingUI();
  61419. window.addEventListener("resize", this._resizeLoadingUI);
  61420. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  61421. document.body.appendChild(this._loadingDiv);
  61422. this._loadingDiv.style.opacity = "1";
  61423. };
  61424. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  61425. var _this = this;
  61426. if (!this._loadingDiv) {
  61427. return;
  61428. }
  61429. var onTransitionEnd = function () {
  61430. if (!_this._loadingDiv) {
  61431. return;
  61432. }
  61433. document.body.removeChild(_this._loadingDiv);
  61434. window.removeEventListener("resize", _this._resizeLoadingUI);
  61435. _this._loadingDiv = null;
  61436. };
  61437. this._loadingDiv.style.opacity = "0";
  61438. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  61439. };
  61440. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  61441. set: function (text) {
  61442. this._loadingText = text;
  61443. if (this._loadingTextDiv) {
  61444. this._loadingTextDiv.innerHTML = this._loadingText;
  61445. }
  61446. },
  61447. enumerable: true,
  61448. configurable: true
  61449. });
  61450. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  61451. get: function () {
  61452. return this._loadingDivBackgroundColor;
  61453. },
  61454. set: function (color) {
  61455. this._loadingDivBackgroundColor = color;
  61456. if (!this._loadingDiv) {
  61457. return;
  61458. }
  61459. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  61460. },
  61461. enumerable: true,
  61462. configurable: true
  61463. });
  61464. return DefaultLoadingScreen;
  61465. }());
  61466. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  61467. })(BABYLON || (BABYLON = {}));
  61468. //# sourceMappingURL=babylon.loadingScreen.js.map
  61469. var BABYLON;
  61470. (function (BABYLON) {
  61471. var SceneLoaderProgressEvent = /** @class */ (function () {
  61472. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  61473. this.lengthComputable = lengthComputable;
  61474. this.loaded = loaded;
  61475. this.total = total;
  61476. }
  61477. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  61478. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  61479. };
  61480. return SceneLoaderProgressEvent;
  61481. }());
  61482. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  61483. var SceneLoader = /** @class */ (function () {
  61484. function SceneLoader() {
  61485. }
  61486. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  61487. get: function () {
  61488. return 0;
  61489. },
  61490. enumerable: true,
  61491. configurable: true
  61492. });
  61493. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  61494. get: function () {
  61495. return 1;
  61496. },
  61497. enumerable: true,
  61498. configurable: true
  61499. });
  61500. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  61501. get: function () {
  61502. return 2;
  61503. },
  61504. enumerable: true,
  61505. configurable: true
  61506. });
  61507. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  61508. get: function () {
  61509. return 3;
  61510. },
  61511. enumerable: true,
  61512. configurable: true
  61513. });
  61514. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  61515. get: function () {
  61516. return SceneLoader._ForceFullSceneLoadingForIncremental;
  61517. },
  61518. set: function (value) {
  61519. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  61520. },
  61521. enumerable: true,
  61522. configurable: true
  61523. });
  61524. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  61525. get: function () {
  61526. return SceneLoader._ShowLoadingScreen;
  61527. },
  61528. set: function (value) {
  61529. SceneLoader._ShowLoadingScreen = value;
  61530. },
  61531. enumerable: true,
  61532. configurable: true
  61533. });
  61534. Object.defineProperty(SceneLoader, "loggingLevel", {
  61535. get: function () {
  61536. return SceneLoader._loggingLevel;
  61537. },
  61538. set: function (value) {
  61539. SceneLoader._loggingLevel = value;
  61540. },
  61541. enumerable: true,
  61542. configurable: true
  61543. });
  61544. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  61545. get: function () {
  61546. return SceneLoader._CleanBoneMatrixWeights;
  61547. },
  61548. set: function (value) {
  61549. SceneLoader._CleanBoneMatrixWeights = value;
  61550. },
  61551. enumerable: true,
  61552. configurable: true
  61553. });
  61554. SceneLoader._getDefaultPlugin = function () {
  61555. return SceneLoader._registeredPlugins[".babylon"];
  61556. };
  61557. SceneLoader._getPluginForExtension = function (extension) {
  61558. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  61559. if (registeredPlugin) {
  61560. return registeredPlugin;
  61561. }
  61562. BABYLON.Tools.Warn("Unable to find a plugin to load " + extension + " files. Trying to use .babylon default plugin.");
  61563. return SceneLoader._getDefaultPlugin();
  61564. };
  61565. SceneLoader._getPluginForDirectLoad = function (data) {
  61566. for (var extension in SceneLoader._registeredPlugins) {
  61567. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  61568. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  61569. return SceneLoader._registeredPlugins[extension];
  61570. }
  61571. }
  61572. return SceneLoader._getDefaultPlugin();
  61573. };
  61574. SceneLoader._getPluginForFilename = function (sceneFilename) {
  61575. if (sceneFilename.name) {
  61576. sceneFilename = sceneFilename.name;
  61577. }
  61578. var queryStringPosition = sceneFilename.indexOf("?");
  61579. if (queryStringPosition !== -1) {
  61580. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  61581. }
  61582. var dotPosition = sceneFilename.lastIndexOf(".");
  61583. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  61584. return SceneLoader._getPluginForExtension(extension);
  61585. };
  61586. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  61587. SceneLoader._getDirectLoad = function (sceneFilename) {
  61588. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  61589. return sceneFilename.substr(5);
  61590. }
  61591. return null;
  61592. };
  61593. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  61594. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  61595. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  61596. var plugin;
  61597. if (registeredPlugin.plugin.createPlugin) {
  61598. plugin = registeredPlugin.plugin.createPlugin();
  61599. }
  61600. else {
  61601. plugin = registeredPlugin.plugin;
  61602. }
  61603. var useArrayBuffer = registeredPlugin.isBinary;
  61604. var database;
  61605. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  61606. var dataCallback = function (data, responseURL) {
  61607. if (scene.isDisposed) {
  61608. onError("Scene has been disposed");
  61609. return;
  61610. }
  61611. scene.database = database;
  61612. onSuccess(plugin, data, responseURL);
  61613. };
  61614. var request = null;
  61615. var pluginDisposed = false;
  61616. var onDisposeObservable = plugin.onDisposeObservable;
  61617. if (onDisposeObservable) {
  61618. onDisposeObservable.add(function () {
  61619. pluginDisposed = true;
  61620. if (request) {
  61621. request.abort();
  61622. request = null;
  61623. }
  61624. onDispose();
  61625. });
  61626. }
  61627. var manifestChecked = function () {
  61628. if (pluginDisposed) {
  61629. return;
  61630. }
  61631. var url = rootUrl + sceneFilename;
  61632. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  61633. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  61634. } : undefined, database, useArrayBuffer, function (request, exception) {
  61635. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  61636. });
  61637. };
  61638. if (directLoad) {
  61639. dataCallback(directLoad);
  61640. return plugin;
  61641. }
  61642. if (rootUrl.indexOf("file:") === -1) {
  61643. if (scene.getEngine().enableOfflineSupport) {
  61644. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  61645. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  61646. }
  61647. else {
  61648. manifestChecked();
  61649. }
  61650. }
  61651. else {
  61652. var fileOrString = sceneFilename;
  61653. if (fileOrString.name) {
  61654. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  61655. }
  61656. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  61657. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  61658. }
  61659. else {
  61660. onError("Unable to find file named " + sceneFilename);
  61661. }
  61662. }
  61663. return plugin;
  61664. };
  61665. // Public functions
  61666. SceneLoader.GetPluginForExtension = function (extension) {
  61667. return SceneLoader._getPluginForExtension(extension).plugin;
  61668. };
  61669. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  61670. return !!SceneLoader._registeredPlugins[extension];
  61671. };
  61672. SceneLoader.RegisterPlugin = function (plugin) {
  61673. if (typeof plugin.extensions === "string") {
  61674. var extension = plugin.extensions;
  61675. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  61676. plugin: plugin,
  61677. isBinary: false
  61678. };
  61679. }
  61680. else {
  61681. var extensions = plugin.extensions;
  61682. Object.keys(extensions).forEach(function (extension) {
  61683. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  61684. plugin: plugin,
  61685. isBinary: extensions[extension].isBinary
  61686. };
  61687. });
  61688. }
  61689. };
  61690. /**
  61691. * Import meshes into a scene
  61692. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  61693. * @param rootUrl a string that defines the root url for scene and resources
  61694. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  61695. * @param scene the instance of BABYLON.Scene to append to
  61696. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  61697. * @param onProgress a callback with a progress event for each file being loaded
  61698. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  61699. * @param pluginExtension the extension used to determine the plugin
  61700. * @returns The loaded plugin
  61701. */
  61702. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  61703. if (onSuccess === void 0) { onSuccess = null; }
  61704. if (onProgress === void 0) { onProgress = null; }
  61705. if (onError === void 0) { onError = null; }
  61706. if (pluginExtension === void 0) { pluginExtension = null; }
  61707. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  61708. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  61709. return null;
  61710. }
  61711. var loadingToken = {};
  61712. scene._addPendingData(loadingToken);
  61713. var disposeHandler = function () {
  61714. scene._removePendingData(loadingToken);
  61715. };
  61716. var errorHandler = function (message, exception) {
  61717. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  61718. if (onError) {
  61719. onError(scene, errorMessage, exception);
  61720. }
  61721. else {
  61722. BABYLON.Tools.Error(errorMessage);
  61723. // should the exception be thrown?
  61724. }
  61725. disposeHandler();
  61726. };
  61727. var progressHandler = onProgress ? function (event) {
  61728. try {
  61729. onProgress(event);
  61730. }
  61731. catch (e) {
  61732. errorHandler("Error in onProgress callback", e);
  61733. }
  61734. } : undefined;
  61735. var successHandler = function (meshes, particleSystems, skeletons) {
  61736. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  61737. if (onSuccess) {
  61738. try {
  61739. onSuccess(meshes, particleSystems, skeletons);
  61740. }
  61741. catch (e) {
  61742. errorHandler("Error in onSuccess callback", e);
  61743. }
  61744. }
  61745. scene._removePendingData(loadingToken);
  61746. };
  61747. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  61748. if (plugin.rewriteRootURL) {
  61749. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  61750. }
  61751. if (sceneFilename === "") {
  61752. if (sceneFilename === "") {
  61753. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  61754. }
  61755. }
  61756. if (plugin.importMesh) {
  61757. var syncedPlugin = plugin;
  61758. var meshes = new Array();
  61759. var particleSystems = new Array();
  61760. var skeletons = new Array();
  61761. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  61762. return;
  61763. }
  61764. scene.loadingPluginName = plugin.name;
  61765. successHandler(meshes, particleSystems, skeletons);
  61766. }
  61767. else {
  61768. var asyncedPlugin = plugin;
  61769. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, progressHandler).then(function (result) {
  61770. scene.loadingPluginName = plugin.name;
  61771. successHandler(result.meshes, result.particleSystems, result.skeletons);
  61772. }).catch(function (error) {
  61773. errorHandler(error.message, error);
  61774. });
  61775. }
  61776. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  61777. };
  61778. /**
  61779. * Import meshes into a scene
  61780. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  61781. * @param rootUrl a string that defines the root url for scene and resources
  61782. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  61783. * @param scene the instance of BABYLON.Scene to append to
  61784. * @param onProgress a callback with a progress event for each file being loaded
  61785. * @param pluginExtension the extension used to determine the plugin
  61786. * @returns The loaded list of imported meshes, particleSystems, and skeletons
  61787. */
  61788. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  61789. if (onProgress === void 0) { onProgress = null; }
  61790. if (pluginExtension === void 0) { pluginExtension = null; }
  61791. return new Promise(function (resolve, reject) {
  61792. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  61793. resolve({
  61794. meshes: meshes,
  61795. particleSystems: particleSystems,
  61796. skeletons: skeletons
  61797. });
  61798. }, onProgress, function (scene, message, exception) {
  61799. reject(exception || new Error(message));
  61800. });
  61801. });
  61802. };
  61803. /**
  61804. * Load a scene
  61805. * @param rootUrl a string that defines the root url for scene and resources
  61806. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  61807. * @param engine is the instance of BABYLON.Engine to use to create the scene
  61808. * @param onSuccess a callback with the scene when import succeeds
  61809. * @param onProgress a callback with a progress event for each file being loaded
  61810. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  61811. * @param pluginExtension the extension used to determine the plugin
  61812. * @returns The loaded plugin
  61813. */
  61814. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  61815. if (onSuccess === void 0) { onSuccess = null; }
  61816. if (onProgress === void 0) { onProgress = null; }
  61817. if (onError === void 0) { onError = null; }
  61818. if (pluginExtension === void 0) { pluginExtension = null; }
  61819. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  61820. };
  61821. /**
  61822. * Load a scene
  61823. * @param rootUrl a string that defines the root url for scene and resources
  61824. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  61825. * @param engine is the instance of BABYLON.Engine to use to create the scene
  61826. * @param onProgress a callback with a progress event for each file being loaded
  61827. * @param pluginExtension the extension used to determine the plugin
  61828. * @returns The loaded scene
  61829. */
  61830. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  61831. if (onProgress === void 0) { onProgress = null; }
  61832. if (pluginExtension === void 0) { pluginExtension = null; }
  61833. return new Promise(function (resolve, reject) {
  61834. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  61835. resolve(scene);
  61836. }, onProgress, function (scene, message, exception) {
  61837. reject(exception || new Error(message));
  61838. }, pluginExtension);
  61839. });
  61840. };
  61841. /**
  61842. * Append a scene
  61843. * @param rootUrl a string that defines the root url for scene and resources
  61844. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  61845. * @param scene is the instance of BABYLON.Scene to append to
  61846. * @param onSuccess a callback with the scene when import succeeds
  61847. * @param onProgress a callback with a progress event for each file being loaded
  61848. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  61849. * @param pluginExtension the extension used to determine the plugin
  61850. * @returns The loaded plugin
  61851. */
  61852. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  61853. if (onSuccess === void 0) { onSuccess = null; }
  61854. if (onProgress === void 0) { onProgress = null; }
  61855. if (onError === void 0) { onError = null; }
  61856. if (pluginExtension === void 0) { pluginExtension = null; }
  61857. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  61858. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  61859. return null;
  61860. }
  61861. if (SceneLoader.ShowLoadingScreen) {
  61862. scene.getEngine().displayLoadingUI();
  61863. }
  61864. var loadingToken = {};
  61865. scene._addPendingData(loadingToken);
  61866. var disposeHandler = function () {
  61867. scene._removePendingData(loadingToken);
  61868. scene.getEngine().hideLoadingUI();
  61869. };
  61870. var errorHandler = function (message, exception) {
  61871. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  61872. if (onError) {
  61873. onError(scene, errorMessage, exception);
  61874. }
  61875. else {
  61876. BABYLON.Tools.Error(errorMessage);
  61877. // should the exception be thrown?
  61878. }
  61879. disposeHandler();
  61880. };
  61881. var progressHandler = onProgress ? function (event) {
  61882. try {
  61883. onProgress(event);
  61884. }
  61885. catch (e) {
  61886. errorHandler("Error in onProgress callback", e);
  61887. }
  61888. } : undefined;
  61889. var successHandler = function () {
  61890. if (onSuccess) {
  61891. try {
  61892. onSuccess(scene);
  61893. }
  61894. catch (e) {
  61895. errorHandler("Error in onSuccess callback", e);
  61896. }
  61897. }
  61898. scene._removePendingData(loadingToken);
  61899. };
  61900. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  61901. if (sceneFilename === "") {
  61902. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  61903. }
  61904. if (plugin.load) {
  61905. var syncedPlugin = plugin;
  61906. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  61907. return;
  61908. }
  61909. scene.loadingPluginName = plugin.name;
  61910. successHandler();
  61911. }
  61912. else {
  61913. var asyncedPlugin = plugin;
  61914. asyncedPlugin.loadAsync(scene, data, rootUrl, progressHandler).then(function () {
  61915. scene.loadingPluginName = plugin.name;
  61916. successHandler();
  61917. }).catch(function (error) {
  61918. errorHandler(error.message, error);
  61919. });
  61920. }
  61921. if (SceneLoader.ShowLoadingScreen) {
  61922. scene.executeWhenReady(function () {
  61923. scene.getEngine().hideLoadingUI();
  61924. });
  61925. }
  61926. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  61927. };
  61928. /**
  61929. * Append a scene
  61930. * @param rootUrl a string that defines the root url for scene and resources
  61931. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  61932. * @param scene is the instance of BABYLON.Scene to append to
  61933. * @param onProgress a callback with a progress event for each file being loaded
  61934. * @param pluginExtension the extension used to determine the plugin
  61935. * @returns The given scene
  61936. */
  61937. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  61938. if (onProgress === void 0) { onProgress = null; }
  61939. if (pluginExtension === void 0) { pluginExtension = null; }
  61940. return new Promise(function (resolve, reject) {
  61941. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  61942. resolve(scene);
  61943. }, onProgress, function (scene, message, exception) {
  61944. reject(exception || new Error(message));
  61945. }, pluginExtension);
  61946. });
  61947. };
  61948. /**
  61949. * Load a scene into an asset container
  61950. * @param rootUrl a string that defines the root url for scene and resources
  61951. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  61952. * @param scene is the instance of BABYLON.Scene to append to
  61953. * @param onSuccess a callback with the scene when import succeeds
  61954. * @param onProgress a callback with a progress event for each file being loaded
  61955. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  61956. * @param pluginExtension the extension used to determine the plugin
  61957. * @returns The loaded plugin
  61958. */
  61959. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  61960. if (onSuccess === void 0) { onSuccess = null; }
  61961. if (onProgress === void 0) { onProgress = null; }
  61962. if (onError === void 0) { onError = null; }
  61963. if (pluginExtension === void 0) { pluginExtension = null; }
  61964. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  61965. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  61966. return null;
  61967. }
  61968. var loadingToken = {};
  61969. scene._addPendingData(loadingToken);
  61970. var disposeHandler = function () {
  61971. scene._removePendingData(loadingToken);
  61972. };
  61973. var errorHandler = function (message, exception) {
  61974. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  61975. if (onError) {
  61976. onError(scene, errorMessage, exception);
  61977. }
  61978. else {
  61979. BABYLON.Tools.Error(errorMessage);
  61980. // should the exception be thrown?
  61981. }
  61982. disposeHandler();
  61983. };
  61984. var progressHandler = onProgress ? function (event) {
  61985. try {
  61986. onProgress(event);
  61987. }
  61988. catch (e) {
  61989. errorHandler("Error in onProgress callback", e);
  61990. }
  61991. } : undefined;
  61992. var successHandler = function (assets) {
  61993. if (onSuccess) {
  61994. try {
  61995. onSuccess(assets);
  61996. }
  61997. catch (e) {
  61998. errorHandler("Error in onSuccess callback", e);
  61999. }
  62000. }
  62001. scene._removePendingData(loadingToken);
  62002. };
  62003. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  62004. if (plugin.loadAssetContainer) {
  62005. var syncedPlugin = plugin;
  62006. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, rootUrl, errorHandler);
  62007. if (!assetContainer) {
  62008. return;
  62009. }
  62010. scene.loadingPluginName = plugin.name;
  62011. successHandler(assetContainer);
  62012. }
  62013. else if (plugin.loadAssetContainerAsync) {
  62014. var asyncedPlugin = plugin;
  62015. asyncedPlugin.loadAssetContainerAsync(scene, data, rootUrl, progressHandler).then(function (assetContainer) {
  62016. scene.loadingPluginName = plugin.name;
  62017. successHandler(assetContainer);
  62018. }).catch(function (error) {
  62019. errorHandler(error.message, error);
  62020. });
  62021. }
  62022. else {
  62023. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  62024. }
  62025. if (SceneLoader.ShowLoadingScreen) {
  62026. scene.executeWhenReady(function () {
  62027. scene.getEngine().hideLoadingUI();
  62028. });
  62029. }
  62030. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  62031. };
  62032. /**
  62033. * Load a scene into an asset container
  62034. * @param rootUrl a string that defines the root url for scene and resources
  62035. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  62036. * @param scene is the instance of BABYLON.Scene to append to
  62037. * @param onProgress a callback with a progress event for each file being loaded
  62038. * @param pluginExtension the extension used to determine the plugin
  62039. * @returns The loaded asset container
  62040. */
  62041. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  62042. if (onProgress === void 0) { onProgress = null; }
  62043. if (pluginExtension === void 0) { pluginExtension = null; }
  62044. return new Promise(function (resolve, reject) {
  62045. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  62046. resolve(assetContainer);
  62047. }, onProgress, function (scene, message, exception) {
  62048. reject(exception || new Error(message));
  62049. }, pluginExtension);
  62050. });
  62051. };
  62052. // Flags
  62053. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  62054. SceneLoader._ShowLoadingScreen = true;
  62055. SceneLoader._CleanBoneMatrixWeights = false;
  62056. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  62057. // Members
  62058. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  62059. SceneLoader._registeredPlugins = {};
  62060. return SceneLoader;
  62061. }());
  62062. BABYLON.SceneLoader = SceneLoader;
  62063. ;
  62064. })(BABYLON || (BABYLON = {}));
  62065. //# sourceMappingURL=babylon.sceneLoader.js.map
  62066. var BABYLON;
  62067. (function (BABYLON) {
  62068. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  62069. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  62070. var parsedMaterial = parsedData.materials[index];
  62071. if (parsedMaterial.id === id) {
  62072. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  62073. }
  62074. }
  62075. return null;
  62076. };
  62077. var isDescendantOf = function (mesh, names, hierarchyIds) {
  62078. for (var i in names) {
  62079. if (mesh.name === names[i]) {
  62080. hierarchyIds.push(mesh.id);
  62081. return true;
  62082. }
  62083. }
  62084. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  62085. hierarchyIds.push(mesh.id);
  62086. return true;
  62087. }
  62088. return false;
  62089. };
  62090. var logOperation = function (operation, producer) {
  62091. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  62092. };
  62093. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  62094. if (addToScene === void 0) { addToScene = false; }
  62095. var container = new BABYLON.AssetContainer(scene);
  62096. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  62097. // when SceneLoader.debugLogging = true (default), or exception encountered.
  62098. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  62099. // and avoid problems with multiple concurrent .babylon loads.
  62100. var log = "importScene has failed JSON parse";
  62101. try {
  62102. var parsedData = JSON.parse(data);
  62103. log = "";
  62104. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  62105. var index;
  62106. var cache;
  62107. // Lights
  62108. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  62109. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  62110. var parsedLight = parsedData.lights[index];
  62111. var light = BABYLON.Light.Parse(parsedLight, scene);
  62112. if (light) {
  62113. container.lights.push(light);
  62114. log += (index === 0 ? "\n\tLights:" : "");
  62115. log += "\n\t\t" + light.toString(fullDetails);
  62116. }
  62117. }
  62118. }
  62119. // Animations
  62120. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  62121. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  62122. var parsedAnimation = parsedData.animations[index];
  62123. var animation = BABYLON.Animation.Parse(parsedAnimation);
  62124. scene.animations.push(animation);
  62125. container.animations.push(animation);
  62126. log += (index === 0 ? "\n\tAnimations:" : "");
  62127. log += "\n\t\t" + animation.toString(fullDetails);
  62128. }
  62129. }
  62130. // Materials
  62131. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  62132. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  62133. var parsedMaterial = parsedData.materials[index];
  62134. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  62135. container.materials.push(mat);
  62136. log += (index === 0 ? "\n\tMaterials:" : "");
  62137. log += "\n\t\t" + mat.toString(fullDetails);
  62138. }
  62139. }
  62140. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  62141. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  62142. var parsedMultiMaterial = parsedData.multiMaterials[index];
  62143. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  62144. container.multiMaterials.push(mmat);
  62145. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  62146. log += "\n\t\t" + mmat.toString(fullDetails);
  62147. }
  62148. }
  62149. // Morph targets
  62150. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  62151. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  62152. var managerData = _a[_i];
  62153. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  62154. }
  62155. }
  62156. // Skeletons
  62157. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  62158. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  62159. var parsedSkeleton = parsedData.skeletons[index];
  62160. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  62161. container.skeletons.push(skeleton);
  62162. log += (index === 0 ? "\n\tSkeletons:" : "");
  62163. log += "\n\t\t" + skeleton.toString(fullDetails);
  62164. }
  62165. }
  62166. // Geometries
  62167. var geometries = parsedData.geometries;
  62168. if (geometries !== undefined && geometries !== null) {
  62169. var addedGeometry = new Array();
  62170. // Boxes
  62171. var boxes = geometries.boxes;
  62172. if (boxes !== undefined && boxes !== null) {
  62173. for (index = 0, cache = boxes.length; index < cache; index++) {
  62174. var parsedBox = boxes[index];
  62175. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  62176. }
  62177. }
  62178. // Spheres
  62179. var spheres = geometries.spheres;
  62180. if (spheres !== undefined && spheres !== null) {
  62181. for (index = 0, cache = spheres.length; index < cache; index++) {
  62182. var parsedSphere = spheres[index];
  62183. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  62184. }
  62185. }
  62186. // Cylinders
  62187. var cylinders = geometries.cylinders;
  62188. if (cylinders !== undefined && cylinders !== null) {
  62189. for (index = 0, cache = cylinders.length; index < cache; index++) {
  62190. var parsedCylinder = cylinders[index];
  62191. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  62192. }
  62193. }
  62194. // Toruses
  62195. var toruses = geometries.toruses;
  62196. if (toruses !== undefined && toruses !== null) {
  62197. for (index = 0, cache = toruses.length; index < cache; index++) {
  62198. var parsedTorus = toruses[index];
  62199. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  62200. }
  62201. }
  62202. // Grounds
  62203. var grounds = geometries.grounds;
  62204. if (grounds !== undefined && grounds !== null) {
  62205. for (index = 0, cache = grounds.length; index < cache; index++) {
  62206. var parsedGround = grounds[index];
  62207. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  62208. }
  62209. }
  62210. // Planes
  62211. var planes = geometries.planes;
  62212. if (planes !== undefined && planes !== null) {
  62213. for (index = 0, cache = planes.length; index < cache; index++) {
  62214. var parsedPlane = planes[index];
  62215. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  62216. }
  62217. }
  62218. // TorusKnots
  62219. var torusKnots = geometries.torusKnots;
  62220. if (torusKnots !== undefined && torusKnots !== null) {
  62221. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  62222. var parsedTorusKnot = torusKnots[index];
  62223. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  62224. }
  62225. }
  62226. // VertexData
  62227. var vertexData = geometries.vertexData;
  62228. if (vertexData !== undefined && vertexData !== null) {
  62229. for (index = 0, cache = vertexData.length; index < cache; index++) {
  62230. var parsedVertexData = vertexData[index];
  62231. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  62232. }
  62233. }
  62234. addedGeometry.forEach(function (g) {
  62235. if (g) {
  62236. container.geometries.push(g);
  62237. }
  62238. });
  62239. }
  62240. // Transform nodes
  62241. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  62242. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  62243. var parsedTransformNode = parsedData.transformNodes[index];
  62244. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  62245. container.transformNodes.push(node);
  62246. }
  62247. }
  62248. // Meshes
  62249. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  62250. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  62251. var parsedMesh = parsedData.meshes[index];
  62252. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  62253. container.meshes.push(mesh);
  62254. log += (index === 0 ? "\n\tMeshes:" : "");
  62255. log += "\n\t\t" + mesh.toString(fullDetails);
  62256. }
  62257. }
  62258. // Cameras
  62259. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  62260. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  62261. var parsedCamera = parsedData.cameras[index];
  62262. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  62263. container.cameras.push(camera);
  62264. log += (index === 0 ? "\n\tCameras:" : "");
  62265. log += "\n\t\t" + camera.toString(fullDetails);
  62266. }
  62267. }
  62268. // Browsing all the graph to connect the dots
  62269. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  62270. var camera = scene.cameras[index];
  62271. if (camera._waitingParentId) {
  62272. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  62273. camera._waitingParentId = null;
  62274. }
  62275. }
  62276. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  62277. var light_1 = scene.lights[index];
  62278. if (light_1 && light_1._waitingParentId) {
  62279. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  62280. light_1._waitingParentId = null;
  62281. }
  62282. }
  62283. // Sounds
  62284. // TODO: add sound
  62285. var loadedSounds = [];
  62286. var loadedSound;
  62287. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  62288. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  62289. var parsedSound = parsedData.sounds[index];
  62290. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62291. if (!parsedSound.url)
  62292. parsedSound.url = parsedSound.name;
  62293. if (!loadedSounds[parsedSound.url]) {
  62294. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  62295. loadedSounds[parsedSound.url] = loadedSound;
  62296. container.sounds.push(loadedSound);
  62297. }
  62298. else {
  62299. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  62300. }
  62301. }
  62302. else {
  62303. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  62304. }
  62305. }
  62306. }
  62307. loadedSounds = [];
  62308. // Connect parents & children and parse actions
  62309. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  62310. var transformNode = scene.transformNodes[index];
  62311. if (transformNode._waitingParentId) {
  62312. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  62313. transformNode._waitingParentId = null;
  62314. }
  62315. }
  62316. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  62317. var mesh = scene.meshes[index];
  62318. if (mesh._waitingParentId) {
  62319. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  62320. mesh._waitingParentId = null;
  62321. }
  62322. if (mesh._waitingActions) {
  62323. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  62324. mesh._waitingActions = null;
  62325. }
  62326. }
  62327. // freeze world matrix application
  62328. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  62329. var currentMesh = scene.meshes[index];
  62330. if (currentMesh._waitingFreezeWorldMatrix) {
  62331. currentMesh.freezeWorldMatrix();
  62332. currentMesh._waitingFreezeWorldMatrix = null;
  62333. }
  62334. else {
  62335. currentMesh.computeWorldMatrix(true);
  62336. }
  62337. }
  62338. // Particles Systems
  62339. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  62340. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  62341. var parsedParticleSystem = parsedData.particleSystems[index];
  62342. if (parsedParticleSystem.activeParticleCount) {
  62343. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  62344. container.particleSystems.push(ps);
  62345. }
  62346. else {
  62347. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  62348. container.particleSystems.push(ps);
  62349. }
  62350. }
  62351. }
  62352. // Lens flares
  62353. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  62354. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  62355. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  62356. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  62357. container.lensFlareSystems.push(lf);
  62358. }
  62359. }
  62360. // Shadows
  62361. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  62362. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  62363. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  62364. var sg = BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  62365. container.shadowGenerators.push(sg);
  62366. }
  62367. }
  62368. // Lights exclusions / inclusions
  62369. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  62370. var light_2 = scene.lights[index];
  62371. // Excluded check
  62372. if (light_2._excludedMeshesIds.length > 0) {
  62373. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  62374. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  62375. if (excludedMesh) {
  62376. light_2.excludedMeshes.push(excludedMesh);
  62377. }
  62378. }
  62379. light_2._excludedMeshesIds = [];
  62380. }
  62381. // Included check
  62382. if (light_2._includedOnlyMeshesIds.length > 0) {
  62383. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  62384. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  62385. if (includedOnlyMesh) {
  62386. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  62387. }
  62388. }
  62389. light_2._includedOnlyMeshesIds = [];
  62390. }
  62391. }
  62392. // Actions (scene)
  62393. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  62394. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  62395. }
  62396. if (!addToScene) {
  62397. container.removeAllFromScene();
  62398. }
  62399. }
  62400. catch (err) {
  62401. var msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
  62402. if (onError) {
  62403. onError(msg, err);
  62404. }
  62405. else {
  62406. BABYLON.Tools.Log(msg);
  62407. throw err;
  62408. }
  62409. }
  62410. finally {
  62411. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  62412. BABYLON.Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  62413. }
  62414. }
  62415. return container;
  62416. };
  62417. BABYLON.SceneLoader.RegisterPlugin({
  62418. name: "babylon.js",
  62419. extensions: ".babylon",
  62420. canDirectLoad: function (data) {
  62421. if (data.indexOf("babylon") !== -1) {
  62422. return true;
  62423. }
  62424. return false;
  62425. },
  62426. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  62427. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  62428. // when SceneLoader.debugLogging = true (default), or exception encountered.
  62429. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  62430. // and avoid problems with multiple concurrent .babylon loads.
  62431. var log = "importMesh has failed JSON parse";
  62432. try {
  62433. var parsedData = JSON.parse(data);
  62434. log = "";
  62435. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  62436. if (!meshesNames) {
  62437. meshesNames = null;
  62438. }
  62439. else if (!Array.isArray(meshesNames)) {
  62440. meshesNames = [meshesNames];
  62441. }
  62442. var hierarchyIds = new Array();
  62443. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  62444. var loadedSkeletonsIds = [];
  62445. var loadedMaterialsIds = [];
  62446. var index;
  62447. var cache;
  62448. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  62449. var parsedMesh = parsedData.meshes[index];
  62450. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  62451. if (meshesNames !== null) {
  62452. // Remove found mesh name from list.
  62453. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  62454. }
  62455. //Geometry?
  62456. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  62457. //does the file contain geometries?
  62458. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  62459. //find the correct geometry and add it to the scene
  62460. var found = false;
  62461. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  62462. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  62463. return;
  62464. }
  62465. else {
  62466. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  62467. if (parsedGeometryData.id === parsedMesh.geometryId) {
  62468. switch (geometryType) {
  62469. case "boxes":
  62470. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  62471. break;
  62472. case "spheres":
  62473. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  62474. break;
  62475. case "cylinders":
  62476. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  62477. break;
  62478. case "toruses":
  62479. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  62480. break;
  62481. case "grounds":
  62482. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  62483. break;
  62484. case "planes":
  62485. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  62486. break;
  62487. case "torusKnots":
  62488. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  62489. break;
  62490. case "vertexData":
  62491. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  62492. break;
  62493. }
  62494. found = true;
  62495. }
  62496. });
  62497. }
  62498. });
  62499. if (found === false) {
  62500. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  62501. }
  62502. }
  62503. }
  62504. // Material ?
  62505. if (parsedMesh.materialId) {
  62506. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  62507. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  62508. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  62509. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  62510. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  62511. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  62512. var subMatId = parsedMultiMaterial.materials[matIndex];
  62513. loadedMaterialsIds.push(subMatId);
  62514. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  62515. if (mat) {
  62516. log += "\n\tMaterial " + mat.toString(fullDetails);
  62517. }
  62518. }
  62519. loadedMaterialsIds.push(parsedMultiMaterial.id);
  62520. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  62521. if (mmat) {
  62522. materialFound = true;
  62523. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  62524. }
  62525. break;
  62526. }
  62527. }
  62528. }
  62529. if (materialFound === false) {
  62530. loadedMaterialsIds.push(parsedMesh.materialId);
  62531. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  62532. if (!mat) {
  62533. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  62534. }
  62535. else {
  62536. log += "\n\tMaterial " + mat.toString(fullDetails);
  62537. }
  62538. }
  62539. }
  62540. // Skeleton ?
  62541. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  62542. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  62543. if (skeletonAlreadyLoaded === false) {
  62544. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  62545. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  62546. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  62547. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  62548. skeletons.push(skeleton);
  62549. loadedSkeletonsIds.push(parsedSkeleton.id);
  62550. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  62551. }
  62552. }
  62553. }
  62554. }
  62555. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  62556. meshes.push(mesh);
  62557. log += "\n\tMesh " + mesh.toString(fullDetails);
  62558. }
  62559. }
  62560. // Connecting parents
  62561. var currentMesh;
  62562. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  62563. currentMesh = scene.meshes[index];
  62564. if (currentMesh._waitingParentId) {
  62565. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  62566. currentMesh._waitingParentId = null;
  62567. }
  62568. }
  62569. // freeze and compute world matrix application
  62570. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  62571. currentMesh = scene.meshes[index];
  62572. if (currentMesh._waitingFreezeWorldMatrix) {
  62573. currentMesh.freezeWorldMatrix();
  62574. currentMesh._waitingFreezeWorldMatrix = null;
  62575. }
  62576. else {
  62577. currentMesh.computeWorldMatrix(true);
  62578. }
  62579. }
  62580. }
  62581. // Particles
  62582. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  62583. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  62584. var parsedParticleSystem = parsedData.particleSystems[index];
  62585. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  62586. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  62587. }
  62588. }
  62589. }
  62590. return true;
  62591. }
  62592. catch (err) {
  62593. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  62594. if (onError) {
  62595. onError(msg, err);
  62596. }
  62597. else {
  62598. BABYLON.Tools.Log(msg);
  62599. throw err;
  62600. }
  62601. }
  62602. finally {
  62603. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  62604. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  62605. }
  62606. }
  62607. return false;
  62608. },
  62609. load: function (scene, data, rootUrl, onError) {
  62610. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  62611. // when SceneLoader.debugLogging = true (default), or exception encountered.
  62612. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  62613. // and avoid problems with multiple concurrent .babylon loads.
  62614. var log = "importScene has failed JSON parse";
  62615. try {
  62616. var parsedData = JSON.parse(data);
  62617. log = "";
  62618. // Scene
  62619. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  62620. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  62621. }
  62622. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  62623. scene.autoClear = parsedData.autoClear;
  62624. }
  62625. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  62626. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  62627. }
  62628. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  62629. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  62630. }
  62631. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  62632. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  62633. }
  62634. // Fog
  62635. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  62636. scene.fogMode = parsedData.fogMode;
  62637. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  62638. scene.fogStart = parsedData.fogStart;
  62639. scene.fogEnd = parsedData.fogEnd;
  62640. scene.fogDensity = parsedData.fogDensity;
  62641. log += "\tFog mode for scene: ";
  62642. switch (scene.fogMode) {
  62643. // getters not compiling, so using hardcoded
  62644. case 1:
  62645. log += "exp\n";
  62646. break;
  62647. case 2:
  62648. log += "exp2\n";
  62649. break;
  62650. case 3:
  62651. log += "linear\n";
  62652. break;
  62653. }
  62654. }
  62655. //Physics
  62656. if (parsedData.physicsEnabled) {
  62657. var physicsPlugin;
  62658. if (parsedData.physicsEngine === "cannon") {
  62659. physicsPlugin = new BABYLON.CannonJSPlugin();
  62660. }
  62661. else if (parsedData.physicsEngine === "oimo") {
  62662. physicsPlugin = new BABYLON.OimoJSPlugin();
  62663. }
  62664. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  62665. //else - default engine, which is currently oimo
  62666. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  62667. scene.enablePhysics(physicsGravity, physicsPlugin);
  62668. }
  62669. // Metadata
  62670. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  62671. scene.metadata = parsedData.metadata;
  62672. }
  62673. //collisions, if defined. otherwise, default is true
  62674. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  62675. scene.collisionsEnabled = parsedData.collisionsEnabled;
  62676. }
  62677. scene.workerCollisions = !!parsedData.workerCollisions;
  62678. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  62679. if (!container) {
  62680. return false;
  62681. }
  62682. if (parsedData.autoAnimate) {
  62683. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  62684. }
  62685. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  62686. scene.setActiveCameraByID(parsedData.activeCameraID);
  62687. }
  62688. // Environment texture
  62689. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  62690. scene.environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  62691. if (parsedData.createDefaultSkybox === true) {
  62692. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  62693. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  62694. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  62695. }
  62696. }
  62697. // Finish
  62698. return true;
  62699. }
  62700. catch (err) {
  62701. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  62702. if (onError) {
  62703. onError(msg, err);
  62704. }
  62705. else {
  62706. BABYLON.Tools.Log(msg);
  62707. throw err;
  62708. }
  62709. }
  62710. finally {
  62711. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  62712. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  62713. }
  62714. }
  62715. return false;
  62716. },
  62717. loadAssetContainer: function (scene, data, rootUrl, onError) {
  62718. var container = loadAssetContainer(scene, data, rootUrl, onError);
  62719. return container;
  62720. }
  62721. });
  62722. })(BABYLON || (BABYLON = {}));
  62723. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  62724. var BABYLON;
  62725. (function (BABYLON) {
  62726. var FilesInput = /** @class */ (function () {
  62727. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  62728. this.onProcessFileCallback = function () { return true; };
  62729. this._engine = engine;
  62730. this._currentScene = scene;
  62731. this._sceneLoadedCallback = sceneLoadedCallback;
  62732. this._progressCallback = progressCallback;
  62733. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  62734. this._textureLoadingCallback = textureLoadingCallback;
  62735. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  62736. this._onReloadCallback = onReloadCallback;
  62737. this._errorCallback = errorCallback;
  62738. }
  62739. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  62740. var _this = this;
  62741. if (elementToMonitor) {
  62742. this._elementToMonitor = elementToMonitor;
  62743. this._dragEnterHandler = function (e) { _this.drag(e); };
  62744. this._dragOverHandler = function (e) { _this.drag(e); };
  62745. this._dropHandler = function (e) { _this.drop(e); };
  62746. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  62747. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  62748. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  62749. }
  62750. };
  62751. FilesInput.prototype.dispose = function () {
  62752. if (!this._elementToMonitor) {
  62753. return;
  62754. }
  62755. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  62756. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  62757. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  62758. };
  62759. FilesInput.prototype.renderFunction = function () {
  62760. if (this._additionalRenderLoopLogicCallback) {
  62761. this._additionalRenderLoopLogicCallback();
  62762. }
  62763. if (this._currentScene) {
  62764. if (this._textureLoadingCallback) {
  62765. var remaining = this._currentScene.getWaitingItemsCount();
  62766. if (remaining > 0) {
  62767. this._textureLoadingCallback(remaining);
  62768. }
  62769. }
  62770. this._currentScene.render();
  62771. }
  62772. };
  62773. FilesInput.prototype.drag = function (e) {
  62774. e.stopPropagation();
  62775. e.preventDefault();
  62776. };
  62777. FilesInput.prototype.drop = function (eventDrop) {
  62778. eventDrop.stopPropagation();
  62779. eventDrop.preventDefault();
  62780. this.loadFiles(eventDrop);
  62781. };
  62782. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  62783. var _this = this;
  62784. var reader = folder.createReader();
  62785. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  62786. reader.readEntries(function (entries) {
  62787. remaining.count += entries.length;
  62788. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  62789. var entry = entries_1[_i];
  62790. if (entry.isFile) {
  62791. entry.file(function (file) {
  62792. file.correctName = relativePath + file.name;
  62793. files.push(file);
  62794. if (--remaining.count === 0) {
  62795. callback();
  62796. }
  62797. });
  62798. }
  62799. else if (entry.isDirectory) {
  62800. _this._traverseFolder(entry, files, remaining, callback);
  62801. }
  62802. }
  62803. if (--remaining.count) {
  62804. callback();
  62805. }
  62806. });
  62807. };
  62808. FilesInput.prototype._processFiles = function (files) {
  62809. for (var i = 0; i < files.length; i++) {
  62810. var name = files[i].correctName.toLowerCase();
  62811. var extension = name.split('.').pop();
  62812. if (!this.onProcessFileCallback(files[i], name, extension)) {
  62813. continue;
  62814. }
  62815. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  62816. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  62817. this._sceneFileToLoad = files[i];
  62818. }
  62819. else {
  62820. FilesInput.FilesToLoad[name] = files[i];
  62821. }
  62822. }
  62823. };
  62824. FilesInput.prototype.loadFiles = function (event) {
  62825. var _this = this;
  62826. if (this._startingProcessingFilesCallback)
  62827. this._startingProcessingFilesCallback();
  62828. // Handling data transfer via drag'n'drop
  62829. if (event && event.dataTransfer && event.dataTransfer.files) {
  62830. this._filesToLoad = event.dataTransfer.files;
  62831. }
  62832. // Handling files from input files
  62833. if (event && event.target && event.target.files) {
  62834. this._filesToLoad = event.target.files;
  62835. }
  62836. if (this._filesToLoad && this._filesToLoad.length > 0) {
  62837. var files_1 = new Array();
  62838. var folders = [];
  62839. var items = event.dataTransfer ? event.dataTransfer.items : null;
  62840. for (var i = 0; i < this._filesToLoad.length; i++) {
  62841. var fileToLoad = this._filesToLoad[i];
  62842. var name_1 = fileToLoad.name.toLowerCase();
  62843. var entry = void 0;
  62844. fileToLoad.correctName = name_1;
  62845. if (items) {
  62846. var item = items[i];
  62847. if (item.getAsEntry) {
  62848. entry = item.getAsEntry();
  62849. }
  62850. else if (item.webkitGetAsEntry) {
  62851. entry = item.webkitGetAsEntry();
  62852. }
  62853. }
  62854. if (!entry) {
  62855. files_1.push(fileToLoad);
  62856. }
  62857. else {
  62858. if (entry.isDirectory) {
  62859. folders.push(entry);
  62860. }
  62861. else {
  62862. files_1.push(fileToLoad);
  62863. }
  62864. }
  62865. }
  62866. if (folders.length === 0) {
  62867. this._processFiles(files_1);
  62868. this._processReload();
  62869. }
  62870. else {
  62871. var remaining = { count: folders.length };
  62872. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  62873. var folder = folders_1[_i];
  62874. this._traverseFolder(folder, files_1, remaining, function () {
  62875. _this._processFiles(files_1);
  62876. if (remaining.count === 0) {
  62877. _this._processReload();
  62878. }
  62879. });
  62880. }
  62881. }
  62882. }
  62883. };
  62884. FilesInput.prototype._processReload = function () {
  62885. if (this._onReloadCallback) {
  62886. this._onReloadCallback(this._sceneFileToLoad);
  62887. }
  62888. else {
  62889. this.reload();
  62890. }
  62891. };
  62892. FilesInput.prototype.reload = function () {
  62893. var _this = this;
  62894. // If a scene file has been provided
  62895. if (this._sceneFileToLoad) {
  62896. if (this._currentScene) {
  62897. if (BABYLON.Tools.errorsCount > 0) {
  62898. BABYLON.Tools.ClearLogCache();
  62899. }
  62900. this._engine.stopRenderLoop();
  62901. this._currentScene.dispose();
  62902. }
  62903. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad, this._engine, function (progress) {
  62904. if (_this._progressCallback) {
  62905. _this._progressCallback(progress);
  62906. }
  62907. }).then(function (scene) {
  62908. _this._currentScene = scene;
  62909. if (_this._sceneLoadedCallback) {
  62910. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  62911. }
  62912. // Wait for textures and shaders to be ready
  62913. _this._currentScene.executeWhenReady(function () {
  62914. _this._engine.runRenderLoop(function () {
  62915. _this.renderFunction();
  62916. });
  62917. });
  62918. }).catch(function (error) {
  62919. if (_this._errorCallback) {
  62920. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  62921. }
  62922. });
  62923. }
  62924. else {
  62925. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  62926. }
  62927. };
  62928. FilesInput.FilesToLoad = {};
  62929. return FilesInput;
  62930. }());
  62931. BABYLON.FilesInput = FilesInput;
  62932. })(BABYLON || (BABYLON = {}));
  62933. //# sourceMappingURL=babylon.filesInput.js.map
  62934. var BABYLON;
  62935. (function (BABYLON) {
  62936. /**
  62937. * This class implement a typical dictionary using a string as key and the generic type T as value.
  62938. * The underlying implementation relies on an associative array to ensure the best performances.
  62939. * The value can be anything including 'null' but except 'undefined'
  62940. */
  62941. var StringDictionary = /** @class */ (function () {
  62942. function StringDictionary() {
  62943. this._count = 0;
  62944. this._data = {};
  62945. }
  62946. /**
  62947. * This will clear this dictionary and copy the content from the 'source' one.
  62948. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  62949. * @param source the dictionary to take the content from and copy to this dictionary
  62950. */
  62951. StringDictionary.prototype.copyFrom = function (source) {
  62952. var _this = this;
  62953. this.clear();
  62954. source.forEach(function (t, v) { return _this.add(t, v); });
  62955. };
  62956. /**
  62957. * Get a value based from its key
  62958. * @param key the given key to get the matching value from
  62959. * @return the value if found, otherwise undefined is returned
  62960. */
  62961. StringDictionary.prototype.get = function (key) {
  62962. var val = this._data[key];
  62963. if (val !== undefined) {
  62964. return val;
  62965. }
  62966. return undefined;
  62967. };
  62968. /**
  62969. * Get a value from its key or add it if it doesn't exist.
  62970. * This method will ensure you that a given key/data will be present in the dictionary.
  62971. * @param key the given key to get the matching value from
  62972. * @param factory the factory that will create the value if the key is not present in the dictionary.
  62973. * The factory will only be invoked if there's no data for the given key.
  62974. * @return the value corresponding to the key.
  62975. */
  62976. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  62977. var val = this.get(key);
  62978. if (val !== undefined) {
  62979. return val;
  62980. }
  62981. val = factory(key);
  62982. if (val) {
  62983. this.add(key, val);
  62984. }
  62985. return val;
  62986. };
  62987. /**
  62988. * Get a value from its key if present in the dictionary otherwise add it
  62989. * @param key the key to get the value from
  62990. * @param val if there's no such key/value pair in the dictionary add it with this value
  62991. * @return the value corresponding to the key
  62992. */
  62993. StringDictionary.prototype.getOrAdd = function (key, val) {
  62994. var curVal = this.get(key);
  62995. if (curVal !== undefined) {
  62996. return curVal;
  62997. }
  62998. this.add(key, val);
  62999. return val;
  63000. };
  63001. /**
  63002. * Check if there's a given key in the dictionary
  63003. * @param key the key to check for
  63004. * @return true if the key is present, false otherwise
  63005. */
  63006. StringDictionary.prototype.contains = function (key) {
  63007. return this._data[key] !== undefined;
  63008. };
  63009. /**
  63010. * Add a new key and its corresponding value
  63011. * @param key the key to add
  63012. * @param value the value corresponding to the key
  63013. * @return true if the operation completed successfully, false if we couldn't insert the key/value because there was already this key in the dictionary
  63014. */
  63015. StringDictionary.prototype.add = function (key, value) {
  63016. if (this._data[key] !== undefined) {
  63017. return false;
  63018. }
  63019. this._data[key] = value;
  63020. ++this._count;
  63021. return true;
  63022. };
  63023. StringDictionary.prototype.set = function (key, value) {
  63024. if (this._data[key] === undefined) {
  63025. return false;
  63026. }
  63027. this._data[key] = value;
  63028. return true;
  63029. };
  63030. /**
  63031. * Get the element of the given key and remove it from the dictionary
  63032. * @param key
  63033. */
  63034. StringDictionary.prototype.getAndRemove = function (key) {
  63035. var val = this.get(key);
  63036. if (val !== undefined) {
  63037. delete this._data[key];
  63038. --this._count;
  63039. return val;
  63040. }
  63041. return null;
  63042. };
  63043. /**
  63044. * Remove a key/value from the dictionary.
  63045. * @param key the key to remove
  63046. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  63047. */
  63048. StringDictionary.prototype.remove = function (key) {
  63049. if (this.contains(key)) {
  63050. delete this._data[key];
  63051. --this._count;
  63052. return true;
  63053. }
  63054. return false;
  63055. };
  63056. /**
  63057. * Clear the whole content of the dictionary
  63058. */
  63059. StringDictionary.prototype.clear = function () {
  63060. this._data = {};
  63061. this._count = 0;
  63062. };
  63063. Object.defineProperty(StringDictionary.prototype, "count", {
  63064. get: function () {
  63065. return this._count;
  63066. },
  63067. enumerable: true,
  63068. configurable: true
  63069. });
  63070. /**
  63071. * Execute a callback on each key/val of the dictionary.
  63072. * Note that you can remove any element in this dictionary in the callback implementation
  63073. * @param callback the callback to execute on a given key/value pair
  63074. */
  63075. StringDictionary.prototype.forEach = function (callback) {
  63076. for (var cur in this._data) {
  63077. var val = this._data[cur];
  63078. callback(cur, val);
  63079. }
  63080. };
  63081. /**
  63082. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  63083. * If the callback returns null or undefined the method will iterate to the next key/value pair
  63084. * Note that you can remove any element in this dictionary in the callback implementation
  63085. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  63086. */
  63087. StringDictionary.prototype.first = function (callback) {
  63088. for (var cur in this._data) {
  63089. var val = this._data[cur];
  63090. var res = callback(cur, val);
  63091. if (res) {
  63092. return res;
  63093. }
  63094. }
  63095. return null;
  63096. };
  63097. return StringDictionary;
  63098. }());
  63099. BABYLON.StringDictionary = StringDictionary;
  63100. })(BABYLON || (BABYLON = {}));
  63101. //# sourceMappingURL=babylon.stringDictionary.js.map
  63102. var BABYLON;
  63103. (function (BABYLON) {
  63104. var Tags = /** @class */ (function () {
  63105. function Tags() {
  63106. }
  63107. Tags.EnableFor = function (obj) {
  63108. obj._tags = obj._tags || {};
  63109. obj.hasTags = function () {
  63110. return Tags.HasTags(obj);
  63111. };
  63112. obj.addTags = function (tagsString) {
  63113. return Tags.AddTagsTo(obj, tagsString);
  63114. };
  63115. obj.removeTags = function (tagsString) {
  63116. return Tags.RemoveTagsFrom(obj, tagsString);
  63117. };
  63118. obj.matchesTagsQuery = function (tagsQuery) {
  63119. return Tags.MatchesQuery(obj, tagsQuery);
  63120. };
  63121. };
  63122. Tags.DisableFor = function (obj) {
  63123. delete obj._tags;
  63124. delete obj.hasTags;
  63125. delete obj.addTags;
  63126. delete obj.removeTags;
  63127. delete obj.matchesTagsQuery;
  63128. };
  63129. Tags.HasTags = function (obj) {
  63130. if (!obj._tags) {
  63131. return false;
  63132. }
  63133. return !BABYLON.Tools.IsEmpty(obj._tags);
  63134. };
  63135. Tags.GetTags = function (obj, asString) {
  63136. if (asString === void 0) { asString = true; }
  63137. if (!obj._tags) {
  63138. return null;
  63139. }
  63140. if (asString) {
  63141. var tagsArray = [];
  63142. for (var tag in obj._tags) {
  63143. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  63144. tagsArray.push(tag);
  63145. }
  63146. }
  63147. return tagsArray.join(" ");
  63148. }
  63149. else {
  63150. return obj._tags;
  63151. }
  63152. };
  63153. // the tags 'true' and 'false' are reserved and cannot be used as tags
  63154. // a tag cannot start with '||', '&&', and '!'
  63155. // it cannot contain whitespaces
  63156. Tags.AddTagsTo = function (obj, tagsString) {
  63157. if (!tagsString) {
  63158. return;
  63159. }
  63160. if (typeof tagsString !== "string") {
  63161. return;
  63162. }
  63163. var tags = tagsString.split(" ");
  63164. tags.forEach(function (tag, index, array) {
  63165. Tags._AddTagTo(obj, tag);
  63166. });
  63167. };
  63168. Tags._AddTagTo = function (obj, tag) {
  63169. tag = tag.trim();
  63170. if (tag === "" || tag === "true" || tag === "false") {
  63171. return;
  63172. }
  63173. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  63174. return;
  63175. }
  63176. Tags.EnableFor(obj);
  63177. obj._tags[tag] = true;
  63178. };
  63179. Tags.RemoveTagsFrom = function (obj, tagsString) {
  63180. if (!Tags.HasTags(obj)) {
  63181. return;
  63182. }
  63183. var tags = tagsString.split(" ");
  63184. for (var t in tags) {
  63185. Tags._RemoveTagFrom(obj, tags[t]);
  63186. }
  63187. };
  63188. Tags._RemoveTagFrom = function (obj, tag) {
  63189. delete obj._tags[tag];
  63190. };
  63191. Tags.MatchesQuery = function (obj, tagsQuery) {
  63192. if (tagsQuery === undefined) {
  63193. return true;
  63194. }
  63195. if (tagsQuery === "") {
  63196. return Tags.HasTags(obj);
  63197. }
  63198. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  63199. };
  63200. return Tags;
  63201. }());
  63202. BABYLON.Tags = Tags;
  63203. })(BABYLON || (BABYLON = {}));
  63204. //# sourceMappingURL=babylon.tags.js.map
  63205. var BABYLON;
  63206. (function (BABYLON) {
  63207. var AndOrNotEvaluator = /** @class */ (function () {
  63208. function AndOrNotEvaluator() {
  63209. }
  63210. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  63211. if (!query.match(/\([^\(\)]*\)/g)) {
  63212. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  63213. }
  63214. else {
  63215. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  63216. // remove parenthesis
  63217. r = r.slice(1, r.length - 1);
  63218. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  63219. });
  63220. }
  63221. if (query === "true") {
  63222. return true;
  63223. }
  63224. if (query === "false") {
  63225. return false;
  63226. }
  63227. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  63228. };
  63229. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  63230. evaluateCallback = evaluateCallback || (function (r) {
  63231. return r === "true" ? true : false;
  63232. });
  63233. var result;
  63234. var or = parenthesisContent.split("||");
  63235. for (var i in or) {
  63236. if (or.hasOwnProperty(i)) {
  63237. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  63238. var and = ori.split("&&");
  63239. if (and.length > 1) {
  63240. for (var j = 0; j < and.length; ++j) {
  63241. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  63242. if (andj !== "true" && andj !== "false") {
  63243. if (andj[0] === "!") {
  63244. result = !evaluateCallback(andj.substring(1));
  63245. }
  63246. else {
  63247. result = evaluateCallback(andj);
  63248. }
  63249. }
  63250. else {
  63251. result = andj === "true" ? true : false;
  63252. }
  63253. if (!result) {
  63254. ori = "false";
  63255. break;
  63256. }
  63257. }
  63258. }
  63259. if (result || ori === "true") {
  63260. result = true;
  63261. break;
  63262. }
  63263. // result equals false (or undefined)
  63264. if (ori !== "true" && ori !== "false") {
  63265. if (ori[0] === "!") {
  63266. result = !evaluateCallback(ori.substring(1));
  63267. }
  63268. else {
  63269. result = evaluateCallback(ori);
  63270. }
  63271. }
  63272. else {
  63273. result = ori === "true" ? true : false;
  63274. }
  63275. }
  63276. }
  63277. // the whole parenthesis scope is replaced by 'true' or 'false'
  63278. return result ? "true" : "false";
  63279. };
  63280. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  63281. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  63282. // remove whitespaces
  63283. r = r.replace(/[\s]/g, function () { return ""; });
  63284. return r.length % 2 ? "!" : "";
  63285. });
  63286. booleanString = booleanString.trim();
  63287. if (booleanString === "!true") {
  63288. booleanString = "false";
  63289. }
  63290. else if (booleanString === "!false") {
  63291. booleanString = "true";
  63292. }
  63293. return booleanString;
  63294. };
  63295. return AndOrNotEvaluator;
  63296. }());
  63297. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  63298. })(BABYLON || (BABYLON = {}));
  63299. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  63300. var BABYLON;
  63301. (function (BABYLON) {
  63302. var Database = /** @class */ (function () {
  63303. function Database(urlToScene, callbackManifestChecked) {
  63304. // Handling various flavors of prefixed version of IndexedDB
  63305. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  63306. this.callbackManifestChecked = callbackManifestChecked;
  63307. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  63308. this.db = null;
  63309. this._enableSceneOffline = false;
  63310. this._enableTexturesOffline = false;
  63311. this.manifestVersionFound = 0;
  63312. this.mustUpdateRessources = false;
  63313. this.hasReachedQuota = false;
  63314. if (!Database.IDBStorageEnabled) {
  63315. this.callbackManifestChecked(true);
  63316. }
  63317. else {
  63318. this.checkManifestFile();
  63319. }
  63320. }
  63321. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  63322. get: function () {
  63323. return this._enableSceneOffline;
  63324. },
  63325. enumerable: true,
  63326. configurable: true
  63327. });
  63328. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  63329. get: function () {
  63330. return this._enableTexturesOffline;
  63331. },
  63332. enumerable: true,
  63333. configurable: true
  63334. });
  63335. Database.prototype.checkManifestFile = function () {
  63336. var _this = this;
  63337. var noManifestFile = function () {
  63338. _this._enableSceneOffline = false;
  63339. _this._enableTexturesOffline = false;
  63340. _this.callbackManifestChecked(false);
  63341. };
  63342. var timeStampUsed = false;
  63343. var manifestURL = this.currentSceneUrl + ".manifest";
  63344. var xhr = new XMLHttpRequest();
  63345. if (navigator.onLine) {
  63346. // Adding a timestamp to by-pass browsers' cache
  63347. timeStampUsed = true;
  63348. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  63349. }
  63350. xhr.open("GET", manifestURL, true);
  63351. xhr.addEventListener("load", function () {
  63352. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  63353. try {
  63354. var manifestFile = JSON.parse(xhr.response);
  63355. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  63356. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  63357. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  63358. _this.manifestVersionFound = manifestFile.version;
  63359. }
  63360. if (_this.callbackManifestChecked) {
  63361. _this.callbackManifestChecked(true);
  63362. }
  63363. }
  63364. catch (ex) {
  63365. noManifestFile();
  63366. }
  63367. }
  63368. else {
  63369. noManifestFile();
  63370. }
  63371. }, false);
  63372. xhr.addEventListener("error", function (event) {
  63373. if (timeStampUsed) {
  63374. timeStampUsed = false;
  63375. // Let's retry without the timeStamp
  63376. // It could fail when coupled with HTML5 Offline API
  63377. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  63378. xhr.open("GET", retryManifestURL, true);
  63379. xhr.send();
  63380. }
  63381. else {
  63382. noManifestFile();
  63383. }
  63384. }, false);
  63385. try {
  63386. xhr.send();
  63387. }
  63388. catch (ex) {
  63389. BABYLON.Tools.Error("Error on XHR send request.");
  63390. this.callbackManifestChecked(false);
  63391. }
  63392. };
  63393. Database.prototype.openAsync = function (successCallback, errorCallback) {
  63394. var _this = this;
  63395. var handleError = function () {
  63396. _this.isSupported = false;
  63397. if (errorCallback)
  63398. errorCallback();
  63399. };
  63400. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  63401. // Your browser doesn't support IndexedDB
  63402. this.isSupported = false;
  63403. if (errorCallback)
  63404. errorCallback();
  63405. }
  63406. else {
  63407. // If the DB hasn't been opened or created yet
  63408. if (!this.db) {
  63409. this.hasReachedQuota = false;
  63410. this.isSupported = true;
  63411. var request = this.idbFactory.open("babylonjs", 1);
  63412. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  63413. request.onerror = function (event) {
  63414. handleError();
  63415. };
  63416. // executes when a version change transaction cannot complete due to other active transactions
  63417. request.onblocked = function (event) {
  63418. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  63419. handleError();
  63420. };
  63421. // DB has been opened successfully
  63422. request.onsuccess = function (event) {
  63423. _this.db = request.result;
  63424. successCallback();
  63425. };
  63426. // Initialization of the DB. Creating Scenes & Textures stores
  63427. request.onupgradeneeded = function (event) {
  63428. _this.db = (event.target).result;
  63429. if (_this.db) {
  63430. try {
  63431. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  63432. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  63433. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  63434. }
  63435. catch (ex) {
  63436. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  63437. handleError();
  63438. }
  63439. }
  63440. };
  63441. }
  63442. else {
  63443. if (successCallback)
  63444. successCallback();
  63445. }
  63446. }
  63447. };
  63448. Database.prototype.loadImageFromDB = function (url, image) {
  63449. var _this = this;
  63450. var completeURL = Database.ReturnFullUrlLocation(url);
  63451. var saveAndLoadImage = function () {
  63452. if (!_this.hasReachedQuota && _this.db !== null) {
  63453. // the texture is not yet in the DB, let's try to save it
  63454. _this._saveImageIntoDBAsync(completeURL, image);
  63455. }
  63456. else {
  63457. image.src = url;
  63458. }
  63459. };
  63460. if (!this.mustUpdateRessources) {
  63461. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  63462. }
  63463. else {
  63464. saveAndLoadImage();
  63465. }
  63466. };
  63467. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  63468. if (this.isSupported && this.db !== null) {
  63469. var texture;
  63470. var transaction = this.db.transaction(["textures"]);
  63471. transaction.onabort = function (event) {
  63472. image.src = url;
  63473. };
  63474. transaction.oncomplete = function (event) {
  63475. var blobTextureURL;
  63476. if (texture) {
  63477. var URL = window.URL || window.webkitURL;
  63478. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  63479. image.onerror = function () {
  63480. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  63481. image.src = url;
  63482. };
  63483. image.src = blobTextureURL;
  63484. }
  63485. else {
  63486. notInDBCallback();
  63487. }
  63488. };
  63489. var getRequest = transaction.objectStore("textures").get(url);
  63490. getRequest.onsuccess = function (event) {
  63491. texture = (event.target).result;
  63492. };
  63493. getRequest.onerror = function (event) {
  63494. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  63495. image.src = url;
  63496. };
  63497. }
  63498. else {
  63499. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  63500. image.src = url;
  63501. }
  63502. };
  63503. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  63504. var _this = this;
  63505. if (this.isSupported) {
  63506. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  63507. var generateBlobUrl = function () {
  63508. var blobTextureURL;
  63509. if (blob) {
  63510. var URL = window.URL || window.webkitURL;
  63511. try {
  63512. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  63513. }
  63514. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  63515. catch (ex) {
  63516. blobTextureURL = URL.createObjectURL(blob);
  63517. }
  63518. }
  63519. if (blobTextureURL) {
  63520. image.src = blobTextureURL;
  63521. }
  63522. };
  63523. if (Database.IsUASupportingBlobStorage) {
  63524. var xhr = new XMLHttpRequest(), blob;
  63525. xhr.open("GET", url, true);
  63526. xhr.responseType = "blob";
  63527. xhr.addEventListener("load", function () {
  63528. if (xhr.status === 200 && _this.db) {
  63529. // Blob as response (XHR2)
  63530. blob = xhr.response;
  63531. var transaction = _this.db.transaction(["textures"], "readwrite");
  63532. // the transaction could abort because of a QuotaExceededError error
  63533. transaction.onabort = function (event) {
  63534. try {
  63535. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  63536. var srcElement = (event.srcElement || event.target);
  63537. var error = srcElement.error;
  63538. if (error && error.name === "QuotaExceededError") {
  63539. _this.hasReachedQuota = true;
  63540. }
  63541. }
  63542. catch (ex) { }
  63543. generateBlobUrl();
  63544. };
  63545. transaction.oncomplete = function (event) {
  63546. generateBlobUrl();
  63547. };
  63548. var newTexture = { textureUrl: url, data: blob };
  63549. try {
  63550. // Put the blob into the dabase
  63551. var addRequest = transaction.objectStore("textures").put(newTexture);
  63552. addRequest.onsuccess = function (event) {
  63553. };
  63554. addRequest.onerror = function (event) {
  63555. generateBlobUrl();
  63556. };
  63557. }
  63558. catch (ex) {
  63559. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  63560. if (ex.code === 25) {
  63561. Database.IsUASupportingBlobStorage = false;
  63562. }
  63563. image.src = url;
  63564. }
  63565. }
  63566. else {
  63567. image.src = url;
  63568. }
  63569. }, false);
  63570. xhr.addEventListener("error", function (event) {
  63571. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  63572. image.src = url;
  63573. }, false);
  63574. xhr.send();
  63575. }
  63576. else {
  63577. image.src = url;
  63578. }
  63579. }
  63580. else {
  63581. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  63582. image.src = url;
  63583. }
  63584. };
  63585. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  63586. var _this = this;
  63587. var updateVersion = function () {
  63588. // the version is not yet in the DB or we need to update it
  63589. _this._saveVersionIntoDBAsync(url, versionLoaded);
  63590. };
  63591. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  63592. };
  63593. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  63594. var _this = this;
  63595. if (this.isSupported && this.db) {
  63596. var version;
  63597. try {
  63598. var transaction = this.db.transaction(["versions"]);
  63599. transaction.oncomplete = function (event) {
  63600. if (version) {
  63601. // If the version in the JSON file is > than the version in DB
  63602. if (_this.manifestVersionFound > version.data) {
  63603. _this.mustUpdateRessources = true;
  63604. updateInDBCallback();
  63605. }
  63606. else {
  63607. callback(version.data);
  63608. }
  63609. }
  63610. else {
  63611. _this.mustUpdateRessources = true;
  63612. updateInDBCallback();
  63613. }
  63614. };
  63615. transaction.onabort = function (event) {
  63616. callback(-1);
  63617. };
  63618. var getRequest = transaction.objectStore("versions").get(url);
  63619. getRequest.onsuccess = function (event) {
  63620. version = (event.target).result;
  63621. };
  63622. getRequest.onerror = function (event) {
  63623. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  63624. callback(-1);
  63625. };
  63626. }
  63627. catch (ex) {
  63628. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  63629. callback(-1);
  63630. }
  63631. }
  63632. else {
  63633. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  63634. callback(-1);
  63635. }
  63636. };
  63637. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  63638. var _this = this;
  63639. if (this.isSupported && !this.hasReachedQuota && this.db) {
  63640. try {
  63641. // Open a transaction to the database
  63642. var transaction = this.db.transaction(["versions"], "readwrite");
  63643. // the transaction could abort because of a QuotaExceededError error
  63644. transaction.onabort = function (event) {
  63645. try {
  63646. var error = event.srcElement['error'];
  63647. if (error && error.name === "QuotaExceededError") {
  63648. _this.hasReachedQuota = true;
  63649. }
  63650. }
  63651. catch (ex) { }
  63652. callback(-1);
  63653. };
  63654. transaction.oncomplete = function (event) {
  63655. callback(_this.manifestVersionFound);
  63656. };
  63657. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  63658. // Put the scene into the database
  63659. var addRequest = transaction.objectStore("versions").put(newVersion);
  63660. addRequest.onsuccess = function (event) {
  63661. };
  63662. addRequest.onerror = function (event) {
  63663. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  63664. };
  63665. }
  63666. catch (ex) {
  63667. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  63668. callback(-1);
  63669. }
  63670. }
  63671. else {
  63672. callback(-1);
  63673. }
  63674. };
  63675. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  63676. var _this = this;
  63677. var completeUrl = Database.ReturnFullUrlLocation(url);
  63678. var saveAndLoadFile = function () {
  63679. // the scene is not yet in the DB, let's try to save it
  63680. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  63681. };
  63682. this._checkVersionFromDB(completeUrl, function (version) {
  63683. if (version !== -1) {
  63684. if (!_this.mustUpdateRessources) {
  63685. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  63686. }
  63687. else {
  63688. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  63689. }
  63690. }
  63691. else {
  63692. if (errorCallback) {
  63693. errorCallback();
  63694. }
  63695. }
  63696. });
  63697. };
  63698. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  63699. if (this.isSupported && this.db) {
  63700. var targetStore;
  63701. if (url.indexOf(".babylon") !== -1) {
  63702. targetStore = "scenes";
  63703. }
  63704. else {
  63705. targetStore = "textures";
  63706. }
  63707. var file;
  63708. var transaction = this.db.transaction([targetStore]);
  63709. transaction.oncomplete = function (event) {
  63710. if (file) {
  63711. callback(file.data);
  63712. }
  63713. else {
  63714. notInDBCallback();
  63715. }
  63716. };
  63717. transaction.onabort = function (event) {
  63718. notInDBCallback();
  63719. };
  63720. var getRequest = transaction.objectStore(targetStore).get(url);
  63721. getRequest.onsuccess = function (event) {
  63722. file = (event.target).result;
  63723. };
  63724. getRequest.onerror = function (event) {
  63725. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  63726. notInDBCallback();
  63727. };
  63728. }
  63729. else {
  63730. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  63731. callback();
  63732. }
  63733. };
  63734. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  63735. var _this = this;
  63736. if (this.isSupported) {
  63737. var targetStore;
  63738. if (url.indexOf(".babylon") !== -1) {
  63739. targetStore = "scenes";
  63740. }
  63741. else {
  63742. targetStore = "textures";
  63743. }
  63744. // Create XHR
  63745. var xhr = new XMLHttpRequest();
  63746. var fileData;
  63747. xhr.open("GET", url, true);
  63748. if (useArrayBuffer) {
  63749. xhr.responseType = "arraybuffer";
  63750. }
  63751. if (progressCallback) {
  63752. xhr.onprogress = progressCallback;
  63753. }
  63754. xhr.addEventListener("load", function () {
  63755. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  63756. // Blob as response (XHR2)
  63757. //fileData = xhr.responseText;
  63758. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  63759. if (!_this.hasReachedQuota && _this.db) {
  63760. // Open a transaction to the database
  63761. var transaction = _this.db.transaction([targetStore], "readwrite");
  63762. // the transaction could abort because of a QuotaExceededError error
  63763. transaction.onabort = function (event) {
  63764. try {
  63765. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  63766. var error = event.srcElement['error'];
  63767. if (error && error.name === "QuotaExceededError") {
  63768. _this.hasReachedQuota = true;
  63769. }
  63770. }
  63771. catch (ex) { }
  63772. callback(fileData);
  63773. };
  63774. transaction.oncomplete = function (event) {
  63775. callback(fileData);
  63776. };
  63777. var newFile;
  63778. if (targetStore === "scenes") {
  63779. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  63780. }
  63781. else {
  63782. newFile = { textureUrl: url, data: fileData };
  63783. }
  63784. try {
  63785. // Put the scene into the database
  63786. var addRequest = transaction.objectStore(targetStore).put(newFile);
  63787. addRequest.onsuccess = function (event) {
  63788. };
  63789. addRequest.onerror = function (event) {
  63790. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  63791. };
  63792. }
  63793. catch (ex) {
  63794. callback(fileData);
  63795. }
  63796. }
  63797. else {
  63798. callback(fileData);
  63799. }
  63800. }
  63801. else {
  63802. callback();
  63803. }
  63804. }, false);
  63805. xhr.addEventListener("error", function (event) {
  63806. BABYLON.Tools.Error("error on XHR request.");
  63807. callback();
  63808. }, false);
  63809. xhr.send();
  63810. }
  63811. else {
  63812. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  63813. callback();
  63814. }
  63815. };
  63816. Database.IsUASupportingBlobStorage = true;
  63817. Database.IDBStorageEnabled = true;
  63818. Database.parseURL = function (url) {
  63819. var a = document.createElement('a');
  63820. a.href = url;
  63821. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  63822. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  63823. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  63824. return absLocation;
  63825. };
  63826. Database.ReturnFullUrlLocation = function (url) {
  63827. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  63828. return (Database.parseURL(window.location.href) + url);
  63829. }
  63830. else {
  63831. return url;
  63832. }
  63833. };
  63834. return Database;
  63835. }());
  63836. BABYLON.Database = Database;
  63837. })(BABYLON || (BABYLON = {}));
  63838. //# sourceMappingURL=babylon.database.js.map
  63839. var BABYLON;
  63840. (function (BABYLON) {
  63841. var FresnelParameters = /** @class */ (function () {
  63842. function FresnelParameters() {
  63843. this._isEnabled = true;
  63844. this.leftColor = BABYLON.Color3.White();
  63845. this.rightColor = BABYLON.Color3.Black();
  63846. this.bias = 0;
  63847. this.power = 1;
  63848. }
  63849. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  63850. get: function () {
  63851. return this._isEnabled;
  63852. },
  63853. set: function (value) {
  63854. if (this._isEnabled === value) {
  63855. return;
  63856. }
  63857. this._isEnabled = value;
  63858. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  63859. },
  63860. enumerable: true,
  63861. configurable: true
  63862. });
  63863. FresnelParameters.prototype.clone = function () {
  63864. var newFresnelParameters = new FresnelParameters();
  63865. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  63866. return newFresnelParameters;
  63867. };
  63868. FresnelParameters.prototype.serialize = function () {
  63869. var serializationObject = {};
  63870. serializationObject.isEnabled = this.isEnabled;
  63871. serializationObject.leftColor = this.leftColor;
  63872. serializationObject.rightColor = this.rightColor;
  63873. serializationObject.bias = this.bias;
  63874. serializationObject.power = this.power;
  63875. return serializationObject;
  63876. };
  63877. FresnelParameters.Parse = function (parsedFresnelParameters) {
  63878. var fresnelParameters = new FresnelParameters();
  63879. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  63880. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  63881. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  63882. fresnelParameters.bias = parsedFresnelParameters.bias;
  63883. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  63884. return fresnelParameters;
  63885. };
  63886. return FresnelParameters;
  63887. }());
  63888. BABYLON.FresnelParameters = FresnelParameters;
  63889. })(BABYLON || (BABYLON = {}));
  63890. //# sourceMappingURL=babylon.fresnelParameters.js.map
  63891. var BABYLON;
  63892. (function (BABYLON) {
  63893. var MultiMaterial = /** @class */ (function (_super) {
  63894. __extends(MultiMaterial, _super);
  63895. function MultiMaterial(name, scene) {
  63896. var _this = _super.call(this, name, scene, true) || this;
  63897. scene.multiMaterials.push(_this);
  63898. _this.subMaterials = new Array();
  63899. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  63900. return _this;
  63901. }
  63902. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  63903. get: function () {
  63904. return this._subMaterials;
  63905. },
  63906. set: function (value) {
  63907. this._subMaterials = value;
  63908. this._hookArray(value);
  63909. },
  63910. enumerable: true,
  63911. configurable: true
  63912. });
  63913. MultiMaterial.prototype._hookArray = function (array) {
  63914. var _this = this;
  63915. var oldPush = array.push;
  63916. array.push = function () {
  63917. var items = [];
  63918. for (var _i = 0; _i < arguments.length; _i++) {
  63919. items[_i] = arguments[_i];
  63920. }
  63921. var result = oldPush.apply(array, items);
  63922. _this._markAllSubMeshesAsTexturesDirty();
  63923. return result;
  63924. };
  63925. var oldSplice = array.splice;
  63926. array.splice = function (index, deleteCount) {
  63927. var deleted = oldSplice.apply(array, [index, deleteCount]);
  63928. _this._markAllSubMeshesAsTexturesDirty();
  63929. return deleted;
  63930. };
  63931. };
  63932. // Properties
  63933. MultiMaterial.prototype.getSubMaterial = function (index) {
  63934. if (index < 0 || index >= this.subMaterials.length) {
  63935. return this.getScene().defaultMaterial;
  63936. }
  63937. return this.subMaterials[index];
  63938. };
  63939. MultiMaterial.prototype.getActiveTextures = function () {
  63940. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  63941. if (subMaterial) {
  63942. return subMaterial.getActiveTextures();
  63943. }
  63944. else {
  63945. return [];
  63946. }
  63947. }));
  63948. var _a;
  63949. };
  63950. // Methods
  63951. MultiMaterial.prototype.getClassName = function () {
  63952. return "MultiMaterial";
  63953. };
  63954. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  63955. for (var index = 0; index < this.subMaterials.length; index++) {
  63956. var subMaterial = this.subMaterials[index];
  63957. if (subMaterial) {
  63958. if (subMaterial.storeEffectOnSubMeshes) {
  63959. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  63960. return false;
  63961. }
  63962. continue;
  63963. }
  63964. if (!subMaterial.isReady(mesh)) {
  63965. return false;
  63966. }
  63967. }
  63968. }
  63969. return true;
  63970. };
  63971. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  63972. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  63973. for (var index = 0; index < this.subMaterials.length; index++) {
  63974. var subMaterial = null;
  63975. var current = this.subMaterials[index];
  63976. if (cloneChildren && current) {
  63977. subMaterial = current.clone(name + "-" + current.name);
  63978. }
  63979. else {
  63980. subMaterial = this.subMaterials[index];
  63981. }
  63982. newMultiMaterial.subMaterials.push(subMaterial);
  63983. }
  63984. return newMultiMaterial;
  63985. };
  63986. MultiMaterial.prototype.serialize = function () {
  63987. var serializationObject = {};
  63988. serializationObject.name = this.name;
  63989. serializationObject.id = this.id;
  63990. if (BABYLON.Tags) {
  63991. serializationObject.tags = BABYLON.Tags.GetTags(this);
  63992. }
  63993. serializationObject.materials = [];
  63994. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  63995. var subMat = this.subMaterials[matIndex];
  63996. if (subMat) {
  63997. serializationObject.materials.push(subMat.id);
  63998. }
  63999. else {
  64000. serializationObject.materials.push(null);
  64001. }
  64002. }
  64003. return serializationObject;
  64004. };
  64005. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  64006. var scene = this.getScene();
  64007. if (!scene) {
  64008. return;
  64009. }
  64010. var index = scene.multiMaterials.indexOf(this);
  64011. if (index >= 0) {
  64012. scene.multiMaterials.splice(index, 1);
  64013. }
  64014. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  64015. };
  64016. return MultiMaterial;
  64017. }(BABYLON.Material));
  64018. BABYLON.MultiMaterial = MultiMaterial;
  64019. })(BABYLON || (BABYLON = {}));
  64020. //# sourceMappingURL=babylon.multiMaterial.js.map
  64021. var BABYLON;
  64022. (function (BABYLON) {
  64023. var FreeCameraTouchInput = /** @class */ (function () {
  64024. function FreeCameraTouchInput() {
  64025. this._offsetX = null;
  64026. this._offsetY = null;
  64027. this._pointerPressed = new Array();
  64028. this.touchAngularSensibility = 200000.0;
  64029. this.touchMoveSensibility = 250.0;
  64030. }
  64031. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  64032. var _this = this;
  64033. var previousPosition = null;
  64034. if (this._pointerInput === undefined) {
  64035. this._onLostFocus = function (evt) {
  64036. _this._offsetX = null;
  64037. _this._offsetY = null;
  64038. };
  64039. this._pointerInput = function (p, s) {
  64040. var evt = p.event;
  64041. if (evt.pointerType === "mouse") {
  64042. return;
  64043. }
  64044. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  64045. if (!noPreventDefault) {
  64046. evt.preventDefault();
  64047. }
  64048. _this._pointerPressed.push(evt.pointerId);
  64049. if (_this._pointerPressed.length !== 1) {
  64050. return;
  64051. }
  64052. previousPosition = {
  64053. x: evt.clientX,
  64054. y: evt.clientY
  64055. };
  64056. }
  64057. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  64058. if (!noPreventDefault) {
  64059. evt.preventDefault();
  64060. }
  64061. var index = _this._pointerPressed.indexOf(evt.pointerId);
  64062. if (index === -1) {
  64063. return;
  64064. }
  64065. _this._pointerPressed.splice(index, 1);
  64066. if (index != 0) {
  64067. return;
  64068. }
  64069. previousPosition = null;
  64070. _this._offsetX = null;
  64071. _this._offsetY = null;
  64072. }
  64073. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  64074. if (!noPreventDefault) {
  64075. evt.preventDefault();
  64076. }
  64077. if (!previousPosition) {
  64078. return;
  64079. }
  64080. var index = _this._pointerPressed.indexOf(evt.pointerId);
  64081. if (index != 0) {
  64082. return;
  64083. }
  64084. _this._offsetX = evt.clientX - previousPosition.x;
  64085. _this._offsetY = -(evt.clientY - previousPosition.y);
  64086. }
  64087. };
  64088. }
  64089. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  64090. if (this._onLostFocus) {
  64091. element.addEventListener("blur", this._onLostFocus);
  64092. }
  64093. };
  64094. FreeCameraTouchInput.prototype.detachControl = function (element) {
  64095. if (this._pointerInput && element) {
  64096. if (this._observer) {
  64097. this.camera.getScene().onPointerObservable.remove(this._observer);
  64098. this._observer = null;
  64099. }
  64100. if (this._onLostFocus) {
  64101. element.removeEventListener("blur", this._onLostFocus);
  64102. this._onLostFocus = null;
  64103. }
  64104. this._pointerPressed = [];
  64105. this._offsetX = null;
  64106. this._offsetY = null;
  64107. }
  64108. };
  64109. FreeCameraTouchInput.prototype.checkInputs = function () {
  64110. if (this._offsetX && this._offsetY) {
  64111. var camera = this.camera;
  64112. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  64113. if (this._pointerPressed.length > 1) {
  64114. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  64115. }
  64116. else {
  64117. var speed = camera._computeLocalCameraSpeed();
  64118. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  64119. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  64120. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  64121. }
  64122. }
  64123. };
  64124. FreeCameraTouchInput.prototype.getClassName = function () {
  64125. return "FreeCameraTouchInput";
  64126. };
  64127. FreeCameraTouchInput.prototype.getSimpleName = function () {
  64128. return "touch";
  64129. };
  64130. __decorate([
  64131. BABYLON.serialize()
  64132. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  64133. __decorate([
  64134. BABYLON.serialize()
  64135. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  64136. return FreeCameraTouchInput;
  64137. }());
  64138. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  64139. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  64140. })(BABYLON || (BABYLON = {}));
  64141. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  64142. var BABYLON;
  64143. (function (BABYLON) {
  64144. // We're mainly based on the logic defined into the FreeCamera code
  64145. var TouchCamera = /** @class */ (function (_super) {
  64146. __extends(TouchCamera, _super);
  64147. //-- end properties for backward compatibility for inputs
  64148. function TouchCamera(name, position, scene) {
  64149. var _this = _super.call(this, name, position, scene) || this;
  64150. _this.inputs.addTouch();
  64151. _this._setupInputs();
  64152. return _this;
  64153. }
  64154. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  64155. //-- Begin properties for backward compatibility for inputs
  64156. get: function () {
  64157. var touch = this.inputs.attached["touch"];
  64158. if (touch)
  64159. return touch.touchAngularSensibility;
  64160. return 0;
  64161. },
  64162. set: function (value) {
  64163. var touch = this.inputs.attached["touch"];
  64164. if (touch)
  64165. touch.touchAngularSensibility = value;
  64166. },
  64167. enumerable: true,
  64168. configurable: true
  64169. });
  64170. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  64171. get: function () {
  64172. var touch = this.inputs.attached["touch"];
  64173. if (touch)
  64174. return touch.touchMoveSensibility;
  64175. return 0;
  64176. },
  64177. set: function (value) {
  64178. var touch = this.inputs.attached["touch"];
  64179. if (touch)
  64180. touch.touchMoveSensibility = value;
  64181. },
  64182. enumerable: true,
  64183. configurable: true
  64184. });
  64185. TouchCamera.prototype.getClassName = function () {
  64186. return "TouchCamera";
  64187. };
  64188. TouchCamera.prototype._setupInputs = function () {
  64189. var mouse = this.inputs.attached["mouse"];
  64190. if (mouse) {
  64191. mouse.touchEnabled = false;
  64192. }
  64193. };
  64194. return TouchCamera;
  64195. }(BABYLON.FreeCamera));
  64196. BABYLON.TouchCamera = TouchCamera;
  64197. })(BABYLON || (BABYLON = {}));
  64198. //# sourceMappingURL=babylon.touchCamera.js.map
  64199. var BABYLON;
  64200. (function (BABYLON) {
  64201. var ProceduralTexture = /** @class */ (function (_super) {
  64202. __extends(ProceduralTexture, _super);
  64203. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  64204. if (fallbackTexture === void 0) { fallbackTexture = null; }
  64205. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64206. if (isCube === void 0) { isCube = false; }
  64207. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  64208. _this.isCube = isCube;
  64209. _this.isEnabled = true;
  64210. _this._currentRefreshId = -1;
  64211. _this._refreshRate = 1;
  64212. _this._vertexBuffers = {};
  64213. _this._uniforms = new Array();
  64214. _this._samplers = new Array();
  64215. _this._textures = {};
  64216. _this._floats = {};
  64217. _this._floatsArrays = {};
  64218. _this._colors3 = {};
  64219. _this._colors4 = {};
  64220. _this._vectors2 = {};
  64221. _this._vectors3 = {};
  64222. _this._matrices = {};
  64223. _this._fallbackTextureUsed = false;
  64224. scene._proceduralTextures.push(_this);
  64225. _this._engine = scene.getEngine();
  64226. _this.name = name;
  64227. _this.isRenderTarget = true;
  64228. _this._size = size;
  64229. _this._generateMipMaps = generateMipMaps;
  64230. _this.setFragment(fragment);
  64231. _this._fallbackTexture = fallbackTexture;
  64232. if (isCube) {
  64233. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  64234. _this.setFloat("face", 0);
  64235. }
  64236. else {
  64237. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  64238. }
  64239. // VBO
  64240. var vertices = [];
  64241. vertices.push(1, 1);
  64242. vertices.push(-1, 1);
  64243. vertices.push(-1, -1);
  64244. vertices.push(1, -1);
  64245. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  64246. _this._createIndexBuffer();
  64247. return _this;
  64248. }
  64249. ProceduralTexture.prototype._createIndexBuffer = function () {
  64250. var engine = this._engine;
  64251. // Indices
  64252. var indices = [];
  64253. indices.push(0);
  64254. indices.push(1);
  64255. indices.push(2);
  64256. indices.push(0);
  64257. indices.push(2);
  64258. indices.push(3);
  64259. this._indexBuffer = engine.createIndexBuffer(indices);
  64260. };
  64261. ProceduralTexture.prototype._rebuild = function () {
  64262. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  64263. if (vb) {
  64264. vb._rebuild();
  64265. }
  64266. this._createIndexBuffer();
  64267. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  64268. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  64269. }
  64270. };
  64271. ProceduralTexture.prototype.reset = function () {
  64272. if (this._effect === undefined) {
  64273. return;
  64274. }
  64275. var engine = this._engine;
  64276. engine._releaseEffect(this._effect);
  64277. };
  64278. ProceduralTexture.prototype.isReady = function () {
  64279. var _this = this;
  64280. var engine = this._engine;
  64281. var shaders;
  64282. if (!this._fragment) {
  64283. return false;
  64284. }
  64285. if (this._fallbackTextureUsed) {
  64286. return true;
  64287. }
  64288. if (this._fragment.fragmentElement !== undefined) {
  64289. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  64290. }
  64291. else {
  64292. shaders = { vertex: "procedural", fragment: this._fragment };
  64293. }
  64294. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  64295. _this.releaseInternalTexture();
  64296. if (_this._fallbackTexture) {
  64297. _this._texture = _this._fallbackTexture._texture;
  64298. if (_this._texture) {
  64299. _this._texture.incrementReferences();
  64300. }
  64301. }
  64302. _this._fallbackTextureUsed = true;
  64303. });
  64304. return this._effect.isReady();
  64305. };
  64306. ProceduralTexture.prototype.resetRefreshCounter = function () {
  64307. this._currentRefreshId = -1;
  64308. };
  64309. ProceduralTexture.prototype.setFragment = function (fragment) {
  64310. this._fragment = fragment;
  64311. };
  64312. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  64313. get: function () {
  64314. return this._refreshRate;
  64315. },
  64316. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  64317. set: function (value) {
  64318. this._refreshRate = value;
  64319. this.resetRefreshCounter();
  64320. },
  64321. enumerable: true,
  64322. configurable: true
  64323. });
  64324. ProceduralTexture.prototype._shouldRender = function () {
  64325. if (!this.isEnabled || !this.isReady() || !this._texture) {
  64326. return false;
  64327. }
  64328. if (this._fallbackTextureUsed) {
  64329. return false;
  64330. }
  64331. if (this._currentRefreshId === -1) {
  64332. this._currentRefreshId = 1;
  64333. return true;
  64334. }
  64335. if (this.refreshRate === this._currentRefreshId) {
  64336. this._currentRefreshId = 1;
  64337. return true;
  64338. }
  64339. this._currentRefreshId++;
  64340. return false;
  64341. };
  64342. ProceduralTexture.prototype.getRenderSize = function () {
  64343. return this._size;
  64344. };
  64345. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  64346. if (this._fallbackTextureUsed) {
  64347. return;
  64348. }
  64349. this.releaseInternalTexture();
  64350. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  64351. };
  64352. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  64353. if (this._uniforms.indexOf(uniformName) === -1) {
  64354. this._uniforms.push(uniformName);
  64355. }
  64356. };
  64357. ProceduralTexture.prototype.setTexture = function (name, texture) {
  64358. if (this._samplers.indexOf(name) === -1) {
  64359. this._samplers.push(name);
  64360. }
  64361. this._textures[name] = texture;
  64362. return this;
  64363. };
  64364. ProceduralTexture.prototype.setFloat = function (name, value) {
  64365. this._checkUniform(name);
  64366. this._floats[name] = value;
  64367. return this;
  64368. };
  64369. ProceduralTexture.prototype.setFloats = function (name, value) {
  64370. this._checkUniform(name);
  64371. this._floatsArrays[name] = value;
  64372. return this;
  64373. };
  64374. ProceduralTexture.prototype.setColor3 = function (name, value) {
  64375. this._checkUniform(name);
  64376. this._colors3[name] = value;
  64377. return this;
  64378. };
  64379. ProceduralTexture.prototype.setColor4 = function (name, value) {
  64380. this._checkUniform(name);
  64381. this._colors4[name] = value;
  64382. return this;
  64383. };
  64384. ProceduralTexture.prototype.setVector2 = function (name, value) {
  64385. this._checkUniform(name);
  64386. this._vectors2[name] = value;
  64387. return this;
  64388. };
  64389. ProceduralTexture.prototype.setVector3 = function (name, value) {
  64390. this._checkUniform(name);
  64391. this._vectors3[name] = value;
  64392. return this;
  64393. };
  64394. ProceduralTexture.prototype.setMatrix = function (name, value) {
  64395. this._checkUniform(name);
  64396. this._matrices[name] = value;
  64397. return this;
  64398. };
  64399. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  64400. var scene = this.getScene();
  64401. if (!scene) {
  64402. return;
  64403. }
  64404. var engine = this._engine;
  64405. // Render
  64406. engine.enableEffect(this._effect);
  64407. engine.setState(false);
  64408. // Texture
  64409. for (var name in this._textures) {
  64410. this._effect.setTexture(name, this._textures[name]);
  64411. }
  64412. // Float
  64413. for (name in this._floats) {
  64414. this._effect.setFloat(name, this._floats[name]);
  64415. }
  64416. // Floats
  64417. for (name in this._floatsArrays) {
  64418. this._effect.setArray(name, this._floatsArrays[name]);
  64419. }
  64420. // Color3
  64421. for (name in this._colors3) {
  64422. this._effect.setColor3(name, this._colors3[name]);
  64423. }
  64424. // Color4
  64425. for (name in this._colors4) {
  64426. var color = this._colors4[name];
  64427. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  64428. }
  64429. // Vector2
  64430. for (name in this._vectors2) {
  64431. this._effect.setVector2(name, this._vectors2[name]);
  64432. }
  64433. // Vector3
  64434. for (name in this._vectors3) {
  64435. this._effect.setVector3(name, this._vectors3[name]);
  64436. }
  64437. // Matrix
  64438. for (name in this._matrices) {
  64439. this._effect.setMatrix(name, this._matrices[name]);
  64440. }
  64441. if (!this._texture) {
  64442. return;
  64443. }
  64444. if (this.isCube) {
  64445. for (var face = 0; face < 6; face++) {
  64446. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  64447. // VBOs
  64448. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  64449. this._effect.setFloat("face", face);
  64450. // Clear
  64451. engine.clear(scene.clearColor, true, true, true);
  64452. // Draw order
  64453. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  64454. // Mipmaps
  64455. if (face === 5) {
  64456. engine.generateMipMapsForCubemap(this._texture);
  64457. }
  64458. }
  64459. }
  64460. else {
  64461. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  64462. // VBOs
  64463. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  64464. // Clear
  64465. engine.clear(scene.clearColor, true, true, true);
  64466. // Draw order
  64467. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  64468. }
  64469. // Unbind
  64470. engine.unBindFramebuffer(this._texture, this.isCube);
  64471. if (this.onGenerated) {
  64472. this.onGenerated();
  64473. }
  64474. };
  64475. ProceduralTexture.prototype.clone = function () {
  64476. var textureSize = this.getSize();
  64477. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  64478. // Base texture
  64479. newTexture.hasAlpha = this.hasAlpha;
  64480. newTexture.level = this.level;
  64481. // RenderTarget Texture
  64482. newTexture.coordinatesMode = this.coordinatesMode;
  64483. return newTexture;
  64484. };
  64485. ProceduralTexture.prototype.dispose = function () {
  64486. var scene = this.getScene();
  64487. if (!scene) {
  64488. return;
  64489. }
  64490. var index = scene._proceduralTextures.indexOf(this);
  64491. if (index >= 0) {
  64492. scene._proceduralTextures.splice(index, 1);
  64493. }
  64494. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  64495. if (vertexBuffer) {
  64496. vertexBuffer.dispose();
  64497. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  64498. }
  64499. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  64500. this._indexBuffer = null;
  64501. }
  64502. _super.prototype.dispose.call(this);
  64503. };
  64504. return ProceduralTexture;
  64505. }(BABYLON.Texture));
  64506. BABYLON.ProceduralTexture = ProceduralTexture;
  64507. })(BABYLON || (BABYLON = {}));
  64508. //# sourceMappingURL=babylon.proceduralTexture.js.map
  64509. var BABYLON;
  64510. (function (BABYLON) {
  64511. var CustomProceduralTexture = /** @class */ (function (_super) {
  64512. __extends(CustomProceduralTexture, _super);
  64513. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  64514. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  64515. _this._animate = true;
  64516. _this._time = 0;
  64517. _this._texturePath = texturePath;
  64518. //Try to load json
  64519. _this.loadJson(texturePath);
  64520. _this.refreshRate = 1;
  64521. return _this;
  64522. }
  64523. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  64524. var _this = this;
  64525. var noConfigFile = function () {
  64526. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  64527. try {
  64528. _this.setFragment(_this._texturePath);
  64529. }
  64530. catch (ex) {
  64531. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  64532. }
  64533. };
  64534. var configFileUrl = jsonUrl + "/config.json";
  64535. var xhr = new XMLHttpRequest();
  64536. xhr.open("GET", configFileUrl, true);
  64537. xhr.addEventListener("load", function () {
  64538. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  64539. try {
  64540. _this._config = JSON.parse(xhr.response);
  64541. _this.updateShaderUniforms();
  64542. _this.updateTextures();
  64543. _this.setFragment(_this._texturePath + "/custom");
  64544. _this._animate = _this._config.animate;
  64545. _this.refreshRate = _this._config.refreshrate;
  64546. }
  64547. catch (ex) {
  64548. noConfigFile();
  64549. }
  64550. }
  64551. else {
  64552. noConfigFile();
  64553. }
  64554. }, false);
  64555. xhr.addEventListener("error", function () {
  64556. noConfigFile();
  64557. }, false);
  64558. try {
  64559. xhr.send();
  64560. }
  64561. catch (ex) {
  64562. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  64563. }
  64564. };
  64565. CustomProceduralTexture.prototype.isReady = function () {
  64566. if (!_super.prototype.isReady.call(this)) {
  64567. return false;
  64568. }
  64569. for (var name in this._textures) {
  64570. var texture = this._textures[name];
  64571. if (!texture.isReady()) {
  64572. return false;
  64573. }
  64574. }
  64575. return true;
  64576. };
  64577. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  64578. var scene = this.getScene();
  64579. if (this._animate && scene) {
  64580. this._time += scene.getAnimationRatio() * 0.03;
  64581. this.updateShaderUniforms();
  64582. }
  64583. _super.prototype.render.call(this, useCameraPostProcess);
  64584. };
  64585. CustomProceduralTexture.prototype.updateTextures = function () {
  64586. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  64587. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  64588. }
  64589. };
  64590. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  64591. if (this._config) {
  64592. for (var j = 0; j < this._config.uniforms.length; j++) {
  64593. var uniform = this._config.uniforms[j];
  64594. switch (uniform.type) {
  64595. case "float":
  64596. this.setFloat(uniform.name, uniform.value);
  64597. break;
  64598. case "color3":
  64599. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  64600. break;
  64601. case "color4":
  64602. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  64603. break;
  64604. case "vector2":
  64605. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  64606. break;
  64607. case "vector3":
  64608. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  64609. break;
  64610. }
  64611. }
  64612. }
  64613. this.setFloat("time", this._time);
  64614. };
  64615. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  64616. get: function () {
  64617. return this._animate;
  64618. },
  64619. set: function (value) {
  64620. this._animate = value;
  64621. },
  64622. enumerable: true,
  64623. configurable: true
  64624. });
  64625. return CustomProceduralTexture;
  64626. }(BABYLON.ProceduralTexture));
  64627. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  64628. })(BABYLON || (BABYLON = {}));
  64629. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  64630. var BABYLON;
  64631. (function (BABYLON) {
  64632. var FreeCameraGamepadInput = /** @class */ (function () {
  64633. function FreeCameraGamepadInput() {
  64634. this.gamepadAngularSensibility = 200;
  64635. this.gamepadMoveSensibility = 40;
  64636. // private members
  64637. this._cameraTransform = BABYLON.Matrix.Identity();
  64638. this._deltaTransform = BABYLON.Vector3.Zero();
  64639. this._vector3 = BABYLON.Vector3.Zero();
  64640. this._vector2 = BABYLON.Vector2.Zero();
  64641. }
  64642. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  64643. var _this = this;
  64644. var manager = this.camera.getScene().gamepadManager;
  64645. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  64646. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  64647. // prioritize XBOX gamepads.
  64648. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  64649. _this.gamepad = gamepad;
  64650. }
  64651. }
  64652. });
  64653. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  64654. if (_this.gamepad === gamepad) {
  64655. _this.gamepad = null;
  64656. }
  64657. });
  64658. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  64659. };
  64660. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  64661. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  64662. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  64663. this.gamepad = null;
  64664. };
  64665. FreeCameraGamepadInput.prototype.checkInputs = function () {
  64666. if (this.gamepad && this.gamepad.leftStick) {
  64667. var camera = this.camera;
  64668. var LSValues = this.gamepad.leftStick;
  64669. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  64670. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  64671. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  64672. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  64673. var RSValues = this.gamepad.rightStick;
  64674. if (RSValues) {
  64675. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  64676. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  64677. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  64678. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  64679. }
  64680. else {
  64681. RSValues = { x: 0, y: 0 };
  64682. }
  64683. if (!camera.rotationQuaternion) {
  64684. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  64685. }
  64686. else {
  64687. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  64688. }
  64689. var speed = camera._computeLocalCameraSpeed() * 50.0;
  64690. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  64691. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  64692. camera.cameraDirection.addInPlace(this._deltaTransform);
  64693. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  64694. camera.cameraRotation.addInPlace(this._vector2);
  64695. }
  64696. };
  64697. FreeCameraGamepadInput.prototype.getClassName = function () {
  64698. return "FreeCameraGamepadInput";
  64699. };
  64700. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  64701. return "gamepad";
  64702. };
  64703. __decorate([
  64704. BABYLON.serialize()
  64705. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  64706. __decorate([
  64707. BABYLON.serialize()
  64708. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  64709. return FreeCameraGamepadInput;
  64710. }());
  64711. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  64712. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  64713. })(BABYLON || (BABYLON = {}));
  64714. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  64715. var BABYLON;
  64716. (function (BABYLON) {
  64717. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  64718. function ArcRotateCameraGamepadInput() {
  64719. this.gamepadRotationSensibility = 80;
  64720. this.gamepadMoveSensibility = 40;
  64721. }
  64722. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  64723. var _this = this;
  64724. var manager = this.camera.getScene().gamepadManager;
  64725. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  64726. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  64727. // prioritize XBOX gamepads.
  64728. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  64729. _this.gamepad = gamepad;
  64730. }
  64731. }
  64732. });
  64733. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  64734. if (_this.gamepad === gamepad) {
  64735. _this.gamepad = null;
  64736. }
  64737. });
  64738. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  64739. };
  64740. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  64741. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  64742. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  64743. this.gamepad = null;
  64744. };
  64745. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  64746. if (this.gamepad) {
  64747. var camera = this.camera;
  64748. var RSValues = this.gamepad.rightStick;
  64749. if (RSValues) {
  64750. if (RSValues.x != 0) {
  64751. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  64752. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  64753. camera.inertialAlphaOffset += normalizedRX;
  64754. }
  64755. }
  64756. if (RSValues.y != 0) {
  64757. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  64758. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  64759. camera.inertialBetaOffset += normalizedRY;
  64760. }
  64761. }
  64762. }
  64763. var LSValues = this.gamepad.leftStick;
  64764. if (LSValues && LSValues.y != 0) {
  64765. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  64766. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  64767. this.camera.inertialRadiusOffset -= normalizedLY;
  64768. }
  64769. }
  64770. }
  64771. };
  64772. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  64773. return "ArcRotateCameraGamepadInput";
  64774. };
  64775. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  64776. return "gamepad";
  64777. };
  64778. __decorate([
  64779. BABYLON.serialize()
  64780. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  64781. __decorate([
  64782. BABYLON.serialize()
  64783. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  64784. return ArcRotateCameraGamepadInput;
  64785. }());
  64786. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  64787. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  64788. })(BABYLON || (BABYLON = {}));
  64789. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  64790. var BABYLON;
  64791. (function (BABYLON) {
  64792. var GamepadManager = /** @class */ (function () {
  64793. function GamepadManager(_scene) {
  64794. var _this = this;
  64795. this._scene = _scene;
  64796. this._babylonGamepads = [];
  64797. this._oneGamepadConnected = false;
  64798. this._isMonitoring = false;
  64799. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  64800. if (!BABYLON.Tools.IsWindowObjectExist()) {
  64801. this._gamepadEventSupported = false;
  64802. }
  64803. else {
  64804. this._gamepadEventSupported = 'GamepadEvent' in window;
  64805. this._gamepadSupport = (navigator.getGamepads ||
  64806. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  64807. }
  64808. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  64809. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  64810. for (var i in _this._babylonGamepads) {
  64811. var gamepad = _this._babylonGamepads[i];
  64812. if (gamepad && gamepad._isConnected) {
  64813. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  64814. }
  64815. }
  64816. });
  64817. this._onGamepadConnectedEvent = function (evt) {
  64818. var gamepad = evt.gamepad;
  64819. if (gamepad.index in _this._babylonGamepads) {
  64820. if (_this._babylonGamepads[gamepad.index].isConnected) {
  64821. return;
  64822. }
  64823. }
  64824. var newGamepad;
  64825. if (_this._babylonGamepads[gamepad.index]) {
  64826. newGamepad = _this._babylonGamepads[gamepad.index];
  64827. newGamepad.browserGamepad = gamepad;
  64828. newGamepad._isConnected = true;
  64829. }
  64830. else {
  64831. newGamepad = _this._addNewGamepad(gamepad);
  64832. }
  64833. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  64834. _this._startMonitoringGamepads();
  64835. };
  64836. this._onGamepadDisconnectedEvent = function (evt) {
  64837. var gamepad = evt.gamepad;
  64838. // Remove the gamepad from the list of gamepads to monitor.
  64839. for (var i in _this._babylonGamepads) {
  64840. if (_this._babylonGamepads[i].index === gamepad.index) {
  64841. var disconnectedGamepad = _this._babylonGamepads[i];
  64842. disconnectedGamepad._isConnected = false;
  64843. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  64844. break;
  64845. }
  64846. }
  64847. };
  64848. if (this._gamepadSupport) {
  64849. //first add already-connected gamepads
  64850. this._updateGamepadObjects();
  64851. if (this._babylonGamepads.length) {
  64852. this._startMonitoringGamepads();
  64853. }
  64854. // Checking if the gamepad connected event is supported (like in Firefox)
  64855. if (this._gamepadEventSupported) {
  64856. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  64857. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  64858. }
  64859. else {
  64860. this._startMonitoringGamepads();
  64861. }
  64862. }
  64863. }
  64864. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  64865. get: function () {
  64866. return this._babylonGamepads;
  64867. },
  64868. enumerable: true,
  64869. configurable: true
  64870. });
  64871. GamepadManager.prototype.getGamepadByType = function (type) {
  64872. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  64873. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  64874. var gamepad = _a[_i];
  64875. if (gamepad && gamepad.type === type) {
  64876. return gamepad;
  64877. }
  64878. }
  64879. return null;
  64880. };
  64881. GamepadManager.prototype.dispose = function () {
  64882. if (this._gamepadEventSupported) {
  64883. if (this._onGamepadConnectedEvent) {
  64884. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  64885. }
  64886. if (this._onGamepadDisconnectedEvent) {
  64887. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  64888. }
  64889. this._onGamepadConnectedEvent = null;
  64890. this._onGamepadDisconnectedEvent = null;
  64891. }
  64892. this._babylonGamepads.forEach(function (gamepad) {
  64893. gamepad.dispose();
  64894. });
  64895. this.onGamepadConnectedObservable.clear();
  64896. this.onGamepadDisconnectedObservable.clear();
  64897. this._oneGamepadConnected = false;
  64898. this._stopMonitoringGamepads();
  64899. this._babylonGamepads = [];
  64900. };
  64901. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  64902. if (!this._oneGamepadConnected) {
  64903. this._oneGamepadConnected = true;
  64904. }
  64905. var newGamepad;
  64906. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  64907. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  64908. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  64909. }
  64910. else if (gamepad.pose) {
  64911. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  64912. }
  64913. else {
  64914. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  64915. }
  64916. this._babylonGamepads[newGamepad.index] = newGamepad;
  64917. return newGamepad;
  64918. };
  64919. GamepadManager.prototype._startMonitoringGamepads = function () {
  64920. if (!this._isMonitoring) {
  64921. this._isMonitoring = true;
  64922. //back-comp
  64923. if (!this._scene) {
  64924. this._checkGamepadsStatus();
  64925. }
  64926. }
  64927. };
  64928. GamepadManager.prototype._stopMonitoringGamepads = function () {
  64929. this._isMonitoring = false;
  64930. };
  64931. GamepadManager.prototype._checkGamepadsStatus = function () {
  64932. var _this = this;
  64933. // Hack to be compatible Chrome
  64934. this._updateGamepadObjects();
  64935. for (var i in this._babylonGamepads) {
  64936. var gamepad = this._babylonGamepads[i];
  64937. if (!gamepad || !gamepad.isConnected) {
  64938. continue;
  64939. }
  64940. gamepad.update();
  64941. }
  64942. if (this._isMonitoring && !this._scene) {
  64943. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  64944. }
  64945. };
  64946. // This function is called only on Chrome, which does not properly support
  64947. // connection/disconnection events and forces you to recopy again the gamepad object
  64948. GamepadManager.prototype._updateGamepadObjects = function () {
  64949. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  64950. for (var i = 0; i < gamepads.length; i++) {
  64951. if (gamepads[i]) {
  64952. if (!this._babylonGamepads[gamepads[i].index]) {
  64953. var newGamepad = this._addNewGamepad(gamepads[i]);
  64954. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  64955. }
  64956. else {
  64957. // Forced to copy again this object for Chrome for unknown reason
  64958. this._babylonGamepads[i].browserGamepad = gamepads[i];
  64959. if (!this._babylonGamepads[i].isConnected) {
  64960. this._babylonGamepads[i]._isConnected = true;
  64961. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  64962. }
  64963. }
  64964. }
  64965. }
  64966. };
  64967. return GamepadManager;
  64968. }());
  64969. BABYLON.GamepadManager = GamepadManager;
  64970. })(BABYLON || (BABYLON = {}));
  64971. //# sourceMappingURL=babylon.gamepadManager.js.map
  64972. var BABYLON;
  64973. (function (BABYLON) {
  64974. var StickValues = /** @class */ (function () {
  64975. function StickValues(x, y) {
  64976. this.x = x;
  64977. this.y = y;
  64978. }
  64979. return StickValues;
  64980. }());
  64981. BABYLON.StickValues = StickValues;
  64982. var Gamepad = /** @class */ (function () {
  64983. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  64984. if (leftStickX === void 0) { leftStickX = 0; }
  64985. if (leftStickY === void 0) { leftStickY = 1; }
  64986. if (rightStickX === void 0) { rightStickX = 2; }
  64987. if (rightStickY === void 0) { rightStickY = 3; }
  64988. this.id = id;
  64989. this.index = index;
  64990. this.browserGamepad = browserGamepad;
  64991. this._isConnected = true;
  64992. this._invertLeftStickY = false;
  64993. this.type = Gamepad.GAMEPAD;
  64994. this._leftStickAxisX = leftStickX;
  64995. this._leftStickAxisY = leftStickY;
  64996. this._rightStickAxisX = rightStickX;
  64997. this._rightStickAxisY = rightStickY;
  64998. if (this.browserGamepad.axes.length >= 2) {
  64999. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  65000. }
  65001. if (this.browserGamepad.axes.length >= 4) {
  65002. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  65003. }
  65004. }
  65005. Object.defineProperty(Gamepad.prototype, "isConnected", {
  65006. get: function () {
  65007. return this._isConnected;
  65008. },
  65009. enumerable: true,
  65010. configurable: true
  65011. });
  65012. Gamepad.prototype.onleftstickchanged = function (callback) {
  65013. this._onleftstickchanged = callback;
  65014. };
  65015. Gamepad.prototype.onrightstickchanged = function (callback) {
  65016. this._onrightstickchanged = callback;
  65017. };
  65018. Object.defineProperty(Gamepad.prototype, "leftStick", {
  65019. get: function () {
  65020. return this._leftStick;
  65021. },
  65022. set: function (newValues) {
  65023. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  65024. this._onleftstickchanged(newValues);
  65025. }
  65026. this._leftStick = newValues;
  65027. },
  65028. enumerable: true,
  65029. configurable: true
  65030. });
  65031. Object.defineProperty(Gamepad.prototype, "rightStick", {
  65032. get: function () {
  65033. return this._rightStick;
  65034. },
  65035. set: function (newValues) {
  65036. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  65037. this._onrightstickchanged(newValues);
  65038. }
  65039. this._rightStick = newValues;
  65040. },
  65041. enumerable: true,
  65042. configurable: true
  65043. });
  65044. Gamepad.prototype.update = function () {
  65045. if (this._leftStick) {
  65046. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  65047. if (this._invertLeftStickY) {
  65048. this.leftStick.y *= -1;
  65049. }
  65050. }
  65051. if (this._rightStick) {
  65052. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  65053. }
  65054. };
  65055. Gamepad.prototype.dispose = function () {
  65056. };
  65057. Gamepad.GAMEPAD = 0;
  65058. Gamepad.GENERIC = 1;
  65059. Gamepad.XBOX = 2;
  65060. Gamepad.POSE_ENABLED = 3;
  65061. return Gamepad;
  65062. }());
  65063. BABYLON.Gamepad = Gamepad;
  65064. var GenericPad = /** @class */ (function (_super) {
  65065. __extends(GenericPad, _super);
  65066. function GenericPad(id, index, browserGamepad) {
  65067. var _this = _super.call(this, id, index, browserGamepad) || this;
  65068. _this.onButtonDownObservable = new BABYLON.Observable();
  65069. _this.onButtonUpObservable = new BABYLON.Observable();
  65070. _this.type = Gamepad.GENERIC;
  65071. _this._buttons = new Array(browserGamepad.buttons.length);
  65072. return _this;
  65073. }
  65074. GenericPad.prototype.onbuttondown = function (callback) {
  65075. this._onbuttondown = callback;
  65076. };
  65077. GenericPad.prototype.onbuttonup = function (callback) {
  65078. this._onbuttonup = callback;
  65079. };
  65080. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  65081. if (newValue !== currentValue) {
  65082. if (newValue === 1) {
  65083. if (this._onbuttondown) {
  65084. this._onbuttondown(buttonIndex);
  65085. }
  65086. this.onButtonDownObservable.notifyObservers(buttonIndex);
  65087. }
  65088. if (newValue === 0) {
  65089. if (this._onbuttonup) {
  65090. this._onbuttonup(buttonIndex);
  65091. }
  65092. this.onButtonUpObservable.notifyObservers(buttonIndex);
  65093. }
  65094. }
  65095. return newValue;
  65096. };
  65097. GenericPad.prototype.update = function () {
  65098. _super.prototype.update.call(this);
  65099. for (var index = 0; index < this._buttons.length; index++) {
  65100. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  65101. }
  65102. };
  65103. GenericPad.prototype.dispose = function () {
  65104. _super.prototype.dispose.call(this);
  65105. this.onButtonDownObservable.clear();
  65106. this.onButtonUpObservable.clear();
  65107. };
  65108. return GenericPad;
  65109. }(Gamepad));
  65110. BABYLON.GenericPad = GenericPad;
  65111. })(BABYLON || (BABYLON = {}));
  65112. //# sourceMappingURL=babylon.gamepad.js.map
  65113. var BABYLON;
  65114. (function (BABYLON) {
  65115. var Xbox360Button;
  65116. (function (Xbox360Button) {
  65117. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  65118. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  65119. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  65120. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  65121. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  65122. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  65123. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  65124. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  65125. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  65126. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  65127. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  65128. var Xbox360Dpad;
  65129. (function (Xbox360Dpad) {
  65130. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  65131. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  65132. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  65133. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  65134. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  65135. var Xbox360Pad = /** @class */ (function (_super) {
  65136. __extends(Xbox360Pad, _super);
  65137. function Xbox360Pad(id, index, gamepad, xboxOne) {
  65138. if (xboxOne === void 0) { xboxOne = false; }
  65139. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  65140. _this._leftTrigger = 0;
  65141. _this._rightTrigger = 0;
  65142. _this.onButtonDownObservable = new BABYLON.Observable();
  65143. _this.onButtonUpObservable = new BABYLON.Observable();
  65144. _this.onPadDownObservable = new BABYLON.Observable();
  65145. _this.onPadUpObservable = new BABYLON.Observable();
  65146. _this._buttonA = 0;
  65147. _this._buttonB = 0;
  65148. _this._buttonX = 0;
  65149. _this._buttonY = 0;
  65150. _this._buttonBack = 0;
  65151. _this._buttonStart = 0;
  65152. _this._buttonLB = 0;
  65153. _this._buttonRB = 0;
  65154. _this._buttonLeftStick = 0;
  65155. _this._buttonRightStick = 0;
  65156. _this._dPadUp = 0;
  65157. _this._dPadDown = 0;
  65158. _this._dPadLeft = 0;
  65159. _this._dPadRight = 0;
  65160. _this._isXboxOnePad = false;
  65161. _this.type = BABYLON.Gamepad.XBOX;
  65162. _this._isXboxOnePad = xboxOne;
  65163. return _this;
  65164. }
  65165. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  65166. this._onlefttriggerchanged = callback;
  65167. };
  65168. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  65169. this._onrighttriggerchanged = callback;
  65170. };
  65171. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  65172. get: function () {
  65173. return this._leftTrigger;
  65174. },
  65175. set: function (newValue) {
  65176. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  65177. this._onlefttriggerchanged(newValue);
  65178. }
  65179. this._leftTrigger = newValue;
  65180. },
  65181. enumerable: true,
  65182. configurable: true
  65183. });
  65184. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  65185. get: function () {
  65186. return this._rightTrigger;
  65187. },
  65188. set: function (newValue) {
  65189. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  65190. this._onrighttriggerchanged(newValue);
  65191. }
  65192. this._rightTrigger = newValue;
  65193. },
  65194. enumerable: true,
  65195. configurable: true
  65196. });
  65197. Xbox360Pad.prototype.onbuttondown = function (callback) {
  65198. this._onbuttondown = callback;
  65199. };
  65200. Xbox360Pad.prototype.onbuttonup = function (callback) {
  65201. this._onbuttonup = callback;
  65202. };
  65203. Xbox360Pad.prototype.ondpaddown = function (callback) {
  65204. this._ondpaddown = callback;
  65205. };
  65206. Xbox360Pad.prototype.ondpadup = function (callback) {
  65207. this._ondpadup = callback;
  65208. };
  65209. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  65210. if (newValue !== currentValue) {
  65211. if (newValue === 1) {
  65212. if (this._onbuttondown) {
  65213. this._onbuttondown(buttonType);
  65214. }
  65215. this.onButtonDownObservable.notifyObservers(buttonType);
  65216. }
  65217. if (newValue === 0) {
  65218. if (this._onbuttonup) {
  65219. this._onbuttonup(buttonType);
  65220. }
  65221. this.onButtonUpObservable.notifyObservers(buttonType);
  65222. }
  65223. }
  65224. return newValue;
  65225. };
  65226. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  65227. if (newValue !== currentValue) {
  65228. if (newValue === 1) {
  65229. if (this._ondpaddown) {
  65230. this._ondpaddown(buttonType);
  65231. }
  65232. this.onPadDownObservable.notifyObservers(buttonType);
  65233. }
  65234. if (newValue === 0) {
  65235. if (this._ondpadup) {
  65236. this._ondpadup(buttonType);
  65237. }
  65238. this.onPadUpObservable.notifyObservers(buttonType);
  65239. }
  65240. }
  65241. return newValue;
  65242. };
  65243. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  65244. get: function () {
  65245. return this._buttonA;
  65246. },
  65247. set: function (value) {
  65248. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  65249. },
  65250. enumerable: true,
  65251. configurable: true
  65252. });
  65253. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  65254. get: function () {
  65255. return this._buttonB;
  65256. },
  65257. set: function (value) {
  65258. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  65259. },
  65260. enumerable: true,
  65261. configurable: true
  65262. });
  65263. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  65264. get: function () {
  65265. return this._buttonX;
  65266. },
  65267. set: function (value) {
  65268. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  65269. },
  65270. enumerable: true,
  65271. configurable: true
  65272. });
  65273. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  65274. get: function () {
  65275. return this._buttonY;
  65276. },
  65277. set: function (value) {
  65278. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  65279. },
  65280. enumerable: true,
  65281. configurable: true
  65282. });
  65283. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  65284. get: function () {
  65285. return this._buttonStart;
  65286. },
  65287. set: function (value) {
  65288. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  65289. },
  65290. enumerable: true,
  65291. configurable: true
  65292. });
  65293. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  65294. get: function () {
  65295. return this._buttonBack;
  65296. },
  65297. set: function (value) {
  65298. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  65299. },
  65300. enumerable: true,
  65301. configurable: true
  65302. });
  65303. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  65304. get: function () {
  65305. return this._buttonLB;
  65306. },
  65307. set: function (value) {
  65308. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  65309. },
  65310. enumerable: true,
  65311. configurable: true
  65312. });
  65313. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  65314. get: function () {
  65315. return this._buttonRB;
  65316. },
  65317. set: function (value) {
  65318. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  65319. },
  65320. enumerable: true,
  65321. configurable: true
  65322. });
  65323. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  65324. get: function () {
  65325. return this._buttonLeftStick;
  65326. },
  65327. set: function (value) {
  65328. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  65329. },
  65330. enumerable: true,
  65331. configurable: true
  65332. });
  65333. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  65334. get: function () {
  65335. return this._buttonRightStick;
  65336. },
  65337. set: function (value) {
  65338. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  65339. },
  65340. enumerable: true,
  65341. configurable: true
  65342. });
  65343. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  65344. get: function () {
  65345. return this._dPadUp;
  65346. },
  65347. set: function (value) {
  65348. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  65349. },
  65350. enumerable: true,
  65351. configurable: true
  65352. });
  65353. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  65354. get: function () {
  65355. return this._dPadDown;
  65356. },
  65357. set: function (value) {
  65358. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  65359. },
  65360. enumerable: true,
  65361. configurable: true
  65362. });
  65363. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  65364. get: function () {
  65365. return this._dPadLeft;
  65366. },
  65367. set: function (value) {
  65368. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  65369. },
  65370. enumerable: true,
  65371. configurable: true
  65372. });
  65373. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  65374. get: function () {
  65375. return this._dPadRight;
  65376. },
  65377. set: function (value) {
  65378. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  65379. },
  65380. enumerable: true,
  65381. configurable: true
  65382. });
  65383. Xbox360Pad.prototype.update = function () {
  65384. _super.prototype.update.call(this);
  65385. if (this._isXboxOnePad) {
  65386. this.buttonA = this.browserGamepad.buttons[0].value;
  65387. this.buttonB = this.browserGamepad.buttons[1].value;
  65388. this.buttonX = this.browserGamepad.buttons[2].value;
  65389. this.buttonY = this.browserGamepad.buttons[3].value;
  65390. this.buttonLB = this.browserGamepad.buttons[4].value;
  65391. this.buttonRB = this.browserGamepad.buttons[5].value;
  65392. this.leftTrigger = this.browserGamepad.axes[2];
  65393. this.rightTrigger = this.browserGamepad.axes[5];
  65394. this.buttonBack = this.browserGamepad.buttons[9].value;
  65395. this.buttonStart = this.browserGamepad.buttons[8].value;
  65396. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  65397. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  65398. this.dPadUp = this.browserGamepad.buttons[11].value;
  65399. this.dPadDown = this.browserGamepad.buttons[12].value;
  65400. this.dPadLeft = this.browserGamepad.buttons[13].value;
  65401. this.dPadRight = this.browserGamepad.buttons[14].value;
  65402. }
  65403. else {
  65404. this.buttonA = this.browserGamepad.buttons[0].value;
  65405. this.buttonB = this.browserGamepad.buttons[1].value;
  65406. this.buttonX = this.browserGamepad.buttons[2].value;
  65407. this.buttonY = this.browserGamepad.buttons[3].value;
  65408. this.buttonLB = this.browserGamepad.buttons[4].value;
  65409. this.buttonRB = this.browserGamepad.buttons[5].value;
  65410. this.leftTrigger = this.browserGamepad.buttons[6].value;
  65411. this.rightTrigger = this.browserGamepad.buttons[7].value;
  65412. this.buttonBack = this.browserGamepad.buttons[8].value;
  65413. this.buttonStart = this.browserGamepad.buttons[9].value;
  65414. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  65415. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  65416. this.dPadUp = this.browserGamepad.buttons[12].value;
  65417. this.dPadDown = this.browserGamepad.buttons[13].value;
  65418. this.dPadLeft = this.browserGamepad.buttons[14].value;
  65419. this.dPadRight = this.browserGamepad.buttons[15].value;
  65420. }
  65421. };
  65422. Xbox360Pad.prototype.dispose = function () {
  65423. _super.prototype.dispose.call(this);
  65424. this.onButtonDownObservable.clear();
  65425. this.onButtonUpObservable.clear();
  65426. this.onPadDownObservable.clear();
  65427. this.onPadUpObservable.clear();
  65428. };
  65429. return Xbox360Pad;
  65430. }(BABYLON.Gamepad));
  65431. BABYLON.Xbox360Pad = Xbox360Pad;
  65432. })(BABYLON || (BABYLON = {}));
  65433. //# sourceMappingURL=babylon.xboxGamepad.js.map
  65434. var BABYLON;
  65435. (function (BABYLON) {
  65436. var PoseEnabledControllerType;
  65437. (function (PoseEnabledControllerType) {
  65438. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  65439. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  65440. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  65441. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  65442. /**
  65443. * Google Daydream
  65444. */
  65445. PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM";
  65446. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC";
  65447. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  65448. var PoseEnabledControllerHelper = /** @class */ (function () {
  65449. function PoseEnabledControllerHelper() {
  65450. }
  65451. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  65452. // Oculus Touch
  65453. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  65454. return new BABYLON.OculusTouchController(vrGamepad);
  65455. }
  65456. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  65457. return new BABYLON.WindowsMotionController(vrGamepad);
  65458. }
  65459. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  65460. return new BABYLON.ViveController(vrGamepad);
  65461. }
  65462. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0) {
  65463. return new BABYLON.GearVRController(vrGamepad);
  65464. }
  65465. else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
  65466. return new BABYLON.DaydreamController(vrGamepad);
  65467. }
  65468. else {
  65469. return new BABYLON.GenericController(vrGamepad);
  65470. }
  65471. };
  65472. return PoseEnabledControllerHelper;
  65473. }());
  65474. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  65475. var PoseEnabledController = /** @class */ (function (_super) {
  65476. __extends(PoseEnabledController, _super);
  65477. function PoseEnabledController(browserGamepad) {
  65478. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  65479. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  65480. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  65481. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  65482. // Represents device position and rotation in babylon space
  65483. _this.devicePosition = BABYLON.Vector3.Zero();
  65484. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  65485. _this.deviceScaleFactor = 1;
  65486. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  65487. _this._deviceToWorld = BABYLON.Matrix.Identity();
  65488. /**
  65489. * Node to be used when casting a ray from the controller
  65490. */
  65491. _this._pointingPoseNode = null;
  65492. _this._workingMatrix = BABYLON.Matrix.Identity();
  65493. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  65494. _this.controllerType = PoseEnabledControllerType.GENERIC;
  65495. _this.position = BABYLON.Vector3.Zero();
  65496. _this.rotationQuaternion = new BABYLON.Quaternion();
  65497. _this._calculatedPosition = BABYLON.Vector3.Zero();
  65498. _this._calculatedRotation = new BABYLON.Quaternion();
  65499. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  65500. return _this;
  65501. }
  65502. PoseEnabledController.prototype.update = function () {
  65503. _super.prototype.update.call(this);
  65504. var pose = this.browserGamepad.pose;
  65505. this.updateFromDevice(pose);
  65506. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  65507. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  65508. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  65509. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  65510. if (this._mesh) {
  65511. this._mesh.position.copyFrom(this.devicePosition);
  65512. if (this._mesh.rotationQuaternion) {
  65513. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  65514. }
  65515. }
  65516. };
  65517. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  65518. if (poseData) {
  65519. this.rawPose = poseData;
  65520. if (poseData.position) {
  65521. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  65522. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  65523. this._deviceRoomPosition.z *= -1;
  65524. }
  65525. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  65526. this._calculatedPosition.addInPlace(this.position);
  65527. }
  65528. var pose = this.rawPose;
  65529. if (poseData.orientation && pose.orientation) {
  65530. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  65531. if (this._mesh) {
  65532. if (this._mesh.getScene().useRightHandedSystem) {
  65533. this._deviceRoomRotationQuaternion.z *= -1;
  65534. this._deviceRoomRotationQuaternion.w *= -1;
  65535. }
  65536. else {
  65537. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  65538. }
  65539. }
  65540. // if the camera is set, rotate to the camera's rotation
  65541. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  65542. }
  65543. }
  65544. };
  65545. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  65546. if (this._mesh) {
  65547. this._mesh.parent = null;
  65548. }
  65549. this._mesh = mesh;
  65550. if (this._poseControlledCamera) {
  65551. this._mesh.parent = this._poseControlledCamera;
  65552. }
  65553. if (!this._mesh.rotationQuaternion) {
  65554. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  65555. }
  65556. };
  65557. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  65558. this._poseControlledCamera = camera;
  65559. if (this._mesh) {
  65560. this._mesh.parent = this._poseControlledCamera;
  65561. }
  65562. };
  65563. PoseEnabledController.prototype.dispose = function () {
  65564. if (this._mesh) {
  65565. this._mesh.dispose();
  65566. }
  65567. this._mesh = null;
  65568. _super.prototype.dispose.call(this);
  65569. };
  65570. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  65571. get: function () {
  65572. return this._mesh;
  65573. },
  65574. enumerable: true,
  65575. configurable: true
  65576. });
  65577. PoseEnabledController.prototype.getForwardRay = function (length) {
  65578. if (length === void 0) { length = 100; }
  65579. if (!this.mesh) {
  65580. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  65581. }
  65582. var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();
  65583. var origin = m.getTranslation();
  65584. var forward = new BABYLON.Vector3(0, 0, -1);
  65585. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  65586. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  65587. return new BABYLON.Ray(origin, direction, length);
  65588. };
  65589. /**
  65590. * Name of the child mesh that can be used to cast a ray from the controller
  65591. */
  65592. PoseEnabledController.POINTING_POSE = "POINTING_POSE";
  65593. return PoseEnabledController;
  65594. }(BABYLON.Gamepad));
  65595. BABYLON.PoseEnabledController = PoseEnabledController;
  65596. })(BABYLON || (BABYLON = {}));
  65597. //# sourceMappingURL=babylon.poseEnabledController.js.map
  65598. var BABYLON;
  65599. (function (BABYLON) {
  65600. var WebVRController = /** @class */ (function (_super) {
  65601. __extends(WebVRController, _super);
  65602. function WebVRController(vrGamepad) {
  65603. var _this = _super.call(this, vrGamepad) || this;
  65604. // Observables
  65605. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  65606. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  65607. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  65608. _this.onPadStateChangedObservable = new BABYLON.Observable();
  65609. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  65610. _this.pad = { x: 0, y: 0 };
  65611. // avoid GC, store state in a tmp object
  65612. _this._changes = {
  65613. pressChanged: false,
  65614. touchChanged: false,
  65615. valueChanged: false,
  65616. changed: false
  65617. };
  65618. _this._buttons = new Array(vrGamepad.buttons.length);
  65619. _this.hand = vrGamepad.hand;
  65620. return _this;
  65621. }
  65622. WebVRController.prototype.onButtonStateChange = function (callback) {
  65623. this._onButtonStateChange = callback;
  65624. };
  65625. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  65626. get: function () {
  65627. return this._defaultModel;
  65628. },
  65629. enumerable: true,
  65630. configurable: true
  65631. });
  65632. WebVRController.prototype.update = function () {
  65633. _super.prototype.update.call(this);
  65634. for (var index = 0; index < this._buttons.length; index++) {
  65635. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  65636. }
  65637. ;
  65638. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  65639. this.pad.x = this.leftStick.x;
  65640. this.pad.y = this.leftStick.y;
  65641. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  65642. }
  65643. };
  65644. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  65645. if (!newState) {
  65646. newState = {
  65647. pressed: false,
  65648. touched: false,
  65649. value: 0
  65650. };
  65651. }
  65652. if (!currentState) {
  65653. this._buttons[buttonIndex] = {
  65654. pressed: newState.pressed,
  65655. touched: newState.touched,
  65656. value: newState.value
  65657. };
  65658. return;
  65659. }
  65660. this._checkChanges(newState, currentState);
  65661. if (this._changes.changed) {
  65662. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  65663. this._handleButtonChange(buttonIndex, newState, this._changes);
  65664. }
  65665. this._buttons[buttonIndex].pressed = newState.pressed;
  65666. this._buttons[buttonIndex].touched = newState.touched;
  65667. // oculus triggers are never 0, thou not touched.
  65668. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  65669. };
  65670. WebVRController.prototype._checkChanges = function (newState, currentState) {
  65671. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  65672. this._changes.touchChanged = newState.touched !== currentState.touched;
  65673. this._changes.valueChanged = newState.value !== currentState.value;
  65674. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  65675. return this._changes;
  65676. };
  65677. WebVRController.prototype.dispose = function () {
  65678. _super.prototype.dispose.call(this);
  65679. this.onTriggerStateChangedObservable.clear();
  65680. this.onMainButtonStateChangedObservable.clear();
  65681. this.onSecondaryButtonStateChangedObservable.clear();
  65682. this.onPadStateChangedObservable.clear();
  65683. this.onPadValuesChangedObservable.clear();
  65684. };
  65685. return WebVRController;
  65686. }(BABYLON.PoseEnabledController));
  65687. BABYLON.WebVRController = WebVRController;
  65688. })(BABYLON || (BABYLON = {}));
  65689. //# sourceMappingURL=babylon.webVRController.js.map
  65690. var BABYLON;
  65691. (function (BABYLON) {
  65692. var OculusTouchController = /** @class */ (function (_super) {
  65693. __extends(OculusTouchController, _super);
  65694. function OculusTouchController(vrGamepad) {
  65695. var _this = _super.call(this, vrGamepad) || this;
  65696. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  65697. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  65698. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  65699. return _this;
  65700. }
  65701. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  65702. var _this = this;
  65703. var meshName;
  65704. // Hand
  65705. if (this.hand === 'left') {
  65706. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  65707. }
  65708. else {
  65709. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  65710. }
  65711. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  65712. /*
  65713. Parent Mesh name: oculus_touch_left
  65714. - body
  65715. - trigger
  65716. - thumbstick
  65717. - grip
  65718. - button_y
  65719. - button_x
  65720. - button_enter
  65721. */
  65722. _this._defaultModel = newMeshes[1];
  65723. _this.attachToMesh(_this._defaultModel);
  65724. if (meshLoaded) {
  65725. meshLoaded(_this._defaultModel);
  65726. }
  65727. });
  65728. };
  65729. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  65730. // helper getters for left and right hand.
  65731. get: function () {
  65732. if (this.hand === 'right') {
  65733. return this.onMainButtonStateChangedObservable;
  65734. }
  65735. else {
  65736. throw new Error('No A button on left hand');
  65737. }
  65738. },
  65739. enumerable: true,
  65740. configurable: true
  65741. });
  65742. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  65743. get: function () {
  65744. if (this.hand === 'right') {
  65745. return this.onSecondaryButtonStateChangedObservable;
  65746. }
  65747. else {
  65748. throw new Error('No B button on left hand');
  65749. }
  65750. },
  65751. enumerable: true,
  65752. configurable: true
  65753. });
  65754. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  65755. get: function () {
  65756. if (this.hand === 'left') {
  65757. return this.onMainButtonStateChangedObservable;
  65758. }
  65759. else {
  65760. throw new Error('No X button on right hand');
  65761. }
  65762. },
  65763. enumerable: true,
  65764. configurable: true
  65765. });
  65766. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  65767. get: function () {
  65768. if (this.hand === 'left') {
  65769. return this.onSecondaryButtonStateChangedObservable;
  65770. }
  65771. else {
  65772. throw new Error('No Y button on right hand');
  65773. }
  65774. },
  65775. enumerable: true,
  65776. configurable: true
  65777. });
  65778. /*
  65779. 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  65780. 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  65781. 2) secondary trigger (same)
  65782. 3) A (right) X (left), touch, pressed = value
  65783. 4) B / Y
  65784. 5) thumb rest
  65785. */
  65786. OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  65787. var notifyObject = state; //{ state: state, changes: changes };
  65788. var triggerDirection = this.hand === 'right' ? -1 : 1;
  65789. switch (buttonIdx) {
  65790. case 0:
  65791. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  65792. return;
  65793. case 1:// index trigger
  65794. if (this._defaultModel) {
  65795. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  65796. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  65797. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  65798. }
  65799. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  65800. return;
  65801. case 2:// secondary trigger
  65802. if (this._defaultModel) {
  65803. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  65804. }
  65805. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  65806. return;
  65807. case 3:
  65808. if (this._defaultModel) {
  65809. if (notifyObject.pressed) {
  65810. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  65811. }
  65812. else {
  65813. (this._defaultModel.getChildren()[1]).position.y = 0;
  65814. }
  65815. }
  65816. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  65817. return;
  65818. case 4:
  65819. if (this._defaultModel) {
  65820. if (notifyObject.pressed) {
  65821. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  65822. }
  65823. else {
  65824. (this._defaultModel.getChildren()[2]).position.y = 0;
  65825. }
  65826. }
  65827. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  65828. return;
  65829. case 5:
  65830. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  65831. return;
  65832. }
  65833. };
  65834. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  65835. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  65836. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  65837. return OculusTouchController;
  65838. }(BABYLON.WebVRController));
  65839. BABYLON.OculusTouchController = OculusTouchController;
  65840. })(BABYLON || (BABYLON = {}));
  65841. //# sourceMappingURL=babylon.oculusTouchController.js.map
  65842. var BABYLON;
  65843. (function (BABYLON) {
  65844. var ViveController = /** @class */ (function (_super) {
  65845. __extends(ViveController, _super);
  65846. function ViveController(vrGamepad) {
  65847. var _this = _super.call(this, vrGamepad) || this;
  65848. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  65849. _this._invertLeftStickY = true;
  65850. return _this;
  65851. }
  65852. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  65853. var _this = this;
  65854. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  65855. /*
  65856. Parent Mesh name: ViveWand
  65857. - body
  65858. - r_gripper
  65859. - l_gripper
  65860. - menu_button
  65861. - system_button
  65862. - trackpad
  65863. - trigger
  65864. - LED
  65865. */
  65866. _this._defaultModel = newMeshes[1];
  65867. _this.attachToMesh(_this._defaultModel);
  65868. if (meshLoaded) {
  65869. meshLoaded(_this._defaultModel);
  65870. }
  65871. });
  65872. };
  65873. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  65874. get: function () {
  65875. return this.onMainButtonStateChangedObservable;
  65876. },
  65877. enumerable: true,
  65878. configurable: true
  65879. });
  65880. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  65881. get: function () {
  65882. return this.onMainButtonStateChangedObservable;
  65883. },
  65884. enumerable: true,
  65885. configurable: true
  65886. });
  65887. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  65888. get: function () {
  65889. return this.onSecondaryButtonStateChangedObservable;
  65890. },
  65891. enumerable: true,
  65892. configurable: true
  65893. });
  65894. /**
  65895. * Vive mapping:
  65896. * 0: touchpad
  65897. * 1: trigger
  65898. * 2: left AND right buttons
  65899. * 3: menu button
  65900. */
  65901. ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  65902. var notifyObject = state; //{ state: state, changes: changes };
  65903. switch (buttonIdx) {
  65904. case 0:
  65905. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  65906. return;
  65907. case 1:// index trigger
  65908. if (this._defaultModel) {
  65909. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  65910. }
  65911. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  65912. return;
  65913. case 2:// left AND right button
  65914. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  65915. return;
  65916. case 3:
  65917. if (this._defaultModel) {
  65918. if (notifyObject.pressed) {
  65919. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  65920. }
  65921. else {
  65922. (this._defaultModel.getChildren()[2]).position.y = 0;
  65923. }
  65924. }
  65925. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  65926. return;
  65927. }
  65928. };
  65929. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  65930. ViveController.MODEL_FILENAME = 'wand.babylon';
  65931. return ViveController;
  65932. }(BABYLON.WebVRController));
  65933. BABYLON.ViveController = ViveController;
  65934. })(BABYLON || (BABYLON = {}));
  65935. //# sourceMappingURL=babylon.viveController.js.map
  65936. var BABYLON;
  65937. (function (BABYLON) {
  65938. var GenericController = /** @class */ (function (_super) {
  65939. __extends(GenericController, _super);
  65940. function GenericController(vrGamepad) {
  65941. return _super.call(this, vrGamepad) || this;
  65942. }
  65943. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  65944. var _this = this;
  65945. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  65946. _this._defaultModel = newMeshes[1];
  65947. _this.attachToMesh(_this._defaultModel);
  65948. if (meshLoaded) {
  65949. meshLoaded(_this._defaultModel);
  65950. }
  65951. });
  65952. };
  65953. GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  65954. console.log("Button id: " + buttonIdx + "state: ");
  65955. console.dir(state);
  65956. };
  65957. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  65958. GenericController.MODEL_FILENAME = 'generic.babylon';
  65959. return GenericController;
  65960. }(BABYLON.WebVRController));
  65961. BABYLON.GenericController = GenericController;
  65962. })(BABYLON || (BABYLON = {}));
  65963. //# sourceMappingURL=babylon.genericController.js.map
  65964. var BABYLON;
  65965. (function (BABYLON) {
  65966. var LoadedMeshInfo = /** @class */ (function () {
  65967. function LoadedMeshInfo() {
  65968. this.buttonMeshes = {};
  65969. this.axisMeshes = {};
  65970. }
  65971. return LoadedMeshInfo;
  65972. }());
  65973. var WindowsMotionController = /** @class */ (function (_super) {
  65974. __extends(WindowsMotionController, _super);
  65975. function WindowsMotionController(vrGamepad) {
  65976. var _this = _super.call(this, vrGamepad) || this;
  65977. _this._mapping = {
  65978. // Semantic button names
  65979. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  65980. // A mapping of the button name to glTF model node name
  65981. // that should be transformed by button value.
  65982. buttonMeshNames: {
  65983. 'trigger': 'SELECT',
  65984. 'menu': 'MENU',
  65985. 'grip': 'GRASP',
  65986. 'thumbstick': 'THUMBSTICK_PRESS',
  65987. 'trackpad': 'TOUCHPAD_PRESS'
  65988. },
  65989. // This mapping is used to translate from the Motion Controller to Babylon semantics
  65990. buttonObservableNames: {
  65991. 'trigger': 'onTriggerStateChangedObservable',
  65992. 'menu': 'onSecondaryButtonStateChangedObservable',
  65993. 'grip': 'onMainButtonStateChangedObservable',
  65994. 'thumbstick': 'onPadStateChangedObservable',
  65995. 'trackpad': 'onTrackpadChangedObservable'
  65996. },
  65997. // A mapping of the axis name to glTF model node name
  65998. // that should be transformed by axis value.
  65999. // This array mirrors the browserGamepad.axes array, such that
  66000. // the mesh corresponding to axis 0 is in this array index 0.
  66001. axisMeshNames: [
  66002. 'THUMBSTICK_X',
  66003. 'THUMBSTICK_Y',
  66004. 'TOUCHPAD_TOUCH_X',
  66005. 'TOUCHPAD_TOUCH_Y'
  66006. ],
  66007. pointingPoseMeshName: BABYLON.PoseEnabledController.POINTING_POSE
  66008. };
  66009. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  66010. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  66011. _this.trackpad = { x: 0, y: 0 };
  66012. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  66013. _this._loadedMeshInfo = null;
  66014. return _this;
  66015. }
  66016. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  66017. get: function () {
  66018. return this.onTriggerStateChangedObservable;
  66019. },
  66020. enumerable: true,
  66021. configurable: true
  66022. });
  66023. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  66024. get: function () {
  66025. return this.onSecondaryButtonStateChangedObservable;
  66026. },
  66027. enumerable: true,
  66028. configurable: true
  66029. });
  66030. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  66031. get: function () {
  66032. return this.onMainButtonStateChangedObservable;
  66033. },
  66034. enumerable: true,
  66035. configurable: true
  66036. });
  66037. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  66038. get: function () {
  66039. return this.onPadStateChangedObservable;
  66040. },
  66041. enumerable: true,
  66042. configurable: true
  66043. });
  66044. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  66045. get: function () {
  66046. return this.onTrackpadChangedObservable;
  66047. },
  66048. enumerable: true,
  66049. configurable: true
  66050. });
  66051. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  66052. get: function () {
  66053. return this.onTrackpadValuesChangedObservable;
  66054. },
  66055. enumerable: true,
  66056. configurable: true
  66057. });
  66058. /**
  66059. * Called once per frame by the engine.
  66060. */
  66061. WindowsMotionController.prototype.update = function () {
  66062. _super.prototype.update.call(this);
  66063. if (this.browserGamepad.axes) {
  66064. if (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y) {
  66065. this.trackpad.x = this.browserGamepad["axes"][2];
  66066. this.trackpad.y = this.browserGamepad["axes"][3];
  66067. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  66068. }
  66069. // Only need to animate axes if there is a loaded mesh
  66070. if (this._loadedMeshInfo) {
  66071. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  66072. this.lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  66073. }
  66074. }
  66075. }
  66076. };
  66077. /**
  66078. * Called once for each button that changed state since the last frame
  66079. * @param buttonIdx Which button index changed
  66080. * @param state New state of the button
  66081. * @param changes Which properties on the state changed since last frame
  66082. */
  66083. WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  66084. var buttonName = this._mapping.buttons[buttonIdx];
  66085. if (!buttonName) {
  66086. return;
  66087. }
  66088. // Only emit events for buttons that we know how to map from index to name
  66089. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  66090. if (observable) {
  66091. observable.notifyObservers(state);
  66092. }
  66093. this.lerpButtonTransform(buttonName, state.value);
  66094. };
  66095. WindowsMotionController.prototype.lerpButtonTransform = function (buttonName, buttonValue) {
  66096. // If there is no loaded mesh, there is nothing to transform.
  66097. if (!this._loadedMeshInfo) {
  66098. return;
  66099. }
  66100. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  66101. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  66102. return;
  66103. }
  66104. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  66105. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  66106. };
  66107. WindowsMotionController.prototype.lerpAxisTransform = function (axis, axisValue) {
  66108. if (!this._loadedMeshInfo) {
  66109. return;
  66110. }
  66111. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  66112. if (!meshInfo) {
  66113. return;
  66114. }
  66115. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  66116. return;
  66117. }
  66118. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  66119. var lerpValue = axisValue * 0.5 + 0.5;
  66120. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  66121. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  66122. };
  66123. /**
  66124. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  66125. * @param scene scene in which to add meshes
  66126. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  66127. */
  66128. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  66129. var _this = this;
  66130. if (forceDefault === void 0) { forceDefault = false; }
  66131. var path;
  66132. var filename;
  66133. // Checking if GLB loader is present
  66134. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  66135. // Determine the device specific folder based on the ID suffix
  66136. var device = 'default';
  66137. if (this.id && !forceDefault) {
  66138. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  66139. device = ((match && match[0]) || device);
  66140. }
  66141. // Hand
  66142. if (this.hand === 'left') {
  66143. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  66144. }
  66145. else {
  66146. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  66147. }
  66148. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  66149. }
  66150. else {
  66151. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  66152. path = BABYLON.GenericController.MODEL_BASE_URL;
  66153. filename = BABYLON.GenericController.MODEL_FILENAME;
  66154. }
  66155. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  66156. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  66157. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  66158. if (!_this._loadedMeshInfo) {
  66159. return;
  66160. }
  66161. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  66162. _this.attachToMesh(_this._defaultModel);
  66163. if (meshLoaded) {
  66164. meshLoaded(_this._defaultModel);
  66165. }
  66166. }, null, function (scene, message) {
  66167. BABYLON.Tools.Log(message);
  66168. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  66169. if (!forceDefault) {
  66170. _this.initControllerMesh(scene, meshLoaded, true);
  66171. }
  66172. });
  66173. };
  66174. /**
  66175. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  66176. * can be transformed by button presses and axes values, based on this._mapping.
  66177. *
  66178. * @param scene scene in which the meshes exist
  66179. * @param meshes list of meshes that make up the controller model to process
  66180. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  66181. */
  66182. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  66183. var loadedMeshInfo = null;
  66184. // Create a new mesh to contain the glTF hierarchy
  66185. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  66186. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  66187. var childMesh = null;
  66188. for (var i = 0; i < meshes.length; i++) {
  66189. var mesh = meshes[i];
  66190. if (!mesh.parent) {
  66191. // Exclude controller meshes from picking results
  66192. mesh.isPickable = false;
  66193. // Handle root node, attach to the new parentMesh
  66194. childMesh = mesh;
  66195. break;
  66196. }
  66197. }
  66198. if (childMesh) {
  66199. childMesh.setParent(parentMesh);
  66200. // Create our mesh info. Note that this method will always return non-null.
  66201. loadedMeshInfo = this.createMeshInfo(parentMesh);
  66202. }
  66203. else {
  66204. BABYLON.Tools.Warn('Could not find root node in model file.');
  66205. }
  66206. return loadedMeshInfo;
  66207. };
  66208. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  66209. var loadedMeshInfo = new LoadedMeshInfo();
  66210. var i;
  66211. loadedMeshInfo.rootNode = rootNode;
  66212. // Reset the caches
  66213. loadedMeshInfo.buttonMeshes = {};
  66214. loadedMeshInfo.axisMeshes = {};
  66215. // Button Meshes
  66216. for (i = 0; i < this._mapping.buttons.length; i++) {
  66217. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  66218. if (!buttonMeshName) {
  66219. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  66220. continue;
  66221. }
  66222. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  66223. if (!buttonMesh) {
  66224. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  66225. continue;
  66226. }
  66227. var buttonMeshInfo = {
  66228. index: i,
  66229. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  66230. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  66231. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  66232. };
  66233. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  66234. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  66235. }
  66236. else {
  66237. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  66238. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  66239. '(VALUE: ' + !!buttonMeshInfo.value +
  66240. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  66241. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  66242. ')');
  66243. }
  66244. }
  66245. // Axis Meshes
  66246. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  66247. var axisMeshName = this._mapping.axisMeshNames[i];
  66248. if (!axisMeshName) {
  66249. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  66250. continue;
  66251. }
  66252. var axisMesh = getChildByName(rootNode, axisMeshName);
  66253. if (!axisMesh) {
  66254. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  66255. continue;
  66256. }
  66257. var axisMeshInfo = {
  66258. index: i,
  66259. value: getImmediateChildByName(axisMesh, 'VALUE'),
  66260. min: getImmediateChildByName(axisMesh, 'MIN'),
  66261. max: getImmediateChildByName(axisMesh, 'MAX')
  66262. };
  66263. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  66264. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  66265. }
  66266. else {
  66267. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  66268. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  66269. '(VALUE: ' + !!axisMeshInfo.value +
  66270. ', MIN: ' + !!axisMeshInfo.min +
  66271. ', MAX:' + !!axisMeshInfo.max +
  66272. ')');
  66273. }
  66274. }
  66275. // Pointing Ray
  66276. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  66277. if (!loadedMeshInfo.pointingPoseNode) {
  66278. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  66279. }
  66280. return loadedMeshInfo;
  66281. // Look through all children recursively. This will return null if no mesh exists with the given name.
  66282. function getChildByName(node, name) {
  66283. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  66284. }
  66285. // Look through only immediate children. This will return null if no mesh exists with the given name.
  66286. function getImmediateChildByName(node, name) {
  66287. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  66288. }
  66289. };
  66290. WindowsMotionController.prototype.getForwardRay = function (length) {
  66291. if (length === void 0) { length = 100; }
  66292. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  66293. return _super.prototype.getForwardRay.call(this, length);
  66294. }
  66295. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  66296. var origin = m.getTranslation();
  66297. var forward = new BABYLON.Vector3(0, 0, -1);
  66298. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  66299. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  66300. return new BABYLON.Ray(origin, direction, length);
  66301. };
  66302. WindowsMotionController.prototype.dispose = function () {
  66303. _super.prototype.dispose.call(this);
  66304. this.onTrackpadChangedObservable.clear();
  66305. };
  66306. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  66307. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  66308. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  66309. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  66310. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  66311. return WindowsMotionController;
  66312. }(BABYLON.WebVRController));
  66313. BABYLON.WindowsMotionController = WindowsMotionController;
  66314. })(BABYLON || (BABYLON = {}));
  66315. //# sourceMappingURL=babylon.windowsMotionController.js.map
  66316. var BABYLON;
  66317. (function (BABYLON) {
  66318. var GearVRController = /** @class */ (function (_super) {
  66319. __extends(GearVRController, _super);
  66320. function GearVRController(vrGamepad) {
  66321. var _this = _super.call(this, vrGamepad) || this;
  66322. _this._buttonIndexToObservableNameMap = [
  66323. 'onTrackpadChangedObservable',
  66324. 'onTriggerStateChangedObservable' // Trigger
  66325. ];
  66326. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  66327. return _this;
  66328. }
  66329. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  66330. var _this = this;
  66331. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  66332. _this._defaultModel = newMeshes[1];
  66333. _this.attachToMesh(_this._defaultModel);
  66334. if (meshLoaded) {
  66335. meshLoaded(_this._defaultModel);
  66336. }
  66337. });
  66338. };
  66339. GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  66340. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  66341. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  66342. // Only emit events for buttons that we know how to map from index to observable
  66343. var observable = this[observableName];
  66344. if (observable) {
  66345. observable.notifyObservers(state);
  66346. }
  66347. }
  66348. };
  66349. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  66350. GearVRController.MODEL_FILENAME = 'generic.babylon';
  66351. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  66352. return GearVRController;
  66353. }(BABYLON.WebVRController));
  66354. BABYLON.GearVRController = GearVRController;
  66355. })(BABYLON || (BABYLON = {}));
  66356. //# sourceMappingURL=babylon.gearVRController.js.map
  66357. var BABYLON;
  66358. (function (BABYLON) {
  66359. /**
  66360. * Google Daydream controller
  66361. */
  66362. var DaydreamController = /** @class */ (function (_super) {
  66363. __extends(DaydreamController, _super);
  66364. function DaydreamController(vrGamepad) {
  66365. var _this = _super.call(this, vrGamepad) || this;
  66366. _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;
  66367. return _this;
  66368. }
  66369. DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {
  66370. var _this = this;
  66371. BABYLON.SceneLoader.ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {
  66372. _this._defaultModel = newMeshes[1];
  66373. _this.attachToMesh(_this._defaultModel);
  66374. if (meshLoaded) {
  66375. meshLoaded(_this._defaultModel);
  66376. }
  66377. });
  66378. };
  66379. DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  66380. // Daydream controller only has 1 GamepadButton (on the trackpad).
  66381. if (buttonIdx === 0) {
  66382. var observable = this.onTriggerStateChangedObservable;
  66383. if (observable) {
  66384. observable.notifyObservers(state);
  66385. }
  66386. }
  66387. else {
  66388. // If the app or home buttons are ever made available
  66389. BABYLON.Tools.Warn("Unrecognized Daydream button index: " + buttonIdx);
  66390. }
  66391. };
  66392. /**
  66393. * Base Url for the controller model.
  66394. */
  66395. DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  66396. /**
  66397. * File name for the controller model.
  66398. */
  66399. DaydreamController.MODEL_FILENAME = 'generic.babylon';
  66400. /**
  66401. * Gamepad Id prefix used to identify Daydream Controller.
  66402. */
  66403. DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'
  66404. return DaydreamController;
  66405. }(BABYLON.WebVRController));
  66406. BABYLON.DaydreamController = DaydreamController;
  66407. })(BABYLON || (BABYLON = {}));
  66408. //# sourceMappingURL=babylon.daydreamController.js.map
  66409. var BABYLON;
  66410. (function (BABYLON) {
  66411. var FollowCamera = /** @class */ (function (_super) {
  66412. __extends(FollowCamera, _super);
  66413. function FollowCamera(name, position, scene, lockedTarget) {
  66414. if (lockedTarget === void 0) { lockedTarget = null; }
  66415. var _this = _super.call(this, name, position, scene) || this;
  66416. _this.radius = 12;
  66417. _this.rotationOffset = 0;
  66418. _this.heightOffset = 4;
  66419. _this.cameraAcceleration = 0.05;
  66420. _this.maxCameraSpeed = 20;
  66421. _this.lockedTarget = lockedTarget;
  66422. return _this;
  66423. }
  66424. FollowCamera.prototype.getRadians = function (degrees) {
  66425. return degrees * Math.PI / 180;
  66426. };
  66427. FollowCamera.prototype.follow = function (cameraTarget) {
  66428. if (!cameraTarget)
  66429. return;
  66430. var yRotation;
  66431. if (cameraTarget.rotationQuaternion) {
  66432. var rotMatrix = new BABYLON.Matrix();
  66433. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  66434. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  66435. }
  66436. else {
  66437. yRotation = cameraTarget.rotation.y;
  66438. }
  66439. var radians = this.getRadians(this.rotationOffset) + yRotation;
  66440. var targetPosition = cameraTarget.getAbsolutePosition();
  66441. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  66442. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  66443. var dx = targetX - this.position.x;
  66444. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  66445. var dz = (targetZ) - this.position.z;
  66446. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  66447. var vy = dy * this.cameraAcceleration;
  66448. var vz = dz * this.cameraAcceleration * 2;
  66449. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  66450. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  66451. }
  66452. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  66453. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  66454. }
  66455. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  66456. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  66457. }
  66458. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  66459. this.setTarget(targetPosition);
  66460. };
  66461. FollowCamera.prototype._checkInputs = function () {
  66462. _super.prototype._checkInputs.call(this);
  66463. if (this.lockedTarget) {
  66464. this.follow(this.lockedTarget);
  66465. }
  66466. };
  66467. FollowCamera.prototype.getClassName = function () {
  66468. return "FollowCamera";
  66469. };
  66470. __decorate([
  66471. BABYLON.serialize()
  66472. ], FollowCamera.prototype, "radius", void 0);
  66473. __decorate([
  66474. BABYLON.serialize()
  66475. ], FollowCamera.prototype, "rotationOffset", void 0);
  66476. __decorate([
  66477. BABYLON.serialize()
  66478. ], FollowCamera.prototype, "heightOffset", void 0);
  66479. __decorate([
  66480. BABYLON.serialize()
  66481. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  66482. __decorate([
  66483. BABYLON.serialize()
  66484. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  66485. __decorate([
  66486. BABYLON.serializeAsMeshReference("lockedTargetId")
  66487. ], FollowCamera.prototype, "lockedTarget", void 0);
  66488. return FollowCamera;
  66489. }(BABYLON.TargetCamera));
  66490. BABYLON.FollowCamera = FollowCamera;
  66491. var ArcFollowCamera = /** @class */ (function (_super) {
  66492. __extends(ArcFollowCamera, _super);
  66493. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  66494. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  66495. _this.alpha = alpha;
  66496. _this.beta = beta;
  66497. _this.radius = radius;
  66498. _this.target = target;
  66499. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  66500. _this.follow();
  66501. return _this;
  66502. }
  66503. ArcFollowCamera.prototype.follow = function () {
  66504. if (!this.target) {
  66505. return;
  66506. }
  66507. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  66508. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  66509. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  66510. var targetPosition = this.target.getAbsolutePosition();
  66511. this.position = targetPosition.add(this._cartesianCoordinates);
  66512. this.setTarget(targetPosition);
  66513. };
  66514. ArcFollowCamera.prototype._checkInputs = function () {
  66515. _super.prototype._checkInputs.call(this);
  66516. this.follow();
  66517. };
  66518. ArcFollowCamera.prototype.getClassName = function () {
  66519. return "ArcFollowCamera";
  66520. };
  66521. return ArcFollowCamera;
  66522. }(BABYLON.TargetCamera));
  66523. BABYLON.ArcFollowCamera = ArcFollowCamera;
  66524. })(BABYLON || (BABYLON = {}));
  66525. //# sourceMappingURL=babylon.followCamera.js.map
  66526. var BABYLON;
  66527. (function (BABYLON) {
  66528. // We're mainly based on the logic defined into the FreeCamera code
  66529. var UniversalCamera = /** @class */ (function (_super) {
  66530. __extends(UniversalCamera, _super);
  66531. //-- end properties for backward compatibility for inputs
  66532. function UniversalCamera(name, position, scene) {
  66533. var _this = _super.call(this, name, position, scene) || this;
  66534. _this.inputs.addGamepad();
  66535. return _this;
  66536. }
  66537. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  66538. //-- Begin properties for backward compatibility for inputs
  66539. get: function () {
  66540. var gamepad = this.inputs.attached["gamepad"];
  66541. if (gamepad)
  66542. return gamepad.gamepadAngularSensibility;
  66543. return 0;
  66544. },
  66545. set: function (value) {
  66546. var gamepad = this.inputs.attached["gamepad"];
  66547. if (gamepad)
  66548. gamepad.gamepadAngularSensibility = value;
  66549. },
  66550. enumerable: true,
  66551. configurable: true
  66552. });
  66553. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  66554. get: function () {
  66555. var gamepad = this.inputs.attached["gamepad"];
  66556. if (gamepad)
  66557. return gamepad.gamepadMoveSensibility;
  66558. return 0;
  66559. },
  66560. set: function (value) {
  66561. var gamepad = this.inputs.attached["gamepad"];
  66562. if (gamepad)
  66563. gamepad.gamepadMoveSensibility = value;
  66564. },
  66565. enumerable: true,
  66566. configurable: true
  66567. });
  66568. UniversalCamera.prototype.getClassName = function () {
  66569. return "UniversalCamera";
  66570. };
  66571. return UniversalCamera;
  66572. }(BABYLON.TouchCamera));
  66573. BABYLON.UniversalCamera = UniversalCamera;
  66574. })(BABYLON || (BABYLON = {}));
  66575. //# sourceMappingURL=babylon.universalCamera.js.map
  66576. var BABYLON;
  66577. (function (BABYLON) {
  66578. // We're mainly based on the logic defined into the FreeCamera code
  66579. var GamepadCamera = /** @class */ (function (_super) {
  66580. __extends(GamepadCamera, _super);
  66581. //-- end properties for backward compatibility for inputs
  66582. function GamepadCamera(name, position, scene) {
  66583. return _super.call(this, name, position, scene) || this;
  66584. }
  66585. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  66586. //-- Begin properties for backward compatibility for inputs
  66587. get: function () {
  66588. var gamepad = this.inputs.attached["gamepad"];
  66589. if (gamepad)
  66590. return gamepad.gamepadAngularSensibility;
  66591. return 0;
  66592. },
  66593. set: function (value) {
  66594. var gamepad = this.inputs.attached["gamepad"];
  66595. if (gamepad)
  66596. gamepad.gamepadAngularSensibility = value;
  66597. },
  66598. enumerable: true,
  66599. configurable: true
  66600. });
  66601. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  66602. get: function () {
  66603. var gamepad = this.inputs.attached["gamepad"];
  66604. if (gamepad)
  66605. return gamepad.gamepadMoveSensibility;
  66606. return 0;
  66607. },
  66608. set: function (value) {
  66609. var gamepad = this.inputs.attached["gamepad"];
  66610. if (gamepad)
  66611. gamepad.gamepadMoveSensibility = value;
  66612. },
  66613. enumerable: true,
  66614. configurable: true
  66615. });
  66616. GamepadCamera.prototype.getClassName = function () {
  66617. return "GamepadCamera";
  66618. };
  66619. return GamepadCamera;
  66620. }(BABYLON.UniversalCamera));
  66621. BABYLON.GamepadCamera = GamepadCamera;
  66622. })(BABYLON || (BABYLON = {}));
  66623. //# sourceMappingURL=babylon.gamepadCamera.js.map
  66624. var BABYLON;
  66625. (function (BABYLON) {
  66626. var PostProcessRenderPipelineManager = /** @class */ (function () {
  66627. function PostProcessRenderPipelineManager() {
  66628. this._renderPipelines = {};
  66629. }
  66630. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  66631. this._renderPipelines[renderPipeline._name] = renderPipeline;
  66632. };
  66633. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  66634. if (unique === void 0) { unique = false; }
  66635. var renderPipeline = this._renderPipelines[renderPipelineName];
  66636. if (!renderPipeline) {
  66637. return;
  66638. }
  66639. renderPipeline._attachCameras(cameras, unique);
  66640. };
  66641. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  66642. var renderPipeline = this._renderPipelines[renderPipelineName];
  66643. if (!renderPipeline) {
  66644. return;
  66645. }
  66646. renderPipeline._detachCameras(cameras);
  66647. };
  66648. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  66649. var renderPipeline = this._renderPipelines[renderPipelineName];
  66650. if (!renderPipeline) {
  66651. return;
  66652. }
  66653. renderPipeline._enableEffect(renderEffectName, cameras);
  66654. };
  66655. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  66656. var renderPipeline = this._renderPipelines[renderPipelineName];
  66657. if (!renderPipeline) {
  66658. return;
  66659. }
  66660. renderPipeline._disableEffect(renderEffectName, cameras);
  66661. };
  66662. PostProcessRenderPipelineManager.prototype.update = function () {
  66663. for (var renderPipelineName in this._renderPipelines) {
  66664. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  66665. var pipeline = this._renderPipelines[renderPipelineName];
  66666. if (!pipeline.isSupported) {
  66667. pipeline.dispose();
  66668. delete this._renderPipelines[renderPipelineName];
  66669. }
  66670. else {
  66671. pipeline._update();
  66672. }
  66673. }
  66674. }
  66675. };
  66676. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  66677. for (var renderPipelineName in this._renderPipelines) {
  66678. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  66679. var pipeline = this._renderPipelines[renderPipelineName];
  66680. pipeline._rebuild();
  66681. }
  66682. }
  66683. };
  66684. PostProcessRenderPipelineManager.prototype.dispose = function () {
  66685. for (var renderPipelineName in this._renderPipelines) {
  66686. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  66687. var pipeline = this._renderPipelines[renderPipelineName];
  66688. pipeline.dispose();
  66689. }
  66690. }
  66691. };
  66692. return PostProcessRenderPipelineManager;
  66693. }());
  66694. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  66695. })(BABYLON || (BABYLON = {}));
  66696. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  66697. var BABYLON;
  66698. (function (BABYLON) {
  66699. /**
  66700. * This represents a set of one or more post processes in Babylon.
  66701. * A post process can be used to apply a shader to a texture after it is rendered.
  66702. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  66703. */
  66704. var PostProcessRenderEffect = /** @class */ (function () {
  66705. /**
  66706. * Instantiates a post process render effect.
  66707. * A post process can be used to apply a shader to a texture after it is rendered.
  66708. * @param engine The engine the effect is tied to
  66709. * @param name The name of the effect
  66710. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  66711. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  66712. */
  66713. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  66714. this._name = name;
  66715. this._singleInstance = singleInstance || true;
  66716. this._getPostProcesses = getPostProcesses;
  66717. this._cameras = {};
  66718. this._indicesForCamera = {};
  66719. this._postProcesses = {};
  66720. }
  66721. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  66722. /**
  66723. * Checks if all the post processes in the effect are supported.
  66724. */
  66725. get: function () {
  66726. for (var index in this._postProcesses) {
  66727. for (var ppIndex in this._postProcesses[index]) {
  66728. if (!this._postProcesses[index][ppIndex].isSupported) {
  66729. return false;
  66730. }
  66731. }
  66732. }
  66733. return true;
  66734. },
  66735. enumerable: true,
  66736. configurable: true
  66737. });
  66738. /**
  66739. * Updates the current state of the effect
  66740. */
  66741. PostProcessRenderEffect.prototype._update = function () {
  66742. };
  66743. /**
  66744. * Attaches the effect on cameras
  66745. * @param cameras The camera to attach to.
  66746. */
  66747. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  66748. var _this = this;
  66749. var cameraKey;
  66750. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  66751. if (!cams) {
  66752. return;
  66753. }
  66754. for (var i = 0; i < cams.length; i++) {
  66755. var camera = cams[i];
  66756. var cameraName = camera.name;
  66757. if (this._singleInstance) {
  66758. cameraKey = 0;
  66759. }
  66760. else {
  66761. cameraKey = cameraName;
  66762. }
  66763. if (!this._postProcesses[cameraKey]) {
  66764. var postProcess = this._getPostProcesses();
  66765. if (postProcess) {
  66766. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  66767. }
  66768. }
  66769. if (!this._indicesForCamera[cameraName]) {
  66770. this._indicesForCamera[cameraName] = [];
  66771. }
  66772. this._postProcesses[cameraKey].forEach(function (postProcess) {
  66773. var index = camera.attachPostProcess(postProcess);
  66774. _this._indicesForCamera[cameraName].push(index);
  66775. });
  66776. if (!this._cameras[cameraName]) {
  66777. this._cameras[cameraName] = camera;
  66778. }
  66779. }
  66780. };
  66781. /**
  66782. * Detatches the effect on cameras
  66783. * @param cameras The camera to detatch from.
  66784. */
  66785. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  66786. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  66787. if (!cams) {
  66788. return;
  66789. }
  66790. for (var i = 0; i < cams.length; i++) {
  66791. var camera = cams[i];
  66792. var cameraName = camera.name;
  66793. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  66794. camera.detachPostProcess(postProcess);
  66795. });
  66796. if (this._cameras[cameraName]) {
  66797. //this._indicesForCamera.splice(index, 1);
  66798. this._cameras[cameraName] = null;
  66799. }
  66800. }
  66801. };
  66802. /**
  66803. * Enables the effect on given cameras
  66804. * @param cameras The camera to enable.
  66805. */
  66806. PostProcessRenderEffect.prototype._enable = function (cameras) {
  66807. var _this = this;
  66808. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  66809. if (!cams) {
  66810. return;
  66811. }
  66812. for (var i = 0; i < cams.length; i++) {
  66813. var camera = cams[i];
  66814. var cameraName = camera.name;
  66815. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  66816. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined || camera._postProcesses[this._indicesForCamera[cameraName][j]] === null) {
  66817. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  66818. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  66819. });
  66820. }
  66821. }
  66822. }
  66823. };
  66824. /**
  66825. * Disables the effect on the given cameras
  66826. * @param cameras The camera to disable.
  66827. */
  66828. PostProcessRenderEffect.prototype._disable = function (cameras) {
  66829. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  66830. if (!cams) {
  66831. return;
  66832. }
  66833. for (var i = 0; i < cams.length; i++) {
  66834. var camera = cams[i];
  66835. var cameraName = camera.name;
  66836. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  66837. camera.detachPostProcess(postProcess);
  66838. });
  66839. }
  66840. };
  66841. /**
  66842. * Gets a list of the post processes contained in the effect.
  66843. * @param camera The camera to get the post processes on.
  66844. * @returns The list of the post processes in the effect.
  66845. */
  66846. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  66847. if (this._singleInstance) {
  66848. return this._postProcesses[0];
  66849. }
  66850. else {
  66851. if (!camera) {
  66852. return null;
  66853. }
  66854. return this._postProcesses[camera.name];
  66855. }
  66856. };
  66857. return PostProcessRenderEffect;
  66858. }());
  66859. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  66860. })(BABYLON || (BABYLON = {}));
  66861. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  66862. var BABYLON;
  66863. (function (BABYLON) {
  66864. var PostProcessRenderPipeline = /** @class */ (function () {
  66865. function PostProcessRenderPipeline(engine, name) {
  66866. this.engine = engine;
  66867. this._name = name;
  66868. this._renderEffects = {};
  66869. this._renderEffectsForIsolatedPass = new Array();
  66870. this._cameras = [];
  66871. }
  66872. PostProcessRenderPipeline.prototype.getClassName = function () {
  66873. return "PostProcessRenderPipeline";
  66874. };
  66875. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  66876. get: function () {
  66877. for (var renderEffectName in this._renderEffects) {
  66878. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  66879. if (!this._renderEffects[renderEffectName].isSupported) {
  66880. return false;
  66881. }
  66882. }
  66883. }
  66884. return true;
  66885. },
  66886. enumerable: true,
  66887. configurable: true
  66888. });
  66889. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  66890. this._renderEffects[renderEffect._name] = renderEffect;
  66891. };
  66892. // private
  66893. PostProcessRenderPipeline.prototype._rebuild = function () {
  66894. };
  66895. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  66896. var renderEffects = this._renderEffects[renderEffectName];
  66897. if (!renderEffects) {
  66898. return;
  66899. }
  66900. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  66901. };
  66902. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  66903. var renderEffects = this._renderEffects[renderEffectName];
  66904. if (!renderEffects) {
  66905. return;
  66906. }
  66907. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  66908. };
  66909. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  66910. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  66911. if (!cams) {
  66912. return;
  66913. }
  66914. var indicesToDelete = [];
  66915. var i;
  66916. for (i = 0; i < cams.length; i++) {
  66917. var camera = cams[i];
  66918. var cameraName = camera.name;
  66919. if (this._cameras.indexOf(camera) === -1) {
  66920. this._cameras[cameraName] = camera;
  66921. }
  66922. else if (unique) {
  66923. indicesToDelete.push(i);
  66924. }
  66925. }
  66926. for (i = 0; i < indicesToDelete.length; i++) {
  66927. cameras.splice(indicesToDelete[i], 1);
  66928. }
  66929. for (var renderEffectName in this._renderEffects) {
  66930. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  66931. this._renderEffects[renderEffectName]._attachCameras(cams);
  66932. }
  66933. }
  66934. };
  66935. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  66936. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  66937. if (!cams) {
  66938. return;
  66939. }
  66940. for (var renderEffectName in this._renderEffects) {
  66941. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  66942. this._renderEffects[renderEffectName]._detachCameras(cams);
  66943. }
  66944. }
  66945. for (var i = 0; i < cams.length; i++) {
  66946. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  66947. }
  66948. };
  66949. PostProcessRenderPipeline.prototype._update = function () {
  66950. for (var renderEffectName in this._renderEffects) {
  66951. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  66952. this._renderEffects[renderEffectName]._update();
  66953. }
  66954. }
  66955. for (var i = 0; i < this._cameras.length; i++) {
  66956. var cameraName = this._cameras[i].name;
  66957. if (this._renderEffectsForIsolatedPass[cameraName]) {
  66958. this._renderEffectsForIsolatedPass[cameraName]._update();
  66959. }
  66960. }
  66961. };
  66962. PostProcessRenderPipeline.prototype._reset = function () {
  66963. this._renderEffects = {};
  66964. this._renderEffectsForIsolatedPass = new Array();
  66965. };
  66966. PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function () {
  66967. // Set samples of the very first post process to 4 to enable native anti-aliasing in browsers that support webGL 2.0 (See: https://github.com/BabylonJS/Babylon.js/issues/3754)
  66968. var effectKeys = Object.keys(this._renderEffects);
  66969. if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
  66970. var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
  66971. if (postProcesses) {
  66972. postProcesses[0].samples = 4;
  66973. return true;
  66974. }
  66975. }
  66976. return false;
  66977. };
  66978. PostProcessRenderPipeline.prototype.dispose = function () {
  66979. // Must be implemented by children
  66980. };
  66981. __decorate([
  66982. BABYLON.serialize()
  66983. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  66984. return PostProcessRenderPipeline;
  66985. }());
  66986. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  66987. })(BABYLON || (BABYLON = {}));
  66988. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  66989. var BABYLON;
  66990. (function (BABYLON) {
  66991. /**
  66992. * This represents a depth renderer in Babylon.
  66993. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  66994. */
  66995. var DepthRenderer = /** @class */ (function () {
  66996. /**
  66997. * Instantiates a depth renderer
  66998. * @param scene The scene the renderer belongs to
  66999. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  67000. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  67001. */
  67002. function DepthRenderer(scene, type, camera) {
  67003. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  67004. if (camera === void 0) { camera = null; }
  67005. var _this = this;
  67006. this._scene = scene;
  67007. this._camera = camera;
  67008. var engine = scene.getEngine();
  67009. // Render target
  67010. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  67011. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67012. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67013. this._depthMap.refreshRate = 1;
  67014. this._depthMap.renderParticles = false;
  67015. this._depthMap.renderList = null;
  67016. // Camera to get depth map from to support multiple concurrent cameras
  67017. this._depthMap.activeCamera = this._camera;
  67018. this._depthMap.ignoreCameraViewport = true;
  67019. this._depthMap.useCameraPostProcesses = false;
  67020. // set default depth value to 1.0 (far away)
  67021. this._depthMap.onClearObservable.add(function (engine) {
  67022. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  67023. });
  67024. // Custom render function
  67025. var renderSubMesh = function (subMesh) {
  67026. var mesh = subMesh.getRenderingMesh();
  67027. var scene = _this._scene;
  67028. var engine = scene.getEngine();
  67029. var material = subMesh.getMaterial();
  67030. if (!material) {
  67031. return;
  67032. }
  67033. // Culling and reverse (right handed system)
  67034. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  67035. // Managing instances
  67036. var batch = mesh._getInstancesRenderList(subMesh._id);
  67037. if (batch.mustReturn) {
  67038. return;
  67039. }
  67040. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  67041. var camera = _this._camera || scene.activeCamera;
  67042. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  67043. engine.enableEffect(_this._effect);
  67044. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  67045. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  67046. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  67047. // Alpha test
  67048. if (material && material.needAlphaTesting()) {
  67049. var alphaTexture = material.getAlphaTestTexture();
  67050. if (alphaTexture) {
  67051. _this._effect.setTexture("diffuseSampler", alphaTexture);
  67052. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  67053. }
  67054. }
  67055. // Bones
  67056. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  67057. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  67058. }
  67059. // Draw
  67060. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  67061. }
  67062. };
  67063. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  67064. var index;
  67065. if (depthOnlySubMeshes.length) {
  67066. engine.setColorWrite(false);
  67067. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  67068. renderSubMesh(depthOnlySubMeshes.data[index]);
  67069. }
  67070. engine.setColorWrite(true);
  67071. }
  67072. for (index = 0; index < opaqueSubMeshes.length; index++) {
  67073. renderSubMesh(opaqueSubMeshes.data[index]);
  67074. }
  67075. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  67076. renderSubMesh(alphaTestSubMeshes.data[index]);
  67077. }
  67078. };
  67079. }
  67080. /**
  67081. * Creates the depth rendering effect and checks if the effect is ready.
  67082. * @param subMesh The submesh to be used to render the depth map of
  67083. * @param useInstances If multiple world instances should be used
  67084. * @returns if the depth renderer is ready to render the depth map
  67085. */
  67086. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  67087. var material = subMesh.getMaterial();
  67088. if (material.disableDepthWrite) {
  67089. return false;
  67090. }
  67091. var defines = [];
  67092. var attribs = [BABYLON.VertexBuffer.PositionKind];
  67093. var mesh = subMesh.getMesh();
  67094. // Alpha test
  67095. if (material && material.needAlphaTesting() && material.getAlphaTestTexture()) {
  67096. defines.push("#define ALPHATEST");
  67097. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  67098. attribs.push(BABYLON.VertexBuffer.UVKind);
  67099. defines.push("#define UV1");
  67100. }
  67101. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  67102. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  67103. defines.push("#define UV2");
  67104. }
  67105. }
  67106. // Bones
  67107. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  67108. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  67109. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  67110. if (mesh.numBoneInfluencers > 4) {
  67111. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  67112. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  67113. }
  67114. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  67115. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  67116. }
  67117. else {
  67118. defines.push("#define NUM_BONE_INFLUENCERS 0");
  67119. }
  67120. // Instances
  67121. if (useInstances) {
  67122. defines.push("#define INSTANCES");
  67123. attribs.push("world0");
  67124. attribs.push("world1");
  67125. attribs.push("world2");
  67126. attribs.push("world3");
  67127. }
  67128. // Get correct effect
  67129. var join = defines.join("\n");
  67130. if (this._cachedDefines !== join) {
  67131. this._cachedDefines = join;
  67132. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  67133. }
  67134. return this._effect.isReady();
  67135. };
  67136. /**
  67137. * Gets the texture which the depth map will be written to.
  67138. * @returns The depth map texture
  67139. */
  67140. DepthRenderer.prototype.getDepthMap = function () {
  67141. return this._depthMap;
  67142. };
  67143. /**
  67144. * Disposes of the depth renderer.
  67145. */
  67146. DepthRenderer.prototype.dispose = function () {
  67147. this._depthMap.dispose();
  67148. };
  67149. return DepthRenderer;
  67150. }());
  67151. BABYLON.DepthRenderer = DepthRenderer;
  67152. })(BABYLON || (BABYLON = {}));
  67153. //# sourceMappingURL=babylon.depthRenderer.js.map
  67154. var BABYLON;
  67155. (function (BABYLON) {
  67156. var SSAORenderingPipeline = /** @class */ (function (_super) {
  67157. __extends(SSAORenderingPipeline, _super);
  67158. /**
  67159. * @constructor
  67160. * @param {string} name - The rendering pipeline name
  67161. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  67162. * @param {any} ratio - The size of the postprocesses. Can be a number shared between passes or an object for more precision: { ssaoRatio: 0.5, combineRatio: 1.0 }
  67163. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  67164. */
  67165. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  67166. var _this = _super.call(this, scene.getEngine(), name) || this;
  67167. // Members
  67168. /**
  67169. * The PassPostProcess id in the pipeline that contains the original scene color
  67170. * @type {string}
  67171. */
  67172. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  67173. /**
  67174. * The SSAO PostProcess id in the pipeline
  67175. * @type {string}
  67176. */
  67177. _this.SSAORenderEffect = "SSAORenderEffect";
  67178. /**
  67179. * The horizontal blur PostProcess id in the pipeline
  67180. * @type {string}
  67181. */
  67182. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  67183. /**
  67184. * The vertical blur PostProcess id in the pipeline
  67185. * @type {string}
  67186. */
  67187. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  67188. /**
  67189. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  67190. * @type {string}
  67191. */
  67192. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  67193. /**
  67194. * The output strength of the SSAO post-process. Default value is 1.0.
  67195. * @type {number}
  67196. */
  67197. _this.totalStrength = 1.0;
  67198. /**
  67199. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  67200. * @type {number}
  67201. */
  67202. _this.radius = 0.0001;
  67203. /**
  67204. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  67205. * Must not be equal to fallOff and superior to fallOff.
  67206. * Default value is 0.975
  67207. * @type {number}
  67208. */
  67209. _this.area = 0.0075;
  67210. /**
  67211. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  67212. * Must not be equal to area and inferior to area.
  67213. * Default value is 0.0
  67214. * @type {number}
  67215. */
  67216. _this.fallOff = 0.000001;
  67217. /**
  67218. * The base color of the SSAO post-process
  67219. * The final result is "base + ssao" between [0, 1]
  67220. * @type {number}
  67221. */
  67222. _this.base = 0.5;
  67223. _this._firstUpdate = true;
  67224. _this._scene = scene;
  67225. // Set up assets
  67226. _this._createRandomTexture();
  67227. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  67228. var ssaoRatio = ratio.ssaoRatio || ratio;
  67229. var combineRatio = ratio.combineRatio || ratio;
  67230. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  67231. _this._createSSAOPostProcess(ssaoRatio);
  67232. _this._createBlurPostProcess(ssaoRatio);
  67233. _this._createSSAOCombinePostProcess(combineRatio);
  67234. // Set up pipeline
  67235. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  67236. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  67237. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  67238. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  67239. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  67240. // Finish
  67241. scene.postProcessRenderPipelineManager.addPipeline(_this);
  67242. if (cameras)
  67243. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  67244. return _this;
  67245. }
  67246. // Public Methods
  67247. /**
  67248. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  67249. */
  67250. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  67251. if (disableDepthRender === void 0) { disableDepthRender = false; }
  67252. for (var i = 0; i < this._scene.cameras.length; i++) {
  67253. var camera = this._scene.cameras[i];
  67254. this._originalColorPostProcess.dispose(camera);
  67255. this._ssaoPostProcess.dispose(camera);
  67256. this._blurHPostProcess.dispose(camera);
  67257. this._blurVPostProcess.dispose(camera);
  67258. this._ssaoCombinePostProcess.dispose(camera);
  67259. }
  67260. this._randomTexture.dispose();
  67261. if (disableDepthRender)
  67262. this._scene.disableDepthRenderer();
  67263. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  67264. _super.prototype.dispose.call(this);
  67265. };
  67266. // Private Methods
  67267. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  67268. var _this = this;
  67269. var size = 16;
  67270. this._blurHPostProcess = new BABYLON.BlurPostProcess("BlurH", new BABYLON.Vector2(1, 0), size, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  67271. this._blurVPostProcess = new BABYLON.BlurPostProcess("BlurV", new BABYLON.Vector2(0, 1), size, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  67272. this._blurHPostProcess.onActivateObservable.add(function () {
  67273. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  67274. _this._blurHPostProcess.kernel = size * dw;
  67275. });
  67276. this._blurVPostProcess.onActivateObservable.add(function () {
  67277. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  67278. _this._blurVPostProcess.kernel = size * dw;
  67279. });
  67280. };
  67281. SSAORenderingPipeline.prototype._rebuild = function () {
  67282. this._firstUpdate = true;
  67283. _super.prototype._rebuild.call(this);
  67284. };
  67285. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  67286. var _this = this;
  67287. var numSamples = 16;
  67288. var sampleSphere = [
  67289. 0.5381, 0.1856, -0.4319,
  67290. 0.1379, 0.2486, 0.4430,
  67291. 0.3371, 0.5679, -0.0057,
  67292. -0.6999, -0.0451, -0.0019,
  67293. 0.0689, -0.1598, -0.8547,
  67294. 0.0560, 0.0069, -0.1843,
  67295. -0.0146, 0.1402, 0.0762,
  67296. 0.0100, -0.1924, -0.0344,
  67297. -0.3577, -0.5301, -0.4358,
  67298. -0.3169, 0.1063, 0.0158,
  67299. 0.0103, -0.5869, 0.0046,
  67300. -0.0897, -0.4940, 0.3287,
  67301. 0.7119, -0.0154, -0.0918,
  67302. -0.0533, 0.0596, -0.5411,
  67303. 0.0352, -0.0631, 0.5460,
  67304. -0.4776, 0.2847, -0.0271
  67305. ];
  67306. var samplesFactor = 1.0 / numSamples;
  67307. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  67308. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  67309. "area", "fallOff", "base", "range", "viewport"
  67310. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  67311. this._ssaoPostProcess.onApply = function (effect) {
  67312. if (_this._firstUpdate) {
  67313. effect.setArray3("sampleSphere", sampleSphere);
  67314. effect.setFloat("samplesFactor", samplesFactor);
  67315. effect.setFloat("randTextureTiles", 4.0);
  67316. }
  67317. effect.setFloat("totalStrength", _this.totalStrength);
  67318. effect.setFloat("radius", _this.radius);
  67319. effect.setFloat("area", _this.area);
  67320. effect.setFloat("fallOff", _this.fallOff);
  67321. effect.setFloat("base", _this.base);
  67322. effect.setTexture("textureSampler", _this._depthTexture);
  67323. effect.setTexture("randomSampler", _this._randomTexture);
  67324. };
  67325. };
  67326. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  67327. var _this = this;
  67328. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  67329. this._ssaoCombinePostProcess.onApply = function (effect) {
  67330. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  67331. };
  67332. };
  67333. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  67334. var size = 512;
  67335. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  67336. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  67337. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  67338. var context = this._randomTexture.getContext();
  67339. var rand = function (min, max) {
  67340. return Math.random() * (max - min) + min;
  67341. };
  67342. var randVector = BABYLON.Vector3.Zero();
  67343. for (var x = 0; x < size; x++) {
  67344. for (var y = 0; y < size; y++) {
  67345. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  67346. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  67347. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  67348. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  67349. context.fillRect(x, y, 1, 1);
  67350. }
  67351. }
  67352. this._randomTexture.update(false);
  67353. };
  67354. __decorate([
  67355. BABYLON.serialize()
  67356. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  67357. __decorate([
  67358. BABYLON.serialize()
  67359. ], SSAORenderingPipeline.prototype, "radius", void 0);
  67360. __decorate([
  67361. BABYLON.serialize()
  67362. ], SSAORenderingPipeline.prototype, "area", void 0);
  67363. __decorate([
  67364. BABYLON.serialize()
  67365. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  67366. __decorate([
  67367. BABYLON.serialize()
  67368. ], SSAORenderingPipeline.prototype, "base", void 0);
  67369. return SSAORenderingPipeline;
  67370. }(BABYLON.PostProcessRenderPipeline));
  67371. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  67372. })(BABYLON || (BABYLON = {}));
  67373. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  67374. var BABYLON;
  67375. (function (BABYLON) {
  67376. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  67377. __extends(SSAO2RenderingPipeline, _super);
  67378. /**
  67379. * @constructor
  67380. * @param {string} name - The rendering pipeline name
  67381. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  67382. * @param {any} ratio - The size of the postprocesses. Can be a number shared between passes or an object for more precision: { ssaoRatio: 0.5, blurRatio: 1.0 }
  67383. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  67384. */
  67385. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  67386. var _this = _super.call(this, scene.getEngine(), name) || this;
  67387. // Members
  67388. /**
  67389. * The PassPostProcess id in the pipeline that contains the original scene color
  67390. * @type {string}
  67391. */
  67392. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  67393. /**
  67394. * The SSAO PostProcess id in the pipeline
  67395. * @type {string}
  67396. */
  67397. _this.SSAORenderEffect = "SSAORenderEffect";
  67398. /**
  67399. * The horizontal blur PostProcess id in the pipeline
  67400. * @type {string}
  67401. */
  67402. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  67403. /**
  67404. * The vertical blur PostProcess id in the pipeline
  67405. * @type {string}
  67406. */
  67407. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  67408. /**
  67409. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  67410. * @type {string}
  67411. */
  67412. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  67413. /**
  67414. * The output strength of the SSAO post-process. Default value is 1.0.
  67415. * @type {number}
  67416. */
  67417. _this.totalStrength = 1.0;
  67418. /**
  67419. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  67420. * @type {number}
  67421. */
  67422. _this.maxZ = 100.0;
  67423. /**
  67424. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  67425. * @type {number}
  67426. */
  67427. _this.minZAspect = 0.2;
  67428. /**
  67429. * Number of samples used for the SSAO calculations. Default value is 8
  67430. * @type {number}
  67431. */
  67432. _this._samples = 8;
  67433. /**
  67434. * Are we using bilateral blur ?
  67435. * @type {boolean}
  67436. */
  67437. _this._expensiveBlur = true;
  67438. /**
  67439. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  67440. * @type {number}
  67441. */
  67442. _this.radius = 2.0;
  67443. /**
  67444. * The base color of the SSAO post-process
  67445. * The final result is "base + ssao" between [0, 1]
  67446. * @type {number}
  67447. */
  67448. _this.base = 0.1;
  67449. _this._firstUpdate = true;
  67450. _this._scene = scene;
  67451. if (!_this.isSupported) {
  67452. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  67453. return _this;
  67454. }
  67455. var ssaoRatio = ratio.ssaoRatio || ratio;
  67456. var blurRatio = ratio.blurRatio || ratio;
  67457. // Set up assets
  67458. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  67459. _this._createRandomTexture();
  67460. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  67461. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  67462. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  67463. _this._createSSAOPostProcess(1.0);
  67464. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  67465. _this._createSSAOCombinePostProcess(blurRatio);
  67466. // Set up pipeline
  67467. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  67468. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  67469. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  67470. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  67471. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  67472. // Finish
  67473. scene.postProcessRenderPipelineManager.addPipeline(_this);
  67474. if (cameras)
  67475. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  67476. return _this;
  67477. }
  67478. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  67479. get: function () {
  67480. return this._samples;
  67481. },
  67482. set: function (n) {
  67483. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  67484. this._samples = n;
  67485. this._sampleSphere = this._generateHemisphere();
  67486. this._firstUpdate = true;
  67487. },
  67488. enumerable: true,
  67489. configurable: true
  67490. });
  67491. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  67492. get: function () {
  67493. return this._expensiveBlur;
  67494. },
  67495. set: function (b) {
  67496. this._blurHPostProcess.updateEffect("#define BILATERAL_BLUR\n#define BILATERAL_BLUR_H\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  67497. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  67498. this._expensiveBlur = b;
  67499. this._firstUpdate = true;
  67500. },
  67501. enumerable: true,
  67502. configurable: true
  67503. });
  67504. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  67505. /**
  67506. * Support test.
  67507. * @type {boolean}
  67508. */
  67509. get: function () {
  67510. var engine = BABYLON.Engine.LastCreatedEngine;
  67511. if (!engine) {
  67512. return false;
  67513. }
  67514. return engine.getCaps().drawBuffersExtension;
  67515. },
  67516. enumerable: true,
  67517. configurable: true
  67518. });
  67519. // Public Methods
  67520. /**
  67521. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  67522. */
  67523. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  67524. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  67525. for (var i = 0; i < this._scene.cameras.length; i++) {
  67526. var camera = this._scene.cameras[i];
  67527. this._originalColorPostProcess.dispose(camera);
  67528. this._ssaoPostProcess.dispose(camera);
  67529. this._blurHPostProcess.dispose(camera);
  67530. this._blurVPostProcess.dispose(camera);
  67531. this._ssaoCombinePostProcess.dispose(camera);
  67532. }
  67533. this._randomTexture.dispose();
  67534. if (disableGeometryBufferRenderer)
  67535. this._scene.disableGeometryBufferRenderer();
  67536. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  67537. _super.prototype.dispose.call(this);
  67538. };
  67539. // Private Methods
  67540. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  67541. var _this = this;
  67542. this._samplerOffsets = [];
  67543. var expensive = this.expensiveBlur;
  67544. for (var i = -8; i < 8; i++) {
  67545. this._samplerOffsets.push(i * 2 + 0.5);
  67546. }
  67547. this._blurHPostProcess = new BABYLON.PostProcess("BlurH", "ssao2", ["outSize", "samplerOffsets", "near", "far", "radius"], ["depthSampler"], ssaoRatio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define BILATERAL_BLUR\n#define BILATERAL_BLUR_H\n#define SAMPLES 16\n#define EXPENSIVE " + (expensive ? "1" : "0") + "\n");
  67548. this._blurHPostProcess.onApply = function (effect) {
  67549. if (!_this._scene.activeCamera) {
  67550. return;
  67551. }
  67552. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  67553. effect.setFloat("near", _this._scene.activeCamera.minZ);
  67554. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  67555. effect.setFloat("radius", _this.radius);
  67556. effect.setTexture("depthSampler", _this._depthTexture);
  67557. if (_this._firstUpdate) {
  67558. effect.setArray("samplerOffsets", _this._samplerOffsets);
  67559. }
  67560. };
  67561. this._blurVPostProcess = new BABYLON.PostProcess("BlurV", "ssao2", ["outSize", "samplerOffsets", "near", "far", "radius"], ["depthSampler"], blurRatio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define BILATERAL_BLUR\n#define BILATERAL_BLUR_V\n#define SAMPLES 16\n#define EXPENSIVE " + (expensive ? "1" : "0") + "\n");
  67562. this._blurVPostProcess.onApply = function (effect) {
  67563. if (!_this._scene.activeCamera) {
  67564. return;
  67565. }
  67566. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  67567. effect.setFloat("near", _this._scene.activeCamera.minZ);
  67568. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  67569. effect.setFloat("radius", _this.radius);
  67570. effect.setTexture("depthSampler", _this._depthTexture);
  67571. if (_this._firstUpdate) {
  67572. effect.setArray("samplerOffsets", _this._samplerOffsets);
  67573. _this._firstUpdate = false;
  67574. }
  67575. };
  67576. };
  67577. SSAO2RenderingPipeline.prototype._rebuild = function () {
  67578. this._firstUpdate = true;
  67579. _super.prototype._rebuild.call(this);
  67580. };
  67581. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  67582. var numSamples = this.samples;
  67583. var result = [];
  67584. var vector, scale;
  67585. var rand = function (min, max) {
  67586. return Math.random() * (max - min) + min;
  67587. };
  67588. var i = 0;
  67589. while (i < numSamples) {
  67590. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  67591. vector.normalize();
  67592. scale = i / numSamples;
  67593. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  67594. vector.scaleInPlace(scale);
  67595. result.push(vector.x, vector.y, vector.z);
  67596. i++;
  67597. }
  67598. return result;
  67599. };
  67600. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  67601. var _this = this;
  67602. var numSamples = this.samples;
  67603. this._sampleSphere = this._generateHemisphere();
  67604. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  67605. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  67606. "base", "range", "projection", "near", "far", "texelSize",
  67607. "xViewport", "yViewport", "maxZ", "minZAspect"
  67608. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  67609. this._ssaoPostProcess.onApply = function (effect) {
  67610. if (_this._firstUpdate) {
  67611. effect.setArray3("sampleSphere", _this._sampleSphere);
  67612. effect.setFloat("randTextureTiles", 4.0);
  67613. }
  67614. if (!_this._scene.activeCamera) {
  67615. return;
  67616. }
  67617. effect.setFloat("samplesFactor", 1 / _this.samples);
  67618. effect.setFloat("totalStrength", _this.totalStrength);
  67619. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  67620. effect.setFloat("radius", _this.radius);
  67621. effect.setFloat("maxZ", _this.maxZ);
  67622. effect.setFloat("minZAspect", _this.minZAspect);
  67623. effect.setFloat("base", _this.base);
  67624. effect.setFloat("near", _this._scene.activeCamera.minZ);
  67625. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  67626. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  67627. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  67628. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  67629. effect.setTexture("textureSampler", _this._depthTexture);
  67630. effect.setTexture("normalSampler", _this._normalTexture);
  67631. effect.setTexture("randomSampler", _this._randomTexture);
  67632. };
  67633. };
  67634. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  67635. var _this = this;
  67636. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  67637. this._ssaoCombinePostProcess.onApply = function (effect) {
  67638. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  67639. };
  67640. };
  67641. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  67642. var size = 512;
  67643. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  67644. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  67645. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  67646. var context = this._randomTexture.getContext();
  67647. var rand = function (min, max) {
  67648. return Math.random() * (max - min) + min;
  67649. };
  67650. var randVector = BABYLON.Vector3.Zero();
  67651. for (var x = 0; x < size; x++) {
  67652. for (var y = 0; y < size; y++) {
  67653. randVector.x = rand(0.0, 1.0);
  67654. randVector.y = rand(0.0, 1.0);
  67655. randVector.z = 0.0;
  67656. randVector.normalize();
  67657. randVector.scaleInPlace(255);
  67658. randVector.x = Math.floor(randVector.x);
  67659. randVector.y = Math.floor(randVector.y);
  67660. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  67661. context.fillRect(x, y, 1, 1);
  67662. }
  67663. }
  67664. this._randomTexture.update(false);
  67665. };
  67666. __decorate([
  67667. BABYLON.serialize()
  67668. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  67669. __decorate([
  67670. BABYLON.serialize()
  67671. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  67672. __decorate([
  67673. BABYLON.serialize()
  67674. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  67675. __decorate([
  67676. BABYLON.serialize("samples")
  67677. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  67678. __decorate([
  67679. BABYLON.serialize("expensiveBlur")
  67680. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  67681. __decorate([
  67682. BABYLON.serialize()
  67683. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  67684. __decorate([
  67685. BABYLON.serialize()
  67686. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  67687. return SSAO2RenderingPipeline;
  67688. }(BABYLON.PostProcessRenderPipeline));
  67689. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  67690. })(BABYLON || (BABYLON = {}));
  67691. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  67692. // BABYLON.JS Chromatic Aberration GLSL Shader
  67693. // Author: Olivier Guyot
  67694. // Separates very slightly R, G and B colors on the edges of the screen
  67695. // Inspired by Francois Tarlier & Martins Upitis
  67696. var BABYLON;
  67697. (function (BABYLON) {
  67698. var LensRenderingPipeline = /** @class */ (function (_super) {
  67699. __extends(LensRenderingPipeline, _super);
  67700. /**
  67701. * @constructor
  67702. *
  67703. * Effect parameters are as follow:
  67704. * {
  67705. * chromatic_aberration: number; // from 0 to x (1 for realism)
  67706. * edge_blur: number; // from 0 to x (1 for realism)
  67707. * distortion: number; // from 0 to x (1 for realism)
  67708. * grain_amount: number; // from 0 to 1
  67709. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  67710. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  67711. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  67712. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  67713. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  67714. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  67715. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  67716. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  67717. * }
  67718. * Note: if an effect parameter is unset, effect is disabled
  67719. *
  67720. * @param {string} name - The rendering pipeline name
  67721. * @param {object} parameters - An object containing all parameters (see above)
  67722. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  67723. * @param {number} ratio - The size of the postprocesses (0.5 means that your postprocess will have a width = canvas.width 0.5 and a height = canvas.height 0.5)
  67724. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  67725. */
  67726. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  67727. if (ratio === void 0) { ratio = 1.0; }
  67728. var _this = _super.call(this, scene.getEngine(), name) || this;
  67729. // Lens effects can be of the following:
  67730. // - chromatic aberration (slight shift of RGB colors)
  67731. // - blur on the edge of the lens
  67732. // - lens distortion
  67733. // - depth-of-field blur & highlights enhancing
  67734. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  67735. // - grain effect (noise or custom texture)
  67736. // Two additional texture samplers are needed:
  67737. // - depth map (for depth-of-field)
  67738. // - grain texture
  67739. /**
  67740. * The chromatic aberration PostProcess id in the pipeline
  67741. * @type {string}
  67742. */
  67743. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  67744. /**
  67745. * The highlights enhancing PostProcess id in the pipeline
  67746. * @type {string}
  67747. */
  67748. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  67749. /**
  67750. * The depth-of-field PostProcess id in the pipeline
  67751. * @type {string}
  67752. */
  67753. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  67754. _this._scene = scene;
  67755. // Fetch texture samplers
  67756. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  67757. if (parameters.grain_texture) {
  67758. _this._grainTexture = parameters.grain_texture;
  67759. }
  67760. else {
  67761. _this._createGrainTexture();
  67762. }
  67763. // save parameters
  67764. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  67765. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  67766. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  67767. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  67768. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  67769. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  67770. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  67771. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  67772. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  67773. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  67774. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  67775. // Create effects
  67776. _this._createChromaticAberrationPostProcess(ratio);
  67777. _this._createHighlightsPostProcess(ratio);
  67778. _this._createDepthOfFieldPostProcess(ratio / 4);
  67779. // Set up pipeline
  67780. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  67781. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  67782. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  67783. if (_this._highlightsGain === -1) {
  67784. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  67785. }
  67786. // Finish
  67787. scene.postProcessRenderPipelineManager.addPipeline(_this);
  67788. if (cameras) {
  67789. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  67790. }
  67791. return _this;
  67792. }
  67793. // public methods (self explanatory)
  67794. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  67795. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  67796. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  67797. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  67798. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  67799. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  67800. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  67801. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  67802. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  67803. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  67804. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  67805. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  67806. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  67807. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  67808. };
  67809. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  67810. this._highlightsPostProcess.updateEffect();
  67811. };
  67812. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  67813. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  67814. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  67815. this._highlightsGain = amount;
  67816. };
  67817. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  67818. if (this._highlightsGain === -1) {
  67819. this._highlightsGain = 1.0;
  67820. }
  67821. this._highlightsThreshold = amount;
  67822. };
  67823. LensRenderingPipeline.prototype.disableHighlights = function () {
  67824. this._highlightsGain = -1;
  67825. };
  67826. /**
  67827. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  67828. */
  67829. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  67830. if (disableDepthRender === void 0) { disableDepthRender = false; }
  67831. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  67832. this._chromaticAberrationPostProcess = null;
  67833. this._highlightsPostProcess = null;
  67834. this._depthOfFieldPostProcess = null;
  67835. this._grainTexture.dispose();
  67836. if (disableDepthRender)
  67837. this._scene.disableDepthRenderer();
  67838. };
  67839. // colors shifting and distortion
  67840. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  67841. var _this = this;
  67842. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], // uniforms
  67843. [], // samplers
  67844. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  67845. this._chromaticAberrationPostProcess.onApply = function (effect) {
  67846. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  67847. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  67848. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  67849. effect.setFloat('radialIntensity', 1);
  67850. effect.setFloat2('direction', 17, 17);
  67851. effect.setFloat2('centerPosition', 0.5, 0.5);
  67852. };
  67853. };
  67854. // highlights enhancing
  67855. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  67856. var _this = this;
  67857. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  67858. [], // samplers
  67859. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  67860. this._highlightsPostProcess.onApply = function (effect) {
  67861. effect.setFloat('gain', _this._highlightsGain);
  67862. effect.setFloat('threshold', _this._highlightsThreshold);
  67863. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  67864. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  67865. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  67866. };
  67867. };
  67868. // colors shifting and distortion
  67869. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  67870. var _this = this;
  67871. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  67872. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  67873. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  67874. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  67875. this._depthOfFieldPostProcess.onApply = function (effect) {
  67876. effect.setTexture("depthSampler", _this._depthTexture);
  67877. effect.setTexture("grainSampler", _this._grainTexture);
  67878. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  67879. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  67880. effect.setFloat('grain_amount', _this._grainAmount);
  67881. effect.setBool('blur_noise', _this._blurNoise);
  67882. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  67883. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  67884. effect.setFloat('distortion', _this._distortion);
  67885. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  67886. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  67887. effect.setFloat('aperture', _this._dofAperture);
  67888. effect.setFloat('darken', _this._dofDarken);
  67889. effect.setFloat('edge_blur', _this._edgeBlur);
  67890. effect.setBool('highlights', (_this._highlightsGain !== -1));
  67891. if (_this._scene.activeCamera) {
  67892. effect.setFloat('near', _this._scene.activeCamera.minZ);
  67893. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  67894. }
  67895. };
  67896. };
  67897. // creates a black and white random noise texture, 512x512
  67898. LensRenderingPipeline.prototype._createGrainTexture = function () {
  67899. var size = 512;
  67900. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  67901. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  67902. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  67903. var context = this._grainTexture.getContext();
  67904. var rand = function (min, max) {
  67905. return Math.random() * (max - min) + min;
  67906. };
  67907. var value;
  67908. for (var x = 0; x < size; x++) {
  67909. for (var y = 0; y < size; y++) {
  67910. value = Math.floor(rand(0.42, 0.58) * 255);
  67911. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  67912. context.fillRect(x, y, 1, 1);
  67913. }
  67914. }
  67915. this._grainTexture.update(false);
  67916. };
  67917. return LensRenderingPipeline;
  67918. }(BABYLON.PostProcessRenderPipeline));
  67919. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  67920. })(BABYLON || (BABYLON = {}));
  67921. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  67922. var BABYLON;
  67923. (function (BABYLON) {
  67924. var StandardRenderingPipeline = /** @class */ (function (_super) {
  67925. __extends(StandardRenderingPipeline, _super);
  67926. /**
  67927. * @constructor
  67928. * @param {string} name - The rendering pipeline name
  67929. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  67930. * @param {any} ratio - The size of the postprocesses (0.5 means that your postprocess will have a width = canvas.width 0.5 and a height = canvas.height 0.5)
  67931. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  67932. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  67933. */
  67934. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  67935. if (originalPostProcess === void 0) { originalPostProcess = null; }
  67936. var _this = _super.call(this, scene.getEngine(), name) || this;
  67937. _this.downSampleX4PostProcess = null;
  67938. _this.brightPassPostProcess = null;
  67939. _this.blurHPostProcesses = [];
  67940. _this.blurVPostProcesses = [];
  67941. _this.textureAdderPostProcess = null;
  67942. _this.volumetricLightPostProcess = null;
  67943. _this.volumetricLightSmoothXPostProcess = null;
  67944. _this.volumetricLightSmoothYPostProcess = null;
  67945. _this.volumetricLightMergePostProces = null;
  67946. _this.volumetricLightFinalPostProcess = null;
  67947. _this.luminancePostProcess = null;
  67948. _this.luminanceDownSamplePostProcesses = [];
  67949. _this.hdrPostProcess = null;
  67950. _this.textureAdderFinalPostProcess = null;
  67951. _this.lensFlareFinalPostProcess = null;
  67952. _this.hdrFinalPostProcess = null;
  67953. _this.lensFlarePostProcess = null;
  67954. _this.lensFlareComposePostProcess = null;
  67955. _this.motionBlurPostProcess = null;
  67956. _this.depthOfFieldPostProcess = null;
  67957. // Values
  67958. _this.brightThreshold = 1.0;
  67959. _this.blurWidth = 512.0;
  67960. _this.horizontalBlur = false;
  67961. _this.exposure = 1.0;
  67962. _this.lensTexture = null;
  67963. _this.volumetricLightCoefficient = 0.2;
  67964. _this.volumetricLightPower = 4.0;
  67965. _this.volumetricLightBlurScale = 64.0;
  67966. _this.sourceLight = null;
  67967. _this.hdrMinimumLuminance = 1.0;
  67968. _this.hdrDecreaseRate = 0.5;
  67969. _this.hdrIncreaseRate = 0.5;
  67970. _this.lensColorTexture = null;
  67971. _this.lensFlareStrength = 20.0;
  67972. _this.lensFlareGhostDispersal = 1.4;
  67973. _this.lensFlareHaloWidth = 0.7;
  67974. _this.lensFlareDistortionStrength = 16.0;
  67975. _this.lensStarTexture = null;
  67976. _this.lensFlareDirtTexture = null;
  67977. _this.depthOfFieldDistance = 10.0;
  67978. _this.depthOfFieldBlurWidth = 64.0;
  67979. _this.motionStrength = 1.0;
  67980. // IAnimatable
  67981. _this.animations = [];
  67982. _this._currentDepthOfFieldSource = null;
  67983. _this._hdrCurrentLuminance = 1.0;
  67984. // Getters and setters
  67985. _this._bloomEnabled = true;
  67986. _this._depthOfFieldEnabled = false;
  67987. _this._vlsEnabled = false;
  67988. _this._lensFlareEnabled = false;
  67989. _this._hdrEnabled = false;
  67990. _this._motionBlurEnabled = false;
  67991. _this._motionBlurSamples = 64.0;
  67992. _this._volumetricLightStepsCount = 50.0;
  67993. _this._cameras = cameras || [];
  67994. // Initialize
  67995. _this._scene = scene;
  67996. _this._basePostProcess = originalPostProcess;
  67997. _this._ratio = ratio;
  67998. // Misc
  67999. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  68000. // Finish
  68001. scene.postProcessRenderPipelineManager.addPipeline(_this);
  68002. _this._buildPipeline();
  68003. return _this;
  68004. }
  68005. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  68006. get: function () {
  68007. return this._bloomEnabled;
  68008. },
  68009. set: function (enabled) {
  68010. if (this._bloomEnabled === enabled) {
  68011. return;
  68012. }
  68013. this._bloomEnabled = enabled;
  68014. this._buildPipeline();
  68015. },
  68016. enumerable: true,
  68017. configurable: true
  68018. });
  68019. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  68020. get: function () {
  68021. return this._depthOfFieldEnabled;
  68022. },
  68023. set: function (enabled) {
  68024. if (this._depthOfFieldEnabled === enabled) {
  68025. return;
  68026. }
  68027. this._depthOfFieldEnabled = enabled;
  68028. this._buildPipeline();
  68029. },
  68030. enumerable: true,
  68031. configurable: true
  68032. });
  68033. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  68034. get: function () {
  68035. return this._lensFlareEnabled;
  68036. },
  68037. set: function (enabled) {
  68038. if (this._lensFlareEnabled === enabled) {
  68039. return;
  68040. }
  68041. this._lensFlareEnabled = enabled;
  68042. this._buildPipeline();
  68043. },
  68044. enumerable: true,
  68045. configurable: true
  68046. });
  68047. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  68048. get: function () {
  68049. return this._hdrEnabled;
  68050. },
  68051. set: function (enabled) {
  68052. if (this._hdrEnabled === enabled) {
  68053. return;
  68054. }
  68055. this._hdrEnabled = enabled;
  68056. this._buildPipeline();
  68057. },
  68058. enumerable: true,
  68059. configurable: true
  68060. });
  68061. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  68062. get: function () {
  68063. return this._vlsEnabled;
  68064. },
  68065. set: function (enabled) {
  68066. if (this._vlsEnabled === enabled) {
  68067. return;
  68068. }
  68069. if (enabled) {
  68070. var geometry = this._scene.enableGeometryBufferRenderer();
  68071. if (!geometry) {
  68072. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  68073. return;
  68074. }
  68075. }
  68076. this._vlsEnabled = enabled;
  68077. this._buildPipeline();
  68078. },
  68079. enumerable: true,
  68080. configurable: true
  68081. });
  68082. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  68083. get: function () {
  68084. return this._motionBlurEnabled;
  68085. },
  68086. set: function (enabled) {
  68087. if (this._motionBlurEnabled === enabled) {
  68088. return;
  68089. }
  68090. this._motionBlurEnabled = enabled;
  68091. this._buildPipeline();
  68092. },
  68093. enumerable: true,
  68094. configurable: true
  68095. });
  68096. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  68097. get: function () {
  68098. return this._volumetricLightStepsCount;
  68099. },
  68100. set: function (count) {
  68101. if (this.volumetricLightPostProcess) {
  68102. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  68103. }
  68104. this._volumetricLightStepsCount = count;
  68105. },
  68106. enumerable: true,
  68107. configurable: true
  68108. });
  68109. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  68110. get: function () {
  68111. return this._motionBlurSamples;
  68112. },
  68113. set: function (samples) {
  68114. if (this.motionBlurPostProcess) {
  68115. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  68116. }
  68117. this._motionBlurSamples = samples;
  68118. },
  68119. enumerable: true,
  68120. configurable: true
  68121. });
  68122. StandardRenderingPipeline.prototype._buildPipeline = function () {
  68123. var _this = this;
  68124. var ratio = this._ratio;
  68125. var scene = this._scene;
  68126. this._disposePostProcesses();
  68127. this._reset();
  68128. // Create pass post-process
  68129. if (!this._basePostProcess) {
  68130. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  68131. this.originalPostProcess.onApply = function (effect) {
  68132. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  68133. };
  68134. }
  68135. else {
  68136. this.originalPostProcess = this._basePostProcess;
  68137. }
  68138. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  68139. this._currentDepthOfFieldSource = this.originalPostProcess;
  68140. if (this._vlsEnabled) {
  68141. // Create volumetric light
  68142. this._createVolumetricLightPostProcess(scene, ratio);
  68143. // Create volumetric light final post-process
  68144. this.volumetricLightFinalPostProcess = new BABYLON.PostProcess("HDRVLSFinal", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  68145. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  68146. }
  68147. if (this._bloomEnabled) {
  68148. // Create down sample X4 post-process
  68149. this._createDownSampleX4PostProcess(scene, ratio / 2);
  68150. // Create bright pass post-process
  68151. this._createBrightPassPostProcess(scene, ratio / 2);
  68152. // Create gaussian blur post-processes (down sampling blurs)
  68153. this._createBlurPostProcesses(scene, ratio / 4, 1);
  68154. // Create texture adder post-process
  68155. this._createTextureAdderPostProcess(scene, ratio);
  68156. // Create depth-of-field source post-process
  68157. this.textureAdderFinalPostProcess = new BABYLON.PostProcess("HDRDepthOfFieldSource", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  68158. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  68159. }
  68160. if (this._lensFlareEnabled) {
  68161. // Create lens flare post-process
  68162. this._createLensFlarePostProcess(scene, ratio);
  68163. // Create depth-of-field source post-process post lens-flare and disable it now
  68164. this.lensFlareFinalPostProcess = new BABYLON.PostProcess("HDRPostLensFlareDepthOfFieldSource", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  68165. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  68166. }
  68167. if (this._hdrEnabled) {
  68168. // Create luminance
  68169. this._createLuminancePostProcesses(scene, this._floatTextureType);
  68170. // Create HDR
  68171. this._createHdrPostProcess(scene, ratio);
  68172. // Create depth-of-field source post-process post hdr and disable it now
  68173. this.hdrFinalPostProcess = new BABYLON.PostProcess("HDRPostHDReDepthOfFieldSource", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  68174. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  68175. }
  68176. if (this._depthOfFieldEnabled) {
  68177. // Create gaussian blur used by depth-of-field
  68178. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  68179. // Create depth-of-field post-process
  68180. this._createDepthOfFieldPostProcess(scene, ratio);
  68181. }
  68182. if (this._motionBlurEnabled) {
  68183. // Create motion blur post-process
  68184. this._createMotionBlurPostProcess(scene, ratio);
  68185. }
  68186. if (this._cameras !== null) {
  68187. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  68188. }
  68189. };
  68190. // Down Sample X4 Post-Processs
  68191. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  68192. var _this = this;
  68193. var downSampleX4Offsets = new Array(32);
  68194. this.downSampleX4PostProcess = new BABYLON.PostProcess("HDRDownSampleX4", "standard", ["dsOffsets"], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define DOWN_SAMPLE_X4", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  68195. this.downSampleX4PostProcess.onApply = function (effect) {
  68196. var id = 0;
  68197. var width = _this.downSampleX4PostProcess.width;
  68198. var height = _this.downSampleX4PostProcess.height;
  68199. for (var i = -2; i < 2; i++) {
  68200. for (var j = -2; j < 2; j++) {
  68201. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  68202. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  68203. id += 2;
  68204. }
  68205. }
  68206. effect.setArray2("dsOffsets", downSampleX4Offsets);
  68207. };
  68208. // Add to pipeline
  68209. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  68210. };
  68211. // Brightpass Post-Process
  68212. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  68213. var _this = this;
  68214. var brightOffsets = new Array(8);
  68215. this.brightPassPostProcess = new BABYLON.PostProcess("HDRBrightPass", "standard", ["dsOffsets", "brightThreshold"], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define BRIGHT_PASS", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  68216. this.brightPassPostProcess.onApply = function (effect) {
  68217. var sU = (1.0 / _this.brightPassPostProcess.width);
  68218. var sV = (1.0 / _this.brightPassPostProcess.height);
  68219. brightOffsets[0] = -0.5 * sU;
  68220. brightOffsets[1] = 0.5 * sV;
  68221. brightOffsets[2] = 0.5 * sU;
  68222. brightOffsets[3] = 0.5 * sV;
  68223. brightOffsets[4] = -0.5 * sU;
  68224. brightOffsets[5] = -0.5 * sV;
  68225. brightOffsets[6] = 0.5 * sU;
  68226. brightOffsets[7] = -0.5 * sV;
  68227. effect.setArray2("dsOffsets", brightOffsets);
  68228. effect.setFloat("brightThreshold", _this.brightThreshold);
  68229. };
  68230. // Add to pipeline
  68231. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  68232. };
  68233. // Create blur H&V post-processes
  68234. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  68235. var _this = this;
  68236. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  68237. var engine = scene.getEngine();
  68238. var blurX = new BABYLON.BlurPostProcess("HDRBlurH" + "_" + indice, new BABYLON.Vector2(1, 0), this[blurWidthKey], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  68239. var blurY = new BABYLON.BlurPostProcess("HDRBlurV" + "_" + indice, new BABYLON.Vector2(0, 1), this[blurWidthKey], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  68240. blurX.onActivateObservable.add(function () {
  68241. var dw = blurX.width / engine.getRenderWidth();
  68242. blurX.kernel = _this[blurWidthKey] * dw;
  68243. });
  68244. blurY.onActivateObservable.add(function () {
  68245. var dw = blurY.height / engine.getRenderHeight();
  68246. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  68247. });
  68248. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  68249. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  68250. this.blurHPostProcesses.push(blurX);
  68251. this.blurVPostProcesses.push(blurY);
  68252. };
  68253. // Create texture adder post-process
  68254. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  68255. var _this = this;
  68256. this.textureAdderPostProcess = new BABYLON.PostProcess("HDRTextureAdder", "standard", ["exposure"], ["otherSampler", "lensSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define TEXTURE_ADDER", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  68257. this.textureAdderPostProcess.onApply = function (effect) {
  68258. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  68259. effect.setTexture("lensSampler", _this.lensTexture);
  68260. effect.setFloat("exposure", _this.exposure);
  68261. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  68262. };
  68263. // Add to pipeline
  68264. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  68265. };
  68266. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  68267. var _this = this;
  68268. var geometryRenderer = scene.enableGeometryBufferRenderer();
  68269. geometryRenderer.enablePosition = true;
  68270. var geometry = geometryRenderer.getGBuffer();
  68271. // Base post-process
  68272. this.volumetricLightPostProcess = new BABYLON.PostProcess("HDRVLS", "standard", ["shadowViewProjection", "cameraPosition", "sunDirection", "sunColor", "scatteringCoefficient", "scatteringPower", "depthValues"], ["shadowMapSampler", "positionSampler"], ratio / 8, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLS\n#define NB_STEPS " + this._volumetricLightStepsCount.toFixed(1));
  68273. var depthValues = BABYLON.Vector2.Zero();
  68274. this.volumetricLightPostProcess.onApply = function (effect) {
  68275. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  68276. var generator = _this.sourceLight.getShadowGenerator();
  68277. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  68278. effect.setTexture("positionSampler", geometry.textures[2]);
  68279. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  68280. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  68281. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  68282. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  68283. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  68284. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  68285. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  68286. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  68287. effect.setVector2("depthValues", depthValues);
  68288. }
  68289. };
  68290. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  68291. // Smooth
  68292. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  68293. // Merge
  68294. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  68295. this.volumetricLightMergePostProces.onApply = function (effect) {
  68296. effect.setTextureFromPostProcess("originalSampler", _this.originalPostProcess);
  68297. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  68298. };
  68299. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  68300. };
  68301. // Create luminance
  68302. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  68303. var _this = this;
  68304. // Create luminance
  68305. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  68306. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  68307. var offsets = [];
  68308. this.luminancePostProcess.onApply = function (effect) {
  68309. var sU = (1.0 / _this.luminancePostProcess.width);
  68310. var sV = (1.0 / _this.luminancePostProcess.height);
  68311. offsets[0] = -0.5 * sU;
  68312. offsets[1] = 0.5 * sV;
  68313. offsets[2] = 0.5 * sU;
  68314. offsets[3] = 0.5 * sV;
  68315. offsets[4] = -0.5 * sU;
  68316. offsets[5] = -0.5 * sV;
  68317. offsets[6] = 0.5 * sU;
  68318. offsets[7] = -0.5 * sV;
  68319. effect.setArray2("lumOffsets", offsets);
  68320. };
  68321. // Add to pipeline
  68322. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  68323. // Create down sample luminance
  68324. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  68325. var size = Math.pow(3, i);
  68326. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  68327. if (i === 0) {
  68328. defines += "#define FINAL_DOWN_SAMPLER";
  68329. }
  68330. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  68331. this.luminanceDownSamplePostProcesses.push(postProcess);
  68332. }
  68333. // Create callbacks and add effects
  68334. var lastLuminance = this.luminancePostProcess;
  68335. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  68336. var downSampleOffsets = new Array(18);
  68337. pp.onApply = function (effect) {
  68338. if (!lastLuminance) {
  68339. return;
  68340. }
  68341. var id = 0;
  68342. for (var x = -1; x < 2; x++) {
  68343. for (var y = -1; y < 2; y++) {
  68344. downSampleOffsets[id] = x / lastLuminance.width;
  68345. downSampleOffsets[id + 1] = y / lastLuminance.height;
  68346. id += 2;
  68347. }
  68348. }
  68349. effect.setArray2("dsOffsets", downSampleOffsets);
  68350. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  68351. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  68352. lastLuminance = _this.luminancePostProcess;
  68353. }
  68354. else {
  68355. lastLuminance = pp;
  68356. }
  68357. };
  68358. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  68359. pp.onAfterRender = function (effect) {
  68360. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  68361. var bit_shift = new BABYLON.Vector4(1.0 / (255.0 * 255.0 * 255.0), 1.0 / (255.0 * 255.0), 1.0 / 255.0, 1.0);
  68362. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  68363. };
  68364. }
  68365. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  68366. });
  68367. };
  68368. // Create HDR post-process
  68369. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  68370. var _this = this;
  68371. this.hdrPostProcess = new BABYLON.PostProcess("HDR", "standard", ["averageLuminance"], ["textureAdderSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define HDR", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  68372. var outputLiminance = 1;
  68373. var time = 0;
  68374. var lastTime = 0;
  68375. this.hdrPostProcess.onApply = function (effect) {
  68376. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  68377. time += scene.getEngine().getDeltaTime();
  68378. if (outputLiminance < 0) {
  68379. outputLiminance = _this._hdrCurrentLuminance;
  68380. }
  68381. else {
  68382. var dt = (lastTime - time) / 1000.0;
  68383. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  68384. outputLiminance += _this.hdrDecreaseRate * dt;
  68385. }
  68386. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  68387. outputLiminance -= _this.hdrIncreaseRate * dt;
  68388. }
  68389. else {
  68390. outputLiminance = _this._hdrCurrentLuminance;
  68391. }
  68392. }
  68393. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  68394. effect.setFloat("averageLuminance", outputLiminance);
  68395. lastTime = time;
  68396. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  68397. };
  68398. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  68399. };
  68400. // Create lens flare post-process
  68401. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  68402. var _this = this;
  68403. this.lensFlarePostProcess = new BABYLON.PostProcess("HDRLensFlare", "standard", ["strength", "ghostDispersal", "haloWidth", "resolution", "distortionStrength"], ["lensColorSampler"], ratio / 2, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LENS_FLARE", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  68404. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  68405. this._createBlurPostProcesses(scene, ratio / 4, 2);
  68406. this.lensFlareComposePostProcess = new BABYLON.PostProcess("HDRLensFlareCompose", "standard", ["lensStarMatrix"], ["otherSampler", "lensDirtSampler", "lensStarSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LENS_FLARE_COMPOSE", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  68407. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  68408. var resolution = new BABYLON.Vector2(0, 0);
  68409. // Lens flare
  68410. this.lensFlarePostProcess.onApply = function (effect) {
  68411. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  68412. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  68413. effect.setFloat("strength", _this.lensFlareStrength);
  68414. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  68415. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  68416. // Shift
  68417. resolution.x = _this.lensFlarePostProcess.width;
  68418. resolution.y = _this.lensFlarePostProcess.height;
  68419. effect.setVector2("resolution", resolution);
  68420. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  68421. };
  68422. // Compose
  68423. var scaleBias1 = BABYLON.Matrix.FromValues(2.0, 0.0, -1.0, 0.0, 0.0, 2.0, -1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0);
  68424. var scaleBias2 = BABYLON.Matrix.FromValues(0.5, 0.0, 0.5, 0.0, 0.0, 0.5, 0.5, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0);
  68425. this.lensFlareComposePostProcess.onApply = function (effect) {
  68426. if (!_this._scene.activeCamera) {
  68427. return;
  68428. }
  68429. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  68430. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  68431. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  68432. // Lens start rotation matrix
  68433. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  68434. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  68435. var camRot = BABYLON.Vector3.Dot(camerax.toVector3(), new BABYLON.Vector3(1.0, 0.0, 0.0)) + BABYLON.Vector3.Dot(cameraz.toVector3(), new BABYLON.Vector3(0.0, 0.0, 1.0));
  68436. camRot *= 4.0;
  68437. var starRotation = BABYLON.Matrix.FromValues(Math.cos(camRot) * 0.5, -Math.sin(camRot), 0.0, 0.0, Math.sin(camRot), Math.cos(camRot) * 0.5, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0);
  68438. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  68439. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  68440. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  68441. };
  68442. };
  68443. // Create depth-of-field post-process
  68444. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  68445. var _this = this;
  68446. this.depthOfFieldPostProcess = new BABYLON.PostProcess("HDRDepthOfField", "standard", ["distance"], ["otherSampler", "depthSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define DEPTH_OF_FIELD", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  68447. this.depthOfFieldPostProcess.onApply = function (effect) {
  68448. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  68449. effect.setTexture("depthSampler", _this._getDepthTexture());
  68450. effect.setFloat("distance", _this.depthOfFieldDistance);
  68451. };
  68452. // Add to pipeline
  68453. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  68454. };
  68455. // Create motion blur post-process
  68456. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  68457. var _this = this;
  68458. this.motionBlurPostProcess = new BABYLON.PostProcess("HDRMotionBlur", "standard", ["inverseViewProjection", "prevViewProjection", "screenSize", "motionScale", "motionStrength"], ["depthSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + this.motionBlurSamples.toFixed(1), BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  68459. var motionScale = 0;
  68460. var prevViewProjection = BABYLON.Matrix.Identity();
  68461. var invViewProjection = BABYLON.Matrix.Identity();
  68462. var viewProjection = BABYLON.Matrix.Identity();
  68463. var screenSize = BABYLON.Vector2.Zero();
  68464. this.motionBlurPostProcess.onApply = function (effect) {
  68465. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  68466. viewProjection.invertToRef(invViewProjection);
  68467. effect.setMatrix("inverseViewProjection", invViewProjection);
  68468. effect.setMatrix("prevViewProjection", prevViewProjection);
  68469. prevViewProjection = viewProjection;
  68470. screenSize.x = _this.motionBlurPostProcess.width;
  68471. screenSize.y = _this.motionBlurPostProcess.height;
  68472. effect.setVector2("screenSize", screenSize);
  68473. motionScale = scene.getEngine().getFps() / 60.0;
  68474. effect.setFloat("motionScale", motionScale);
  68475. effect.setFloat("motionStrength", _this.motionStrength);
  68476. effect.setTexture("depthSampler", _this._getDepthTexture());
  68477. };
  68478. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  68479. };
  68480. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  68481. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  68482. var renderer = this._scene.enableGeometryBufferRenderer();
  68483. return renderer.getGBuffer().textures[0];
  68484. }
  68485. return this._scene.enableDepthRenderer().getDepthMap();
  68486. };
  68487. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  68488. for (var i = 0; i < this._cameras.length; i++) {
  68489. var camera = this._cameras[i];
  68490. if (this.originalPostProcess) {
  68491. this.originalPostProcess.dispose(camera);
  68492. }
  68493. if (this.downSampleX4PostProcess) {
  68494. this.downSampleX4PostProcess.dispose(camera);
  68495. }
  68496. if (this.brightPassPostProcess) {
  68497. this.brightPassPostProcess.dispose(camera);
  68498. }
  68499. if (this.textureAdderPostProcess) {
  68500. this.textureAdderPostProcess.dispose(camera);
  68501. }
  68502. if (this.textureAdderFinalPostProcess) {
  68503. this.textureAdderFinalPostProcess.dispose(camera);
  68504. }
  68505. if (this.volumetricLightPostProcess) {
  68506. this.volumetricLightPostProcess.dispose(camera);
  68507. }
  68508. if (this.volumetricLightSmoothXPostProcess) {
  68509. this.volumetricLightSmoothXPostProcess.dispose(camera);
  68510. }
  68511. if (this.volumetricLightSmoothYPostProcess) {
  68512. this.volumetricLightSmoothYPostProcess.dispose(camera);
  68513. }
  68514. if (this.volumetricLightMergePostProces) {
  68515. this.volumetricLightMergePostProces.dispose(camera);
  68516. }
  68517. if (this.volumetricLightFinalPostProcess) {
  68518. this.volumetricLightFinalPostProcess.dispose(camera);
  68519. }
  68520. if (this.lensFlarePostProcess) {
  68521. this.lensFlarePostProcess.dispose(camera);
  68522. }
  68523. if (this.lensFlareComposePostProcess) {
  68524. this.lensFlareComposePostProcess.dispose(camera);
  68525. }
  68526. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  68527. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  68528. }
  68529. if (this.luminancePostProcess) {
  68530. this.luminancePostProcess.dispose(camera);
  68531. }
  68532. if (this.hdrPostProcess) {
  68533. this.hdrPostProcess.dispose(camera);
  68534. }
  68535. if (this.hdrFinalPostProcess) {
  68536. this.hdrFinalPostProcess.dispose(camera);
  68537. }
  68538. if (this.depthOfFieldPostProcess) {
  68539. this.depthOfFieldPostProcess.dispose(camera);
  68540. }
  68541. if (this.motionBlurPostProcess) {
  68542. this.motionBlurPostProcess.dispose(camera);
  68543. }
  68544. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  68545. this.blurHPostProcesses[j].dispose(camera);
  68546. }
  68547. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  68548. this.blurVPostProcesses[j].dispose(camera);
  68549. }
  68550. }
  68551. this.originalPostProcess = null;
  68552. this.downSampleX4PostProcess = null;
  68553. this.brightPassPostProcess = null;
  68554. this.textureAdderPostProcess = null;
  68555. this.textureAdderFinalPostProcess = null;
  68556. this.volumetricLightPostProcess = null;
  68557. this.volumetricLightSmoothXPostProcess = null;
  68558. this.volumetricLightSmoothYPostProcess = null;
  68559. this.volumetricLightMergePostProces = null;
  68560. this.volumetricLightFinalPostProcess = null;
  68561. this.lensFlarePostProcess = null;
  68562. this.lensFlareComposePostProcess = null;
  68563. this.luminancePostProcess = null;
  68564. this.hdrPostProcess = null;
  68565. this.hdrFinalPostProcess = null;
  68566. this.depthOfFieldPostProcess = null;
  68567. this.motionBlurPostProcess = null;
  68568. this.luminanceDownSamplePostProcesses = [];
  68569. this.blurHPostProcesses = [];
  68570. this.blurVPostProcesses = [];
  68571. };
  68572. // Dispose
  68573. StandardRenderingPipeline.prototype.dispose = function () {
  68574. this._disposePostProcesses();
  68575. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  68576. _super.prototype.dispose.call(this);
  68577. };
  68578. // Serialize rendering pipeline
  68579. StandardRenderingPipeline.prototype.serialize = function () {
  68580. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  68581. serializationObject.customType = "StandardRenderingPipeline";
  68582. return serializationObject;
  68583. };
  68584. /**
  68585. * Static members
  68586. */
  68587. // Parse serialized pipeline
  68588. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  68589. return BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  68590. };
  68591. // Luminance steps
  68592. StandardRenderingPipeline.LuminanceSteps = 6;
  68593. __decorate([
  68594. BABYLON.serialize()
  68595. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  68596. __decorate([
  68597. BABYLON.serialize()
  68598. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  68599. __decorate([
  68600. BABYLON.serialize()
  68601. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  68602. __decorate([
  68603. BABYLON.serialize()
  68604. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  68605. __decorate([
  68606. BABYLON.serializeAsTexture("lensTexture")
  68607. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  68608. __decorate([
  68609. BABYLON.serialize()
  68610. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  68611. __decorate([
  68612. BABYLON.serialize()
  68613. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  68614. __decorate([
  68615. BABYLON.serialize()
  68616. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  68617. __decorate([
  68618. BABYLON.serialize()
  68619. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  68620. __decorate([
  68621. BABYLON.serialize()
  68622. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  68623. __decorate([
  68624. BABYLON.serialize()
  68625. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  68626. __decorate([
  68627. BABYLON.serializeAsTexture("lensColorTexture")
  68628. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  68629. __decorate([
  68630. BABYLON.serialize()
  68631. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  68632. __decorate([
  68633. BABYLON.serialize()
  68634. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  68635. __decorate([
  68636. BABYLON.serialize()
  68637. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  68638. __decorate([
  68639. BABYLON.serialize()
  68640. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  68641. __decorate([
  68642. BABYLON.serializeAsTexture("lensStarTexture")
  68643. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  68644. __decorate([
  68645. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  68646. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  68647. __decorate([
  68648. BABYLON.serialize()
  68649. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  68650. __decorate([
  68651. BABYLON.serialize()
  68652. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  68653. __decorate([
  68654. BABYLON.serialize()
  68655. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  68656. __decorate([
  68657. BABYLON.serialize()
  68658. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  68659. __decorate([
  68660. BABYLON.serialize()
  68661. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  68662. __decorate([
  68663. BABYLON.serialize()
  68664. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  68665. __decorate([
  68666. BABYLON.serialize()
  68667. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  68668. __decorate([
  68669. BABYLON.serialize()
  68670. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  68671. __decorate([
  68672. BABYLON.serialize()
  68673. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  68674. __decorate([
  68675. BABYLON.serialize()
  68676. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  68677. __decorate([
  68678. BABYLON.serialize()
  68679. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  68680. __decorate([
  68681. BABYLON.serialize()
  68682. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  68683. return StandardRenderingPipeline;
  68684. }(BABYLON.PostProcessRenderPipeline));
  68685. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  68686. })(BABYLON || (BABYLON = {}));
  68687. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  68688. var BABYLON;
  68689. (function (BABYLON) {
  68690. var FxaaPostProcess = /** @class */ (function (_super) {
  68691. __extends(FxaaPostProcess, _super);
  68692. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  68693. if (camera === void 0) { camera = null; }
  68694. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68695. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa") || this;
  68696. _this.onApplyObservable.add(function (effect) {
  68697. var texelSize = _this.texelSize;
  68698. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  68699. });
  68700. return _this;
  68701. }
  68702. return FxaaPostProcess;
  68703. }(BABYLON.PostProcess));
  68704. BABYLON.FxaaPostProcess = FxaaPostProcess;
  68705. })(BABYLON || (BABYLON = {}));
  68706. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  68707. var BABYLON;
  68708. (function (BABYLON) {
  68709. /**
  68710. * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen
  68711. */
  68712. var ChromaticAberrationPostProcess = /** @class */ (function (_super) {
  68713. __extends(ChromaticAberrationPostProcess, _super);
  68714. /**
  68715. * Creates a new instance of @see ChromaticAberrationPostProcess
  68716. * @param name The name of the effect.
  68717. * @param screenWidth The width of the screen to apply the effect on.
  68718. * @param screenHeight The height of the screen to apply the effect on.
  68719. * @param options The required width/height ratio to downsize to before computing the render pass.
  68720. * @param camera The camera to apply the render pass to.
  68721. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  68722. * @param engine The engine which the post process will be applied. (default: current engine)
  68723. * @param reusable If the post process can be reused on the same frame. (default: false)
  68724. * @param textureType Type of textures used when performing the post process. (default: 0)
  68725. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  68726. */
  68727. function ChromaticAberrationPostProcess(name, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  68728. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68729. if (blockCompilation === void 0) { blockCompilation = false; }
  68730. var _this = _super.call(this, name, "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], [], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  68731. /**
  68732. * The amount of seperation of rgb channels (default: 30)
  68733. */
  68734. _this.aberrationAmount = 30;
  68735. /**
  68736. * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0)
  68737. */
  68738. _this.radialIntensity = 0;
  68739. /**
  68740. * The normilized direction in which the rgb channels should be seperated. If set to 0,0 radial direction will be used. (default: Vector2(0.707,0.707))
  68741. */
  68742. _this.direction = new BABYLON.Vector2(0.707, 0.707);
  68743. /**
  68744. * The center position where the radialIntensity should be around. [0.5,0.5 is center of screen, 1,1 is top right corder] (default: Vector2(0.5 ,0.5))
  68745. */
  68746. _this.centerPosition = new BABYLON.Vector2(0.5, 0.5);
  68747. _this.onApplyObservable.add(function (effect) {
  68748. effect.setFloat('chromatic_aberration', _this.aberrationAmount);
  68749. effect.setFloat('screen_width', screenWidth);
  68750. effect.setFloat('screen_height', screenHeight);
  68751. effect.setFloat('radialIntensity', _this.radialIntensity);
  68752. effect.setFloat2('direction', _this.direction.x, _this.direction.y);
  68753. effect.setFloat2('centerPosition', _this.centerPosition.x, _this.centerPosition.y);
  68754. });
  68755. return _this;
  68756. }
  68757. return ChromaticAberrationPostProcess;
  68758. }(BABYLON.PostProcess));
  68759. BABYLON.ChromaticAberrationPostProcess = ChromaticAberrationPostProcess;
  68760. })(BABYLON || (BABYLON = {}));
  68761. //# sourceMappingURL=babylon.chromaticAberrationPostProcess.js.map
  68762. var BABYLON;
  68763. (function (BABYLON) {
  68764. /**
  68765. * The SharpenPostProcess applies a sharpen kernel to every pixel
  68766. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  68767. */
  68768. var SharpenPostProcess = /** @class */ (function (_super) {
  68769. __extends(SharpenPostProcess, _super);
  68770. /**
  68771. * Creates a new instance of @see ConvolutionPostProcess
  68772. * @param name The name of the effect.
  68773. * @param options The required width/height ratio to downsize to before computing the render pass.
  68774. * @param camera The camera to apply the render pass to.
  68775. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  68776. * @param engine The engine which the post process will be applied. (default: current engine)
  68777. * @param reusable If the post process can be reused on the same frame. (default: false)
  68778. * @param textureType Type of textures used when performing the post process. (default: 0)
  68779. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  68780. */
  68781. function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  68782. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68783. if (blockCompilation === void 0) { blockCompilation = false; }
  68784. var _this = _super.call(this, name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  68785. /**
  68786. * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)
  68787. */
  68788. _this.colorAmount = 1.0;
  68789. /**
  68790. * How much sharpness should be applied (default: 0.3)
  68791. */
  68792. _this.edgeAmount = 0.3;
  68793. _this.onApply = function (effect) {
  68794. effect.setFloat2("screenSize", _this.width, _this.height);
  68795. effect.setFloat2("sharpnessAmounts", _this.edgeAmount, _this.colorAmount);
  68796. };
  68797. return _this;
  68798. }
  68799. return SharpenPostProcess;
  68800. }(BABYLON.PostProcess));
  68801. BABYLON.SharpenPostProcess = SharpenPostProcess;
  68802. })(BABYLON || (BABYLON = {}));
  68803. //# sourceMappingURL=babylon.sharpenPostProcess.js.map
  68804. var BABYLON;
  68805. (function (BABYLON) {
  68806. /**
  68807. * The Blur Post Process which blurs an image based on a kernel and direction.
  68808. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  68809. */
  68810. var BlurPostProcess = /** @class */ (function (_super) {
  68811. __extends(BlurPostProcess, _super);
  68812. /**
  68813. * Creates a new instance of @see BlurPostProcess
  68814. * @param name The name of the effect.
  68815. * @param direction The direction in which to blur the image.
  68816. * @param kernel The size of the kernel to be used when computing the blur. eg. Size of 3 will blur the center pixel by 2 pixels surrounding it.
  68817. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  68818. * @param camera The camera to apply the render pass to.
  68819. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  68820. * @param engine The engine which the post process will be applied. (default: current engine)
  68821. * @param reusable If the post process can be reused on the same frame. (default: false)
  68822. * @param textureType Type of textures used when performing the post process. (default: 0)
  68823. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  68824. */
  68825. function BlurPostProcess(name, /** The direction in which to blur the image. */ direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines, blockCompilation) {
  68826. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  68827. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68828. if (defines === void 0) { defines = ""; }
  68829. if (blockCompilation === void 0) { blockCompilation = false; }
  68830. var _this = _super.call(this, name, "kernelBlur", ["delta", "direction", "cameraMinMaxZ"], ["circleOfConfusionSampler"], options, camera, samplingMode, engine, reusable, null, textureType, "kernelBlur", { varyingCount: 0, depCount: 0 }, true) || this;
  68831. _this.direction = direction;
  68832. _this.blockCompilation = blockCompilation;
  68833. _this._packedFloat = false;
  68834. _this._staticDefines = "";
  68835. _this._staticDefines = defines;
  68836. _this.onApplyObservable.add(function (effect) {
  68837. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  68838. });
  68839. _this.kernel = kernel;
  68840. return _this;
  68841. }
  68842. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  68843. /**
  68844. * Gets the length in pixels of the blur sample region
  68845. */
  68846. get: function () {
  68847. return this._idealKernel;
  68848. },
  68849. /**
  68850. * Sets the length in pixels of the blur sample region
  68851. */
  68852. set: function (v) {
  68853. if (this._idealKernel === v) {
  68854. return;
  68855. }
  68856. v = Math.max(v, 1);
  68857. this._idealKernel = v;
  68858. this._kernel = this._nearestBestKernel(v);
  68859. if (!this.blockCompilation) {
  68860. this._updateParameters();
  68861. }
  68862. },
  68863. enumerable: true,
  68864. configurable: true
  68865. });
  68866. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  68867. /**
  68868. * Gets wether or not the blur is unpacking/repacking floats
  68869. */
  68870. get: function () {
  68871. return this._packedFloat;
  68872. },
  68873. /**
  68874. * Sets wether or not the blur needs to unpack/repack floats
  68875. */
  68876. set: function (v) {
  68877. if (this._packedFloat === v) {
  68878. return;
  68879. }
  68880. this._packedFloat = v;
  68881. if (!this.blockCompilation) {
  68882. this._updateParameters();
  68883. }
  68884. },
  68885. enumerable: true,
  68886. configurable: true
  68887. });
  68888. /**
  68889. * Updates the effect with the current post process compile time values and recompiles the shader.
  68890. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  68891. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  68892. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  68893. * @param indexParameters The index parameters to be used for babylons include syntax "#include<kernelBlurVaryingDeclaration>[0..varyingCount]". (default: undefined) See usage in babylon.blurPostProcess.ts and kernelBlur.vertex.fx
  68894. * @param onCompiled Called when the shader has been compiled.
  68895. * @param onError Called if there is an error when compiling a shader.
  68896. */
  68897. BlurPostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  68898. if (defines === void 0) { defines = null; }
  68899. if (uniforms === void 0) { uniforms = null; }
  68900. if (samplers === void 0) { samplers = null; }
  68901. this._updateParameters(onCompiled, onError);
  68902. };
  68903. BlurPostProcess.prototype._updateParameters = function (onCompiled, onError) {
  68904. // Generate sampling offsets and weights
  68905. var N = this._kernel;
  68906. var centerIndex = (N - 1) / 2;
  68907. // Generate Gaussian sampling weights over kernel
  68908. var offsets = [];
  68909. var weights = [];
  68910. var totalWeight = 0;
  68911. for (var i = 0; i < N; i++) {
  68912. var u = i / (N - 1);
  68913. var w = this._gaussianWeight(u * 2.0 - 1);
  68914. offsets[i] = (i - centerIndex);
  68915. weights[i] = w;
  68916. totalWeight += w;
  68917. }
  68918. // Normalize weights
  68919. for (var i = 0; i < weights.length; i++) {
  68920. weights[i] /= totalWeight;
  68921. }
  68922. // Optimize: combine samples to take advantage of hardware linear sampling
  68923. // Walk from left to center, combining pairs (symmetrically)
  68924. var linearSamplingWeights = [];
  68925. var linearSamplingOffsets = [];
  68926. var linearSamplingMap = [];
  68927. for (var i = 0; i <= centerIndex; i += 2) {
  68928. var j = Math.min(i + 1, Math.floor(centerIndex));
  68929. var singleCenterSample = i === j;
  68930. if (singleCenterSample) {
  68931. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  68932. }
  68933. else {
  68934. var sharedCell = j === centerIndex;
  68935. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  68936. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  68937. if (offsetLinear === 0) {
  68938. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  68939. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  68940. }
  68941. else {
  68942. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  68943. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  68944. }
  68945. }
  68946. }
  68947. for (var i = 0; i < linearSamplingMap.length; i++) {
  68948. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  68949. linearSamplingWeights[i] = linearSamplingMap[i].w;
  68950. }
  68951. // Replace with optimized
  68952. offsets = linearSamplingOffsets;
  68953. weights = linearSamplingWeights;
  68954. // Generate shaders
  68955. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  68956. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  68957. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  68958. var defines = "";
  68959. defines += this._staticDefines;
  68960. for (var i = 0; i < varyingCount; i++) {
  68961. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  68962. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  68963. }
  68964. var depCount = 0;
  68965. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  68966. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  68967. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  68968. depCount++;
  68969. }
  68970. if (this.packedFloat) {
  68971. defines += "#define PACKEDFLOAT 1";
  68972. }
  68973. _super.prototype.updateEffect.call(this, defines, null, null, {
  68974. varyingCount: varyingCount,
  68975. depCount: depCount
  68976. }, onCompiled, onError);
  68977. };
  68978. /**
  68979. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  68980. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  68981. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  68982. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  68983. * The gaps between physical kernels are compensated for in the weighting of the samples
  68984. * @param idealKernel Ideal blur kernel.
  68985. * @return Nearest best kernel.
  68986. */
  68987. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  68988. var v = Math.round(idealKernel);
  68989. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  68990. var k = _a[_i];
  68991. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  68992. return Math.max(k, 3);
  68993. }
  68994. }
  68995. return Math.max(v, 3);
  68996. };
  68997. /**
  68998. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  68999. * @param x The point on the Gaussian distribution to sample.
  69000. * @return the value of the Gaussian function at x.
  69001. */
  69002. BlurPostProcess.prototype._gaussianWeight = function (x) {
  69003. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  69004. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  69005. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  69006. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  69007. // truncated at around 1.3% of peak strength.
  69008. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  69009. var sigma = (1 / 3);
  69010. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  69011. var exponent = -((x * x) / (2.0 * sigma * sigma));
  69012. var weight = (1.0 / denominator) * Math.exp(exponent);
  69013. return weight;
  69014. };
  69015. /**
  69016. * Generates a string that can be used as a floating point number in GLSL.
  69017. * @param x Value to print.
  69018. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  69019. * @return GLSL float string.
  69020. */
  69021. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  69022. if (decimalFigures === void 0) { decimalFigures = 8; }
  69023. return x.toFixed(decimalFigures).replace(/0+$/, '');
  69024. };
  69025. return BlurPostProcess;
  69026. }(BABYLON.PostProcess));
  69027. BABYLON.BlurPostProcess = BlurPostProcess;
  69028. })(BABYLON || (BABYLON = {}));
  69029. //# sourceMappingURL=babylon.blurPostProcess.js.map
  69030. var BABYLON;
  69031. (function (BABYLON) {
  69032. /**
  69033. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  69034. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  69035. * based on samples that have a large difference in distance than the center pixel.
  69036. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  69037. */
  69038. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  69039. __extends(DepthOfFieldBlurPostProcess, _super);
  69040. /**
  69041. * Creates a new instance of @see CircleOfConfusionPostProcess
  69042. * @param name The name of the effect.
  69043. * @param scene The scene the effect belongs to.
  69044. * @param direction The direction the blur should be applied.
  69045. * @param kernel The size of the kernel used to blur.
  69046. * @param options The required width/height ratio to downsize to before computing the render pass.
  69047. * @param camera The camera to apply the render pass to.
  69048. * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
  69049. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  69050. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  69051. * @param engine The engine which the post process will be applied. (default: current engine)
  69052. * @param reusable If the post process can be reused on the same frame. (default: false)
  69053. * @param textureType Type of textures used when performing the post process. (default: 0)
  69054. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  69055. */
  69056. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType, blockCompilation) {
  69057. if (imageToBlur === void 0) { imageToBlur = null; }
  69058. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  69059. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69060. if (blockCompilation === void 0) { blockCompilation = false; }
  69061. var _this = _super.call(this, name, direction, kernel, options, camera, samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, "#define DOF 1\r\n", blockCompilation) || this;
  69062. _this.direction = direction;
  69063. _this.onApplyObservable.add(function (effect) {
  69064. if (imageToBlur != null) {
  69065. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  69066. }
  69067. effect.setTextureFromPostProcess("circleOfConfusionSampler", circleOfConfusion);
  69068. if (scene.activeCamera) {
  69069. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  69070. }
  69071. });
  69072. return _this;
  69073. }
  69074. return DepthOfFieldBlurPostProcess;
  69075. }(BABYLON.BlurPostProcess));
  69076. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  69077. })(BABYLON || (BABYLON = {}));
  69078. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  69079. var BABYLON;
  69080. (function (BABYLON) {
  69081. /**
  69082. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  69083. */
  69084. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  69085. __extends(DepthOfFieldMergePostProcess, _super);
  69086. /**
  69087. * Creates a new instance of @see CircleOfConfusionPostProcess
  69088. * @param name The name of the effect.
  69089. * @param original The non-blurred image to be modified
  69090. * @param circleOfConfusion The circle of confusion post process that will determine how blurred each pixel should become.
  69091. * @param blurSteps Incrimental bluring post processes.
  69092. * @param options The required width/height ratio to downsize to before computing the render pass.
  69093. * @param camera The camera to apply the render pass to.
  69094. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  69095. * @param engine The engine which the post process will be applied. (default: current engine)
  69096. * @param reusable If the post process can be reused on the same frame. (default: false)
  69097. * @param textureType Type of textures used when performing the post process. (default: 0)
  69098. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  69099. */
  69100. function DepthOfFieldMergePostProcess(name, original, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  69101. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69102. if (blockCompilation === void 0) { blockCompilation = false; }
  69103. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "originalSampler", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  69104. _this.blurSteps = blurSteps;
  69105. _this.onApplyObservable.add(function (effect) {
  69106. effect.setTextureFromPostProcess("circleOfConfusionSampler", circleOfConfusion);
  69107. effect.setTextureFromPostProcess("originalSampler", original);
  69108. blurSteps.forEach(function (step, index) {
  69109. effect.setTextureFromPostProcess("blurStep" + (index + 1), step);
  69110. });
  69111. });
  69112. if (!blockCompilation) {
  69113. _this.updateEffect();
  69114. }
  69115. return _this;
  69116. }
  69117. /**
  69118. * Updates the effect with the current post process compile time values and recompiles the shader.
  69119. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  69120. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  69121. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  69122. * @param indexParameters The index parameters to be used for babylons include syntax "#include<kernelBlurVaryingDeclaration>[0..varyingCount]". (default: undefined) See usage in babylon.blurPostProcess.ts and kernelBlur.vertex.fx
  69123. * @param onCompiled Called when the shader has been compiled.
  69124. * @param onError Called if there is an error when compiling a shader.
  69125. */
  69126. DepthOfFieldMergePostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  69127. if (defines === void 0) { defines = null; }
  69128. if (uniforms === void 0) { uniforms = null; }
  69129. if (samplers === void 0) { samplers = null; }
  69130. _super.prototype.updateEffect.call(this, defines ? defines : "#define BLUR_LEVEL " + this.blurSteps.length + "\n", uniforms, samplers, indexParameters, onCompiled, onError);
  69131. };
  69132. return DepthOfFieldMergePostProcess;
  69133. }(BABYLON.PostProcess));
  69134. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  69135. })(BABYLON || (BABYLON = {}));
  69136. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  69137. var BABYLON;
  69138. (function (BABYLON) {
  69139. /**
  69140. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  69141. */
  69142. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  69143. __extends(CircleOfConfusionPostProcess, _super);
  69144. /**
  69145. * Creates a new instance of @see CircleOfConfusionPostProcess
  69146. * @param name The name of the effect.
  69147. * @param depthTexture The depth texture of the scene to compute the circle of confusion. This must be set in order for this to function but may be set after initialization if needed.
  69148. * @param options The required width/height ratio to downsize to before computing the render pass.
  69149. * @param camera The camera to apply the render pass to.
  69150. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  69151. * @param engine The engine which the post process will be applied. (default: current engine)
  69152. * @param reusable If the post process can be reused on the same frame. (default: false)
  69153. * @param textureType Type of textures used when performing the post process. (default: 0)
  69154. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  69155. */
  69156. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  69157. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69158. if (blockCompilation === void 0) { blockCompilation = false; }
  69159. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  69160. /**
  69161. * Max lens size in scene units/1000 (eg. millimeter). Standard cameras are 50mm. (default: 50) The diamater of the resulting aperture can be computed by lensSize/fStop.
  69162. */
  69163. _this.lensSize = 50;
  69164. /**
  69165. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  69166. */
  69167. _this.fStop = 1.4;
  69168. /**
  69169. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  69170. */
  69171. _this.focusDistance = 2000;
  69172. /**
  69173. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  69174. */
  69175. _this.focalLength = 50;
  69176. _this._depthTexture = null;
  69177. _this._depthTexture = depthTexture;
  69178. _this.onApplyObservable.add(function (effect) {
  69179. if (!_this._depthTexture) {
  69180. BABYLON.Tools.Warn("No depth texture set on CircleOfConfusionPostProcess");
  69181. return;
  69182. }
  69183. effect.setTexture("depthSampler", _this._depthTexture);
  69184. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  69185. var aperture = _this.lensSize / _this.fStop;
  69186. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  69187. effect.setFloat('focusDistance', _this.focusDistance);
  69188. effect.setFloat('cocPrecalculation', cocPrecalculation);
  69189. effect.setFloat2('cameraMinMaxZ', _this._depthTexture.activeCamera.minZ, _this._depthTexture.activeCamera.maxZ);
  69190. });
  69191. return _this;
  69192. }
  69193. Object.defineProperty(CircleOfConfusionPostProcess.prototype, "depthTexture", {
  69194. /**
  69195. * Depth texture to be used to compute the circle of confusion. This must be set here or in the constructor in order for the post process to function.
  69196. */
  69197. set: function (value) {
  69198. this._depthTexture = value;
  69199. },
  69200. enumerable: true,
  69201. configurable: true
  69202. });
  69203. return CircleOfConfusionPostProcess;
  69204. }(BABYLON.PostProcess));
  69205. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  69206. })(BABYLON || (BABYLON = {}));
  69207. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  69208. var BABYLON;
  69209. (function (BABYLON) {
  69210. /**
  69211. * Specifies the level of max blur that should be applied when using the depth of field effect
  69212. */
  69213. var DepthOfFieldEffectBlurLevel;
  69214. (function (DepthOfFieldEffectBlurLevel) {
  69215. /**
  69216. * Subtle blur
  69217. */
  69218. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  69219. /**
  69220. * Medium blur
  69221. */
  69222. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  69223. /**
  69224. * Large blur
  69225. */
  69226. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  69227. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  69228. ;
  69229. /**
  69230. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  69231. */
  69232. var DepthOfFieldEffect = /** @class */ (function (_super) {
  69233. __extends(DepthOfFieldEffect, _super);
  69234. /**
  69235. * Creates a new instance of @see DepthOfFieldEffect
  69236. * @param scene The scene the effect belongs to.
  69237. * @param depthTexture The depth texture of the scene to compute the circle of confusion.This must be set in order for this to function but may be set after initialization if needed.
  69238. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  69239. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  69240. */
  69241. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType, blockCompilation) {
  69242. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  69243. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  69244. if (blockCompilation === void 0) { blockCompilation = false; }
  69245. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  69246. return _this._effects;
  69247. }, true) || this;
  69248. _this._effects = [];
  69249. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  69250. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  69251. // Capture circle of confusion texture
  69252. _this._depthOfFieldPass = new BABYLON.PassPostProcess("depthOfFieldPass", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  69253. _this._depthOfFieldPass.autoClear = false;
  69254. // Create a pyramid of blurred images (eg. fullSize 1/4 blur, half size 1/2 blur, quarter size 3/4 blur, eith size 4/4 blur)
  69255. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  69256. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  69257. _this._depthOfFieldBlurY = [];
  69258. _this._depthOfFieldBlurX = [];
  69259. var blurCount = 1;
  69260. var kernelSize = 15;
  69261. switch (blurLevel) {
  69262. case DepthOfFieldEffectBlurLevel.High: {
  69263. blurCount = 3;
  69264. kernelSize = 51;
  69265. break;
  69266. }
  69267. case DepthOfFieldEffectBlurLevel.Medium: {
  69268. blurCount = 2;
  69269. kernelSize = 31;
  69270. break;
  69271. }
  69272. default: {
  69273. kernelSize = 15;
  69274. blurCount = 1;
  69275. break;
  69276. }
  69277. }
  69278. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  69279. for (var i = 0; i < blurCount; i++) {
  69280. var blurY = new BABYLON.DepthOfFieldBlurPostProcess("verticle blur", scene, new BABYLON.Vector2(0, 1.0), adjustedKernelSize, 1.0 / Math.pow(2, i), null, _this._depthOfFieldPass, i == 0 ? _this._circleOfConfusion : null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  69281. blurY.autoClear = false;
  69282. var blurX = new BABYLON.DepthOfFieldBlurPostProcess("horizontal blur", scene, new BABYLON.Vector2(1.0, 0), adjustedKernelSize, 1.0 / Math.pow(2, i), null, _this._depthOfFieldPass, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  69283. blurX.autoClear = false;
  69284. _this._depthOfFieldBlurY.push(blurY);
  69285. _this._depthOfFieldBlurX.push(blurX);
  69286. }
  69287. // Merge blurred images with original image based on circleOfConfusion
  69288. _this._depthOfFieldMerge = new BABYLON.DepthOfFieldMergePostProcess("depthOfFieldMerge", _this._circleOfConfusion, _this._depthOfFieldPass, _this._depthOfFieldBlurY.slice(1), 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  69289. _this._depthOfFieldMerge.autoClear = false;
  69290. // Set all post processes on the effect.
  69291. _this._effects = [_this._circleOfConfusion, _this._depthOfFieldPass];
  69292. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  69293. _this._effects.push(_this._depthOfFieldBlurY[i]);
  69294. _this._effects.push(_this._depthOfFieldBlurX[i]);
  69295. }
  69296. _this._effects.push(_this._depthOfFieldMerge);
  69297. return _this;
  69298. }
  69299. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  69300. get: function () {
  69301. return this._circleOfConfusion.focalLength;
  69302. },
  69303. /**
  69304. * The focal the length of the camera used in the effect
  69305. */
  69306. set: function (value) {
  69307. this._circleOfConfusion.focalLength = value;
  69308. },
  69309. enumerable: true,
  69310. configurable: true
  69311. });
  69312. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  69313. get: function () {
  69314. return this._circleOfConfusion.fStop;
  69315. },
  69316. /**
  69317. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  69318. */
  69319. set: function (value) {
  69320. this._circleOfConfusion.fStop = value;
  69321. },
  69322. enumerable: true,
  69323. configurable: true
  69324. });
  69325. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  69326. get: function () {
  69327. return this._circleOfConfusion.focusDistance;
  69328. },
  69329. /**
  69330. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  69331. */
  69332. set: function (value) {
  69333. this._circleOfConfusion.focusDistance = value;
  69334. },
  69335. enumerable: true,
  69336. configurable: true
  69337. });
  69338. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  69339. get: function () {
  69340. return this._circleOfConfusion.lensSize;
  69341. },
  69342. /**
  69343. * Max lens size in scene units/1000 (eg. millimeter). Standard cameras are 50mm. (default: 50) The diamater of the resulting aperture can be computed by lensSize/fStop.
  69344. */
  69345. set: function (value) {
  69346. this._circleOfConfusion.lensSize = value;
  69347. },
  69348. enumerable: true,
  69349. configurable: true
  69350. });
  69351. Object.defineProperty(DepthOfFieldEffect.prototype, "depthTexture", {
  69352. /**
  69353. * Depth texture to be used to compute the circle of confusion. This must be set here or in the constructor in order for the post process to function.
  69354. */
  69355. set: function (value) {
  69356. this._circleOfConfusion.depthTexture = value;
  69357. },
  69358. enumerable: true,
  69359. configurable: true
  69360. });
  69361. /**
  69362. * Disposes each of the internal effects for a given camera.
  69363. * @param camera The camera to dispose the effect on.
  69364. */
  69365. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  69366. this._depthOfFieldPass.dispose(camera);
  69367. this._circleOfConfusion.dispose(camera);
  69368. this._depthOfFieldBlurX.forEach(function (element) {
  69369. element.dispose(camera);
  69370. });
  69371. this._depthOfFieldBlurY.forEach(function (element) {
  69372. element.dispose(camera);
  69373. });
  69374. this._depthOfFieldMerge.dispose(camera);
  69375. };
  69376. /**
  69377. * Internal
  69378. */
  69379. DepthOfFieldEffect.prototype._updateEffects = function () {
  69380. for (var effect in this._effects) {
  69381. this._effects[effect].updateEffect();
  69382. }
  69383. };
  69384. /**
  69385. * Internal
  69386. * @returns if all the contained post processes are ready.
  69387. */
  69388. DepthOfFieldEffect.prototype._isReady = function () {
  69389. for (var effect in this._effects) {
  69390. if (!this._effects[effect].isReady()) {
  69391. return false;
  69392. }
  69393. }
  69394. return true;
  69395. };
  69396. return DepthOfFieldEffect;
  69397. }(BABYLON.PostProcessRenderEffect));
  69398. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  69399. })(BABYLON || (BABYLON = {}));
  69400. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  69401. var BABYLON;
  69402. (function (BABYLON) {
  69403. /**
  69404. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  69405. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  69406. */
  69407. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  69408. __extends(DefaultRenderingPipeline, _super);
  69409. /**
  69410. * @constructor
  69411. * @param {string} name - The rendering pipeline name
  69412. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  69413. * @param {any} ratio - The size of the postprocesses (0.5 means that your postprocess will have a width = canvas.width 0.5 and a height = canvas.height 0.5)
  69414. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  69415. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline
  69416. */
  69417. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  69418. if (automaticBuild === void 0) { automaticBuild = true; }
  69419. var _this = _super.call(this, scene.getEngine(), name) || this;
  69420. _this._originalCameras = [];
  69421. /**
  69422. * ID of the sharpen post process,
  69423. */
  69424. _this.SharpenPostProcessId = "SharpenPostProcessEffect";
  69425. /**
  69426. * ID of the pass post process used for bloom,
  69427. */
  69428. _this.PassPostProcessId = "PassPostProcessEffect";
  69429. /**
  69430. * ID of the highlight post process used for bloom,
  69431. */
  69432. _this.HighLightsPostProcessId = "HighLightsPostProcessEffect";
  69433. /**
  69434. * ID of the blurX post process used for bloom,
  69435. */
  69436. _this.BlurXPostProcessId = "BlurXPostProcessEffect";
  69437. /**
  69438. * ID of the blurY post process used for bloom,
  69439. */
  69440. _this.BlurYPostProcessId = "BlurYPostProcessEffect";
  69441. /**
  69442. * ID of the copy back post process used for bloom,
  69443. */
  69444. _this.CopyBackPostProcessId = "CopyBackPostProcessEffect";
  69445. /**
  69446. * ID of the image processing post process;
  69447. */
  69448. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  69449. /**
  69450. * ID of the Fast Approximate Anti-Aliasing post process;
  69451. */
  69452. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  69453. /**
  69454. * ID of the final merge post process;
  69455. */
  69456. _this.FinalMergePostProcessId = "FinalMergePostProcessEffect";
  69457. /**
  69458. * ID of the chromatic aberration post process,
  69459. */
  69460. _this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect";
  69461. /**
  69462. * Animations which can be used to tweak settings over a period of time
  69463. */
  69464. _this.animations = [];
  69465. // Values
  69466. _this._sharpenEnabled = false;
  69467. _this._bloomEnabled = false;
  69468. _this._depthOfFieldEnabled = false;
  69469. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  69470. _this._fxaaEnabled = false;
  69471. _this._msaaEnabled = false;
  69472. _this._imageProcessingEnabled = true;
  69473. _this._bloomScale = 0.6;
  69474. _this._chromaticAberrationEnabled = false;
  69475. _this._buildAllowed = true;
  69476. /**
  69477. * Specifies the size of the bloom blur kernel, relative to the final output size
  69478. */
  69479. _this.bloomKernel = 64;
  69480. /**
  69481. * Specifies the weight of the bloom in the final rendering
  69482. */
  69483. _this._bloomWeight = 0.15;
  69484. _this._prevPostProcess = null;
  69485. _this._prevPrevPostProcess = null;
  69486. _this._cameras = cameras || [];
  69487. _this._originalCameras = _this._cameras.slice();
  69488. _this._buildAllowed = automaticBuild;
  69489. // Initialize
  69490. _this._scene = scene;
  69491. var caps = _this._scene.getEngine().getCaps();
  69492. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  69493. // Misc
  69494. if (_this._hdr) {
  69495. if (caps.textureHalfFloatRender) {
  69496. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  69497. }
  69498. else if (caps.textureFloatRender) {
  69499. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  69500. }
  69501. }
  69502. else {
  69503. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  69504. }
  69505. // Attach
  69506. scene.postProcessRenderPipelineManager.addPipeline(_this);
  69507. var engine = _this._scene.getEngine();
  69508. // Create post processes before hand so they can be modified before enabled.
  69509. // Block compilation flag is set to true to avoid compilation prior to use, these will be updated on first use in build pipeline.
  69510. _this.sharpen = new BABYLON.SharpenPostProcess("sharpen", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  69511. _this._sharpenEffect = new BABYLON.PostProcessRenderEffect(engine, _this.SharpenPostProcessId, function () { return _this.sharpen; }, true);
  69512. _this.depthOfField = new BABYLON.DepthOfFieldEffect(_this._scene, null, _this._depthOfFieldBlurLevel, _this._defaultPipelineTextureType, true);
  69513. _this.chromaticAberration = new BABYLON.ChromaticAberrationPostProcess("ChromaticAberration", engine.getRenderWidth(), engine.getRenderHeight(), 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  69514. _this._chromaticAberrationEffect = new BABYLON.PostProcessRenderEffect(engine, _this.ChromaticAberrationPostProcessId, function () { return _this.chromaticAberration; }, true);
  69515. _this._buildPipeline();
  69516. return _this;
  69517. }
  69518. Object.defineProperty(DefaultRenderingPipeline.prototype, "sharpenEnabled", {
  69519. get: function () {
  69520. return this._sharpenEnabled;
  69521. },
  69522. /**
  69523. * Enable or disable the sharpen process from the pipeline
  69524. */
  69525. set: function (enabled) {
  69526. if (this._sharpenEnabled === enabled) {
  69527. return;
  69528. }
  69529. this._sharpenEnabled = enabled;
  69530. this._buildPipeline();
  69531. },
  69532. enumerable: true,
  69533. configurable: true
  69534. });
  69535. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  69536. get: function () {
  69537. return this._bloomWeight;
  69538. },
  69539. /**
  69540. * The strength of the bloom.
  69541. */
  69542. set: function (value) {
  69543. if (this._bloomWeight === value) {
  69544. return;
  69545. }
  69546. this._bloomWeight = value;
  69547. if (this._hdr && this.copyBack) {
  69548. this.copyBack.alphaConstants = new BABYLON.Color4(value, value, value, value);
  69549. }
  69550. },
  69551. enumerable: true,
  69552. configurable: true
  69553. });
  69554. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  69555. get: function () {
  69556. return this._bloomScale;
  69557. },
  69558. /**
  69559. * The scale of the bloom, lower value will provide better performance.
  69560. */
  69561. set: function (value) {
  69562. if (this._bloomScale === value) {
  69563. return;
  69564. }
  69565. this._bloomScale = value;
  69566. this._buildPipeline();
  69567. },
  69568. enumerable: true,
  69569. configurable: true
  69570. });
  69571. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  69572. get: function () {
  69573. return this._bloomEnabled;
  69574. },
  69575. /**
  69576. * Enable or disable the bloom from the pipeline
  69577. */
  69578. set: function (enabled) {
  69579. if (this._bloomEnabled === enabled) {
  69580. return;
  69581. }
  69582. this._bloomEnabled = enabled;
  69583. this._buildPipeline();
  69584. },
  69585. enumerable: true,
  69586. configurable: true
  69587. });
  69588. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  69589. /**
  69590. * If the depth of field is enabled.
  69591. */
  69592. get: function () {
  69593. return this._depthOfFieldEnabled;
  69594. },
  69595. set: function (enabled) {
  69596. if (this._depthOfFieldEnabled === enabled) {
  69597. return;
  69598. }
  69599. this._depthOfFieldEnabled = enabled;
  69600. this._buildPipeline();
  69601. },
  69602. enumerable: true,
  69603. configurable: true
  69604. });
  69605. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  69606. /**
  69607. * Blur level of the depth of field effect. (Higher blur will effect performance)
  69608. */
  69609. get: function () {
  69610. return this._depthOfFieldBlurLevel;
  69611. },
  69612. set: function (value) {
  69613. if (this._depthOfFieldBlurLevel === value) {
  69614. return;
  69615. }
  69616. this._depthOfFieldBlurLevel = value;
  69617. // recreate dof and dispose old as this setting is not dynamic
  69618. var oldDof = this.depthOfField;
  69619. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType);
  69620. this.depthOfField.focalLength = oldDof.focalLength;
  69621. this.depthOfField.focusDistance = oldDof.focusDistance;
  69622. this.depthOfField.fStop = oldDof.fStop;
  69623. this.depthOfField.lensSize = oldDof.lensSize;
  69624. for (var i = 0; i < this._cameras.length; i++) {
  69625. oldDof.disposeEffects(this._cameras[i]);
  69626. }
  69627. this._buildPipeline();
  69628. },
  69629. enumerable: true,
  69630. configurable: true
  69631. });
  69632. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  69633. get: function () {
  69634. return this._fxaaEnabled;
  69635. },
  69636. /**
  69637. * If the anti aliasing is enabled.
  69638. */
  69639. set: function (enabled) {
  69640. if (this._fxaaEnabled === enabled) {
  69641. return;
  69642. }
  69643. this._fxaaEnabled = enabled;
  69644. this._buildPipeline();
  69645. },
  69646. enumerable: true,
  69647. configurable: true
  69648. });
  69649. Object.defineProperty(DefaultRenderingPipeline.prototype, "msaaEnabled", {
  69650. get: function () {
  69651. return this._msaaEnabled;
  69652. },
  69653. /**
  69654. * If the multisample anti-aliasing is enabled.
  69655. */
  69656. set: function (enabled) {
  69657. if (this._msaaEnabled === enabled) {
  69658. return;
  69659. }
  69660. this._msaaEnabled = enabled;
  69661. this._buildPipeline();
  69662. },
  69663. enumerable: true,
  69664. configurable: true
  69665. });
  69666. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  69667. get: function () {
  69668. return this._imageProcessingEnabled;
  69669. },
  69670. /**
  69671. * If image processing is enabled.
  69672. */
  69673. set: function (enabled) {
  69674. if (this._imageProcessingEnabled === enabled) {
  69675. return;
  69676. }
  69677. this._imageProcessingEnabled = enabled;
  69678. this._buildPipeline();
  69679. },
  69680. enumerable: true,
  69681. configurable: true
  69682. });
  69683. Object.defineProperty(DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", {
  69684. get: function () {
  69685. return this._chromaticAberrationEnabled;
  69686. },
  69687. /**
  69688. * Enable or disable the chromaticAberration process from the pipeline
  69689. */
  69690. set: function (enabled) {
  69691. if (this._chromaticAberrationEnabled === enabled) {
  69692. return;
  69693. }
  69694. this._chromaticAberrationEnabled = enabled;
  69695. this._buildPipeline();
  69696. },
  69697. enumerable: true,
  69698. configurable: true
  69699. });
  69700. /**
  69701. * Force the compilation of the entire pipeline.
  69702. */
  69703. DefaultRenderingPipeline.prototype.prepare = function () {
  69704. var previousState = this._buildAllowed;
  69705. this._buildAllowed = true;
  69706. this._buildPipeline();
  69707. this._buildAllowed = previousState;
  69708. };
  69709. DefaultRenderingPipeline.prototype._setAutoClearAndTextureSharing = function (postProcess, skipTextureSharing) {
  69710. if (skipTextureSharing === void 0) { skipTextureSharing = false; }
  69711. if (this._prevPostProcess && this._prevPostProcess.autoClear) {
  69712. postProcess.autoClear = false;
  69713. }
  69714. else {
  69715. postProcess.autoClear = true;
  69716. }
  69717. if (!skipTextureSharing) {
  69718. if (this._prevPrevPostProcess) {
  69719. postProcess.shareOutputWith(this._prevPrevPostProcess);
  69720. }
  69721. else {
  69722. postProcess.useOwnOutput();
  69723. }
  69724. if (this._prevPostProcess) {
  69725. this._prevPrevPostProcess = this._prevPostProcess;
  69726. }
  69727. this._prevPostProcess = postProcess;
  69728. }
  69729. };
  69730. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  69731. var _this = this;
  69732. if (!this._buildAllowed) {
  69733. return;
  69734. }
  69735. var engine = this._scene.getEngine();
  69736. this._disposePostProcesses();
  69737. if (this._cameras !== null) {
  69738. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  69739. // get back cameras to be used to reattach pipeline
  69740. this._cameras = this._originalCameras.slice();
  69741. }
  69742. this._reset();
  69743. this._prevPostProcess = null;
  69744. this._prevPrevPostProcess = null;
  69745. if (this.sharpenEnabled) {
  69746. if (!this.sharpen.isReady()) {
  69747. this.sharpen.updateEffect();
  69748. }
  69749. this.addEffect(this._sharpenEffect);
  69750. this._setAutoClearAndTextureSharing(this.sharpen);
  69751. }
  69752. if (this.depthOfFieldEnabled) {
  69753. var depthTexture = this._scene.enableDepthRenderer(this._cameras[0]).getDepthMap();
  69754. this.depthOfField.depthTexture = depthTexture;
  69755. if (!this.depthOfField._isReady()) {
  69756. this.depthOfField._updateEffects();
  69757. }
  69758. this.addEffect(this.depthOfField);
  69759. this._setAutoClearAndTextureSharing(this.depthOfField._depthOfFieldMerge);
  69760. }
  69761. if (this.bloomEnabled) {
  69762. this.pass = new BABYLON.PassPostProcess("sceneRenderTarget", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  69763. this._setAutoClearAndTextureSharing(this.pass, true);
  69764. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.PassPostProcessId, function () { return _this.pass; }, true));
  69765. if (!this._hdr) {
  69766. this.highlights = new BABYLON.HighlightsPostProcess("highlights", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  69767. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.HighLightsPostProcessId, function () { return _this.highlights; }, true));
  69768. this.highlights.autoClear = false;
  69769. this.highlights.alwaysForcePOT = true;
  69770. }
  69771. this.blurX = new BABYLON.BlurPostProcess("horizontal blur", new BABYLON.Vector2(1.0, 0), 10.0, this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  69772. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurXPostProcessId, function () { return _this.blurX; }, true));
  69773. this.blurX.alwaysForcePOT = true;
  69774. this.blurX.autoClear = false;
  69775. this.blurX.onActivateObservable.add(function () {
  69776. var dw = _this.blurX.width / engine.getRenderWidth(true);
  69777. _this.blurX.kernel = _this.bloomKernel * dw;
  69778. });
  69779. this.blurY = new BABYLON.BlurPostProcess("vertical blur", new BABYLON.Vector2(0, 1.0), 10.0, this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  69780. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurYPostProcessId, function () { return _this.blurY; }, true));
  69781. this.blurY.alwaysForcePOT = true;
  69782. this.blurY.autoClear = false;
  69783. this.blurY.onActivateObservable.add(function () {
  69784. var dh = _this.blurY.height / engine.getRenderHeight(true);
  69785. _this.blurY.kernel = _this.bloomKernel * dh;
  69786. });
  69787. this.copyBack = new BABYLON.PassPostProcess("bloomBlendBlit", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  69788. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.CopyBackPostProcessId, function () { return _this.copyBack; }, true));
  69789. this.copyBack.alwaysForcePOT = true;
  69790. if (this._hdr) {
  69791. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_INTERPOLATE;
  69792. var w = this.bloomWeight;
  69793. this.copyBack.alphaConstants = new BABYLON.Color4(w, w, w, w);
  69794. }
  69795. else {
  69796. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_SCREENMODE;
  69797. }
  69798. this.copyBack.autoClear = false;
  69799. }
  69800. if (this._imageProcessingEnabled) {
  69801. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  69802. if (this._hdr) {
  69803. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  69804. }
  69805. else {
  69806. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  69807. }
  69808. }
  69809. if (this._hdr && this.imageProcessing) {
  69810. this.finalMerge = this.imageProcessing;
  69811. }
  69812. else {
  69813. this.finalMerge = new BABYLON.PassPostProcess("finalMerge", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  69814. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FinalMergePostProcessId, function () { return _this.finalMerge; }, true));
  69815. this._setAutoClearAndTextureSharing(this.finalMerge, true);
  69816. this.finalMerge.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  69817. }
  69818. if (this.bloomEnabled) {
  69819. if (this._hdr) {
  69820. this.copyBack.shareOutputWith(this.blurX);
  69821. if (this.imageProcessing) {
  69822. this.imageProcessing.shareOutputWith(this.pass);
  69823. this.imageProcessing.autoClear = false;
  69824. }
  69825. else {
  69826. this.finalMerge.shareOutputWith(this.pass);
  69827. }
  69828. }
  69829. else {
  69830. this.finalMerge.shareOutputWith(this.pass);
  69831. }
  69832. }
  69833. if (this.fxaaEnabled) {
  69834. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  69835. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  69836. this._setAutoClearAndTextureSharing(this.fxaa);
  69837. }
  69838. if (this.chromaticAberrationEnabled) {
  69839. if (!this.chromaticAberration.isReady()) {
  69840. this.chromaticAberration.updateEffect();
  69841. }
  69842. this.addEffect(this._chromaticAberrationEffect);
  69843. this._setAutoClearAndTextureSharing(this.chromaticAberration);
  69844. }
  69845. if (this._cameras !== null) {
  69846. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  69847. }
  69848. if (this.msaaEnabled) {
  69849. if (!this._enableMSAAOnFirstPostProcess()) {
  69850. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  69851. }
  69852. }
  69853. };
  69854. DefaultRenderingPipeline.prototype._disposePostProcesses = function (disposeNonRecreated) {
  69855. if (disposeNonRecreated === void 0) { disposeNonRecreated = false; }
  69856. for (var i = 0; i < this._cameras.length; i++) {
  69857. var camera = this._cameras[i];
  69858. if (this.pass) {
  69859. this.pass.dispose(camera);
  69860. }
  69861. if (this.highlights) {
  69862. this.highlights.dispose(camera);
  69863. }
  69864. if (this.blurX) {
  69865. this.blurX.dispose(camera);
  69866. }
  69867. if (this.blurY) {
  69868. this.blurY.dispose(camera);
  69869. }
  69870. if (this.copyBack) {
  69871. this.copyBack.dispose(camera);
  69872. }
  69873. if (this.imageProcessing) {
  69874. this.imageProcessing.dispose(camera);
  69875. }
  69876. if (this.fxaa) {
  69877. this.fxaa.dispose(camera);
  69878. }
  69879. if (this.finalMerge) {
  69880. this.finalMerge.dispose(camera);
  69881. }
  69882. // These are created in the constructor and should not be disposed on every pipeline change
  69883. if (disposeNonRecreated) {
  69884. if (this.sharpen) {
  69885. this.sharpen.dispose(camera);
  69886. }
  69887. if (this.depthOfField) {
  69888. this.depthOfField.disposeEffects(camera);
  69889. }
  69890. if (this.chromaticAberration) {
  69891. this.chromaticAberration.dispose(camera);
  69892. }
  69893. }
  69894. }
  69895. this.pass = null;
  69896. this.highlights = null;
  69897. this.blurX = null;
  69898. this.blurY = null;
  69899. this.copyBack = null;
  69900. this.imageProcessing = null;
  69901. this.fxaa = null;
  69902. this.finalMerge = null;
  69903. if (disposeNonRecreated) {
  69904. this.sharpen = null;
  69905. this.depthOfField = null;
  69906. this.chromaticAberration = null;
  69907. }
  69908. };
  69909. /**
  69910. * Dispose of the pipeline and stop all post processes
  69911. */
  69912. DefaultRenderingPipeline.prototype.dispose = function () {
  69913. this._disposePostProcesses(true);
  69914. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  69915. _super.prototype.dispose.call(this);
  69916. };
  69917. /**
  69918. * Serialize the rendering pipeline (Used when exporting)
  69919. * @returns the serialized object
  69920. */
  69921. DefaultRenderingPipeline.prototype.serialize = function () {
  69922. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  69923. serializationObject.customType = "DefaultRenderingPipeline";
  69924. return serializationObject;
  69925. };
  69926. /**
  69927. * Parse the serialized pipeline
  69928. * @param source Source pipeline.
  69929. * @param scene The scene to load the pipeline to.
  69930. * @param rootUrl The URL of the serialized pipeline.
  69931. * @returns An instantiated pipeline from the serialized object.
  69932. */
  69933. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  69934. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  69935. };
  69936. __decorate([
  69937. BABYLON.serialize()
  69938. ], DefaultRenderingPipeline.prototype, "sharpenEnabled", null);
  69939. __decorate([
  69940. BABYLON.serialize()
  69941. ], DefaultRenderingPipeline.prototype, "bloomKernel", void 0);
  69942. __decorate([
  69943. BABYLON.serialize()
  69944. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  69945. __decorate([
  69946. BABYLON.serialize()
  69947. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  69948. __decorate([
  69949. BABYLON.serialize()
  69950. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  69951. __decorate([
  69952. BABYLON.serialize()
  69953. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  69954. __decorate([
  69955. BABYLON.serialize()
  69956. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  69957. __decorate([
  69958. BABYLON.serialize()
  69959. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  69960. __decorate([
  69961. BABYLON.serialize()
  69962. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  69963. __decorate([
  69964. BABYLON.serialize()
  69965. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  69966. __decorate([
  69967. BABYLON.serialize()
  69968. ], DefaultRenderingPipeline.prototype, "msaaEnabled", null);
  69969. __decorate([
  69970. BABYLON.serialize()
  69971. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  69972. __decorate([
  69973. BABYLON.serialize()
  69974. ], DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", null);
  69975. return DefaultRenderingPipeline;
  69976. }(BABYLON.PostProcessRenderPipeline));
  69977. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  69978. })(BABYLON || (BABYLON = {}));
  69979. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  69980. var BABYLON;
  69981. (function (BABYLON) {
  69982. /**
  69983. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  69984. */
  69985. var GeometryBufferRenderer = /** @class */ (function () {
  69986. /**
  69987. * Creates a new G Buffer for the scene. @see GeometryBufferRenderer
  69988. * @param scene The scene the buffer belongs to
  69989. * @param ratio How big is the buffer related to the main canvas.
  69990. */
  69991. function GeometryBufferRenderer(scene, ratio) {
  69992. if (ratio === void 0) { ratio = 1; }
  69993. this._enablePosition = false;
  69994. this._scene = scene;
  69995. this._ratio = ratio;
  69996. // Render target
  69997. this._createRenderTargets();
  69998. }
  69999. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  70000. /**
  70001. * Set the render list (meshes to be rendered) used in the G buffer.
  70002. */
  70003. set: function (meshes) {
  70004. this._multiRenderTarget.renderList = meshes;
  70005. },
  70006. enumerable: true,
  70007. configurable: true
  70008. });
  70009. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  70010. /**
  70011. * Gets wether or not G buffer are supported by the running hardware.
  70012. * This requires draw buffer supports
  70013. */
  70014. get: function () {
  70015. return this._multiRenderTarget.isSupported;
  70016. },
  70017. enumerable: true,
  70018. configurable: true
  70019. });
  70020. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  70021. /**
  70022. * Gets wether or not position are enabled for the G buffer.
  70023. */
  70024. get: function () {
  70025. return this._enablePosition;
  70026. },
  70027. /**
  70028. * Sets wether or not position are enabled for the G buffer.
  70029. */
  70030. set: function (enable) {
  70031. this._enablePosition = enable;
  70032. this.dispose();
  70033. this._createRenderTargets();
  70034. },
  70035. enumerable: true,
  70036. configurable: true
  70037. });
  70038. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  70039. /**
  70040. * Gets the scene associated with the buffer.
  70041. */
  70042. get: function () {
  70043. return this._scene;
  70044. },
  70045. enumerable: true,
  70046. configurable: true
  70047. });
  70048. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  70049. /**
  70050. * Gets the ratio used by the buffer during its creation.
  70051. * How big is the buffer related to the main canvas.
  70052. */
  70053. get: function () {
  70054. return this._ratio;
  70055. },
  70056. enumerable: true,
  70057. configurable: true
  70058. });
  70059. /**
  70060. * Checks wether everything is ready to render a submesh to the G buffer.
  70061. * @param subMesh the submesh to check readiness for
  70062. * @param useInstances is the mesh drawn using instance or not
  70063. * @returns true if ready otherwise false
  70064. */
  70065. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  70066. var material = subMesh.getMaterial();
  70067. if (material && material.disableDepthWrite) {
  70068. return false;
  70069. }
  70070. var defines = [];
  70071. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  70072. var mesh = subMesh.getMesh();
  70073. // Alpha test
  70074. if (material && material.needAlphaTesting()) {
  70075. defines.push("#define ALPHATEST");
  70076. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  70077. attribs.push(BABYLON.VertexBuffer.UVKind);
  70078. defines.push("#define UV1");
  70079. }
  70080. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  70081. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  70082. defines.push("#define UV2");
  70083. }
  70084. }
  70085. // Buffers
  70086. if (this._enablePosition) {
  70087. defines.push("#define POSITION");
  70088. }
  70089. // Bones
  70090. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  70091. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  70092. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  70093. if (mesh.numBoneInfluencers > 4) {
  70094. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  70095. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  70096. }
  70097. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  70098. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  70099. }
  70100. else {
  70101. defines.push("#define NUM_BONE_INFLUENCERS 0");
  70102. }
  70103. // Instances
  70104. if (useInstances) {
  70105. defines.push("#define INSTANCES");
  70106. attribs.push("world0");
  70107. attribs.push("world1");
  70108. attribs.push("world2");
  70109. attribs.push("world3");
  70110. }
  70111. // Get correct effect
  70112. var join = defines.join("\n");
  70113. if (this._cachedDefines !== join) {
  70114. this._cachedDefines = join;
  70115. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  70116. }
  70117. return this._effect.isReady();
  70118. };
  70119. /**
  70120. * Gets the current underlying G Buffer.
  70121. * @returns the buffer
  70122. */
  70123. GeometryBufferRenderer.prototype.getGBuffer = function () {
  70124. return this._multiRenderTarget;
  70125. };
  70126. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  70127. /**
  70128. * Gets the number of samples used to render the buffer (anti aliasing).
  70129. */
  70130. get: function () {
  70131. return this._multiRenderTarget.samples;
  70132. },
  70133. /**
  70134. * Sets the number of samples used to render the buffer (anti aliasing).
  70135. */
  70136. set: function (value) {
  70137. this._multiRenderTarget.samples = value;
  70138. },
  70139. enumerable: true,
  70140. configurable: true
  70141. });
  70142. /**
  70143. * Disposes the renderer and frees up associated resources.
  70144. */
  70145. GeometryBufferRenderer.prototype.dispose = function () {
  70146. this.getGBuffer().dispose();
  70147. };
  70148. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  70149. var _this = this;
  70150. var engine = this._scene.getEngine();
  70151. var count = this._enablePosition ? 3 : 2;
  70152. this._multiRenderTarget = new BABYLON.MultiRenderTarget("gBuffer", { width: engine.getRenderWidth() * this._ratio, height: engine.getRenderHeight() * this._ratio }, count, this._scene, { generateMipMaps: false, generateDepthTexture: true, defaultType: BABYLON.Engine.TEXTURETYPE_FLOAT });
  70153. if (!this.isSupported) {
  70154. return;
  70155. }
  70156. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70157. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70158. this._multiRenderTarget.refreshRate = 1;
  70159. this._multiRenderTarget.renderParticles = false;
  70160. this._multiRenderTarget.renderList = null;
  70161. // set default depth value to 1.0 (far away)
  70162. this._multiRenderTarget.onClearObservable.add(function (engine) {
  70163. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  70164. });
  70165. // Custom render function
  70166. var renderSubMesh = function (subMesh) {
  70167. var mesh = subMesh.getRenderingMesh();
  70168. var scene = _this._scene;
  70169. var engine = scene.getEngine();
  70170. var material = subMesh.getMaterial();
  70171. if (!material) {
  70172. return;
  70173. }
  70174. // Culling
  70175. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  70176. // Managing instances
  70177. var batch = mesh._getInstancesRenderList(subMesh._id);
  70178. if (batch.mustReturn) {
  70179. return;
  70180. }
  70181. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  70182. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  70183. engine.enableEffect(_this._effect);
  70184. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  70185. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  70186. _this._effect.setMatrix("view", scene.getViewMatrix());
  70187. // Alpha test
  70188. if (material && material.needAlphaTesting()) {
  70189. var alphaTexture = material.getAlphaTestTexture();
  70190. if (alphaTexture) {
  70191. _this._effect.setTexture("diffuseSampler", alphaTexture);
  70192. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  70193. }
  70194. }
  70195. // Bones
  70196. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  70197. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  70198. }
  70199. // Draw
  70200. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  70201. }
  70202. };
  70203. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  70204. var index;
  70205. if (depthOnlySubMeshes.length) {
  70206. engine.setColorWrite(false);
  70207. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  70208. renderSubMesh(depthOnlySubMeshes.data[index]);
  70209. }
  70210. engine.setColorWrite(true);
  70211. }
  70212. for (index = 0; index < opaqueSubMeshes.length; index++) {
  70213. renderSubMesh(opaqueSubMeshes.data[index]);
  70214. }
  70215. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  70216. renderSubMesh(alphaTestSubMeshes.data[index]);
  70217. }
  70218. };
  70219. };
  70220. return GeometryBufferRenderer;
  70221. }());
  70222. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  70223. })(BABYLON || (BABYLON = {}));
  70224. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  70225. var BABYLON;
  70226. (function (BABYLON) {
  70227. var RefractionPostProcess = /** @class */ (function (_super) {
  70228. __extends(RefractionPostProcess, _super);
  70229. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  70230. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  70231. _this.color = color;
  70232. _this.depth = depth;
  70233. _this.colorLevel = colorLevel;
  70234. _this._ownRefractionTexture = true;
  70235. _this.onActivateObservable.add(function (cam) {
  70236. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  70237. });
  70238. _this.onApplyObservable.add(function (effect) {
  70239. effect.setColor3("baseColor", _this.color);
  70240. effect.setFloat("depth", _this.depth);
  70241. effect.setFloat("colorLevel", _this.colorLevel);
  70242. effect.setTexture("refractionSampler", _this._refTexture);
  70243. });
  70244. return _this;
  70245. }
  70246. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  70247. /**
  70248. * Gets or sets the refraction texture
  70249. * Please note that you are responsible for disposing the texture if you set it manually
  70250. */
  70251. get: function () {
  70252. return this._refTexture;
  70253. },
  70254. set: function (value) {
  70255. if (this._refTexture && this._ownRefractionTexture) {
  70256. this._refTexture.dispose();
  70257. }
  70258. this._refTexture = value;
  70259. this._ownRefractionTexture = false;
  70260. },
  70261. enumerable: true,
  70262. configurable: true
  70263. });
  70264. // Methods
  70265. RefractionPostProcess.prototype.dispose = function (camera) {
  70266. if (this._refTexture && this._ownRefractionTexture) {
  70267. this._refTexture.dispose();
  70268. this._refTexture = null;
  70269. }
  70270. _super.prototype.dispose.call(this, camera);
  70271. };
  70272. return RefractionPostProcess;
  70273. }(BABYLON.PostProcess));
  70274. BABYLON.RefractionPostProcess = RefractionPostProcess;
  70275. })(BABYLON || (BABYLON = {}));
  70276. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  70277. var BABYLON;
  70278. (function (BABYLON) {
  70279. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  70280. __extends(BlackAndWhitePostProcess, _super);
  70281. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  70282. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  70283. _this.degree = 1;
  70284. _this.onApplyObservable.add(function (effect) {
  70285. effect.setFloat("degree", _this.degree);
  70286. });
  70287. return _this;
  70288. }
  70289. return BlackAndWhitePostProcess;
  70290. }(BABYLON.PostProcess));
  70291. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  70292. })(BABYLON || (BABYLON = {}));
  70293. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  70294. var BABYLON;
  70295. (function (BABYLON) {
  70296. /**
  70297. * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the
  70298. * input texture to perform effects such as edge detection or sharpening
  70299. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  70300. */
  70301. var ConvolutionPostProcess = /** @class */ (function (_super) {
  70302. __extends(ConvolutionPostProcess, _super);
  70303. /**
  70304. * Creates a new instance of @see ConvolutionPostProcess
  70305. * @param name The name of the effect.
  70306. * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied
  70307. * @param options The required width/height ratio to downsize to before computing the render pass.
  70308. * @param camera The camera to apply the render pass to.
  70309. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  70310. * @param engine The engine which the post process will be applied. (default: current engine)
  70311. * @param reusable If the post process can be reused on the same frame. (default: false)
  70312. * @param textureType Type of textures used when performing the post process. (default: 0)
  70313. */
  70314. function ConvolutionPostProcess(name, /** Array of 9 values corrisponding to the 3x3 kernel to be applied */ kernel, options, camera, samplingMode, engine, reusable, textureType) {
  70315. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  70316. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  70317. _this.kernel = kernel;
  70318. _this.onApply = function (effect) {
  70319. effect.setFloat2("screenSize", _this.width, _this.height);
  70320. effect.setArray("kernel", _this.kernel);
  70321. };
  70322. return _this;
  70323. }
  70324. // Statics
  70325. /**
  70326. * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  70327. */
  70328. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  70329. /**
  70330. * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  70331. */
  70332. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  70333. /**
  70334. * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  70335. */
  70336. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  70337. /**
  70338. * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  70339. */
  70340. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  70341. /**
  70342. * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  70343. */
  70344. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  70345. /**
  70346. * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  70347. */
  70348. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  70349. return ConvolutionPostProcess;
  70350. }(BABYLON.PostProcess));
  70351. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  70352. })(BABYLON || (BABYLON = {}));
  70353. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  70354. var BABYLON;
  70355. (function (BABYLON) {
  70356. var FilterPostProcess = /** @class */ (function (_super) {
  70357. __extends(FilterPostProcess, _super);
  70358. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  70359. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  70360. _this.kernelMatrix = kernelMatrix;
  70361. _this.onApply = function (effect) {
  70362. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  70363. };
  70364. return _this;
  70365. }
  70366. return FilterPostProcess;
  70367. }(BABYLON.PostProcess));
  70368. BABYLON.FilterPostProcess = FilterPostProcess;
  70369. })(BABYLON || (BABYLON = {}));
  70370. //# sourceMappingURL=babylon.filterPostProcess.js.map
  70371. var BABYLON;
  70372. (function (BABYLON) {
  70373. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  70374. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  70375. __extends(VolumetricLightScatteringPostProcess, _super);
  70376. /**
  70377. * @constructor
  70378. * @param {string} name - The post-process name
  70379. * @param {any} ratio - The size of the post-process and/or internal pass (0.5 means that your postprocess will have a width = canvas.width 0.5 and a height = canvas.height 0.5)
  70380. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  70381. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  70382. * @param {number} samples - The post-process quality, default 100
  70383. * @param {number} samplingMode - The post-process filtering mode
  70384. * @param {BABYLON.Engine} engine - The babylon engine
  70385. * @param {boolean} reusable - If the post-process is reusable
  70386. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  70387. */
  70388. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  70389. if (samples === void 0) { samples = 100; }
  70390. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  70391. var _this = _super.call(this, name, "volumetricLightScattering", ["decay", "exposure", "weight", "meshPositionOnScreen", "density"], ["lightScatteringSampler"], ratio.postProcessRatio || ratio, camera, samplingMode, engine, reusable, "#define NUM_SAMPLES " + samples) || this;
  70392. _this._screenCoordinates = BABYLON.Vector2.Zero();
  70393. /**
  70394. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  70395. * @type {Vector3}
  70396. */
  70397. _this.customMeshPosition = BABYLON.Vector3.Zero();
  70398. /**
  70399. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  70400. * @type {boolean}
  70401. */
  70402. _this.useCustomMeshPosition = false;
  70403. /**
  70404. * If the post-process should inverse the light scattering direction
  70405. * @type {boolean}
  70406. */
  70407. _this.invert = true;
  70408. /**
  70409. * Array containing the excluded meshes not rendered in the internal pass
  70410. */
  70411. _this.excludedMeshes = new Array();
  70412. /**
  70413. * Controls the overall intensity of the post-process
  70414. * @type {number}
  70415. */
  70416. _this.exposure = 0.3;
  70417. /**
  70418. * Dissipates each sample's contribution in range [0, 1]
  70419. * @type {number}
  70420. */
  70421. _this.decay = 0.96815;
  70422. /**
  70423. * Controls the overall intensity of each sample
  70424. * @type {number}
  70425. */
  70426. _this.weight = 0.58767;
  70427. /**
  70428. * Controls the density of each sample
  70429. * @type {number}
  70430. */
  70431. _this.density = 0.926;
  70432. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  70433. engine = scene.getEngine();
  70434. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  70435. // Configure mesh
  70436. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  70437. // Configure
  70438. _this._createPass(scene, ratio.passRatio || ratio);
  70439. _this.onActivate = function (camera) {
  70440. if (!_this.isSupported) {
  70441. _this.dispose(camera);
  70442. }
  70443. _this.onActivate = null;
  70444. };
  70445. _this.onApplyObservable.add(function (effect) {
  70446. _this._updateMeshScreenCoordinates(scene);
  70447. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  70448. effect.setFloat("exposure", _this.exposure);
  70449. effect.setFloat("decay", _this.decay);
  70450. effect.setFloat("weight", _this.weight);
  70451. effect.setFloat("density", _this.density);
  70452. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  70453. });
  70454. return _this;
  70455. }
  70456. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  70457. get: function () {
  70458. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  70459. return false;
  70460. },
  70461. set: function (useDiffuseColor) {
  70462. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  70463. },
  70464. enumerable: true,
  70465. configurable: true
  70466. });
  70467. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  70468. return "VolumetricLightScatteringPostProcess";
  70469. };
  70470. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  70471. var mesh = subMesh.getMesh();
  70472. // Render this.mesh as default
  70473. if (mesh === this.mesh && mesh.material) {
  70474. return mesh.material.isReady(mesh);
  70475. }
  70476. var defines = [];
  70477. var attribs = [BABYLON.VertexBuffer.PositionKind];
  70478. var material = subMesh.getMaterial();
  70479. // Alpha test
  70480. if (material) {
  70481. if (material.needAlphaTesting()) {
  70482. defines.push("#define ALPHATEST");
  70483. }
  70484. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  70485. attribs.push(BABYLON.VertexBuffer.UVKind);
  70486. defines.push("#define UV1");
  70487. }
  70488. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  70489. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  70490. defines.push("#define UV2");
  70491. }
  70492. }
  70493. // Bones
  70494. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  70495. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  70496. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  70497. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  70498. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  70499. }
  70500. else {
  70501. defines.push("#define NUM_BONE_INFLUENCERS 0");
  70502. }
  70503. // Instances
  70504. if (useInstances) {
  70505. defines.push("#define INSTANCES");
  70506. attribs.push("world0");
  70507. attribs.push("world1");
  70508. attribs.push("world2");
  70509. attribs.push("world3");
  70510. }
  70511. // Get correct effect
  70512. var join = defines.join("\n");
  70513. if (this._cachedDefines !== join) {
  70514. this._cachedDefines = join;
  70515. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  70516. }
  70517. return this._volumetricLightScatteringPass.isReady();
  70518. };
  70519. /**
  70520. * Sets the new light position for light scattering effect
  70521. * @param {BABYLON.Vector3} The new custom light position
  70522. */
  70523. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  70524. this.customMeshPosition = position;
  70525. };
  70526. /**
  70527. * Returns the light position for light scattering effect
  70528. * @return {BABYLON.Vector3} The custom light position
  70529. */
  70530. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  70531. return this.customMeshPosition;
  70532. };
  70533. /**
  70534. * Disposes the internal assets and detaches the post-process from the camera
  70535. */
  70536. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  70537. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  70538. if (rttIndex !== -1) {
  70539. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  70540. }
  70541. this._volumetricLightScatteringRTT.dispose();
  70542. _super.prototype.dispose.call(this, camera);
  70543. };
  70544. /**
  70545. * Returns the render target texture used by the post-process
  70546. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  70547. */
  70548. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  70549. return this._volumetricLightScatteringRTT;
  70550. };
  70551. // Private methods
  70552. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  70553. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  70554. return true;
  70555. }
  70556. return false;
  70557. };
  70558. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  70559. var _this = this;
  70560. var engine = scene.getEngine();
  70561. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  70562. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70563. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70564. this._volumetricLightScatteringRTT.renderList = null;
  70565. this._volumetricLightScatteringRTT.renderParticles = false;
  70566. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  70567. var camera = this.getCamera();
  70568. if (camera) {
  70569. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  70570. }
  70571. else {
  70572. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  70573. }
  70574. // Custom render function for submeshes
  70575. var renderSubMesh = function (subMesh) {
  70576. var mesh = subMesh.getRenderingMesh();
  70577. if (_this._meshExcluded(mesh)) {
  70578. return;
  70579. }
  70580. var material = subMesh.getMaterial();
  70581. if (!material) {
  70582. return;
  70583. }
  70584. var scene = mesh.getScene();
  70585. var engine = scene.getEngine();
  70586. // Culling
  70587. engine.setState(material.backFaceCulling);
  70588. // Managing instances
  70589. var batch = mesh._getInstancesRenderList(subMesh._id);
  70590. if (batch.mustReturn) {
  70591. return;
  70592. }
  70593. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  70594. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  70595. var effect = _this._volumetricLightScatteringPass;
  70596. if (mesh === _this.mesh) {
  70597. if (subMesh.effect) {
  70598. effect = subMesh.effect;
  70599. }
  70600. else {
  70601. effect = material.getEffect();
  70602. }
  70603. }
  70604. engine.enableEffect(effect);
  70605. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  70606. if (mesh === _this.mesh) {
  70607. material.bind(mesh.getWorldMatrix(), mesh);
  70608. }
  70609. else {
  70610. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  70611. // Alpha test
  70612. if (material && material.needAlphaTesting()) {
  70613. var alphaTexture = material.getAlphaTestTexture();
  70614. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  70615. if (alphaTexture) {
  70616. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  70617. }
  70618. }
  70619. // Bones
  70620. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  70621. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  70622. }
  70623. }
  70624. // Draw
  70625. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  70626. }
  70627. };
  70628. // Render target texture callbacks
  70629. var savedSceneClearColor;
  70630. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  70631. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  70632. savedSceneClearColor = scene.clearColor;
  70633. scene.clearColor = sceneClearColor;
  70634. });
  70635. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  70636. scene.clearColor = savedSceneClearColor;
  70637. });
  70638. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  70639. var engine = scene.getEngine();
  70640. var index;
  70641. if (depthOnlySubMeshes.length) {
  70642. engine.setColorWrite(false);
  70643. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  70644. renderSubMesh(depthOnlySubMeshes.data[index]);
  70645. }
  70646. engine.setColorWrite(true);
  70647. }
  70648. for (index = 0; index < opaqueSubMeshes.length; index++) {
  70649. renderSubMesh(opaqueSubMeshes.data[index]);
  70650. }
  70651. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  70652. renderSubMesh(alphaTestSubMeshes.data[index]);
  70653. }
  70654. if (transparentSubMeshes.length) {
  70655. // Sort sub meshes
  70656. for (index = 0; index < transparentSubMeshes.length; index++) {
  70657. var submesh = transparentSubMeshes.data[index];
  70658. var boundingInfo = submesh.getBoundingInfo();
  70659. if (boundingInfo && scene.activeCamera) {
  70660. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  70661. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  70662. }
  70663. }
  70664. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  70665. sortedArray.sort(function (a, b) {
  70666. // Alpha index first
  70667. if (a._alphaIndex > b._alphaIndex) {
  70668. return 1;
  70669. }
  70670. if (a._alphaIndex < b._alphaIndex) {
  70671. return -1;
  70672. }
  70673. // Then distance to camera
  70674. if (a._distanceToCamera < b._distanceToCamera) {
  70675. return 1;
  70676. }
  70677. if (a._distanceToCamera > b._distanceToCamera) {
  70678. return -1;
  70679. }
  70680. return 0;
  70681. });
  70682. // Render sub meshes
  70683. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  70684. for (index = 0; index < sortedArray.length; index++) {
  70685. renderSubMesh(sortedArray[index]);
  70686. }
  70687. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  70688. }
  70689. };
  70690. };
  70691. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  70692. var transform = scene.getTransformMatrix();
  70693. var meshPosition;
  70694. if (this.useCustomMeshPosition) {
  70695. meshPosition = this.customMeshPosition;
  70696. }
  70697. else if (this.attachedNode) {
  70698. meshPosition = this.attachedNode.position;
  70699. }
  70700. else {
  70701. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  70702. }
  70703. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  70704. this._screenCoordinates.x = pos.x / this._viewPort.width;
  70705. this._screenCoordinates.y = pos.y / this._viewPort.height;
  70706. if (this.invert)
  70707. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  70708. };
  70709. // Static methods
  70710. /**
  70711. * Creates a default mesh for the Volumeric Light Scattering post-process
  70712. * @param {string} The mesh name
  70713. * @param {BABYLON.Scene} The scene where to create the mesh
  70714. * @return {BABYLON.Mesh} the default mesh
  70715. */
  70716. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  70717. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  70718. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  70719. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  70720. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  70721. mesh.material = material;
  70722. return mesh;
  70723. };
  70724. __decorate([
  70725. BABYLON.serializeAsVector3()
  70726. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  70727. __decorate([
  70728. BABYLON.serialize()
  70729. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  70730. __decorate([
  70731. BABYLON.serialize()
  70732. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  70733. __decorate([
  70734. BABYLON.serializeAsMeshReference()
  70735. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  70736. __decorate([
  70737. BABYLON.serialize()
  70738. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  70739. __decorate([
  70740. BABYLON.serialize()
  70741. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  70742. __decorate([
  70743. BABYLON.serialize()
  70744. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  70745. __decorate([
  70746. BABYLON.serialize()
  70747. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  70748. __decorate([
  70749. BABYLON.serialize()
  70750. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  70751. return VolumetricLightScatteringPostProcess;
  70752. }(BABYLON.PostProcess));
  70753. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  70754. })(BABYLON || (BABYLON = {}));
  70755. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  70756. //
  70757. // This post-process allows the modification of rendered colors by using
  70758. // a 'look-up table' (LUT). This effect is also called Color Grading.
  70759. //
  70760. // The object needs to be provided an url to a texture containing the color
  70761. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  70762. // Use an image editing software to tweak the LUT to match your needs.
  70763. //
  70764. // For an example of a color LUT, see here:
  70765. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  70766. // For explanations on color grading, see here:
  70767. // http://udn.epicgames.com/Three/ColorGrading.html
  70768. //
  70769. var BABYLON;
  70770. (function (BABYLON) {
  70771. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  70772. __extends(ColorCorrectionPostProcess, _super);
  70773. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  70774. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  70775. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  70776. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  70777. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70778. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70779. _this.onApply = function (effect) {
  70780. effect.setTexture("colorTable", _this._colorTableTexture);
  70781. };
  70782. return _this;
  70783. }
  70784. return ColorCorrectionPostProcess;
  70785. }(BABYLON.PostProcess));
  70786. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  70787. })(BABYLON || (BABYLON = {}));
  70788. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  70789. var BABYLON;
  70790. (function (BABYLON) {
  70791. var TonemappingOperator;
  70792. (function (TonemappingOperator) {
  70793. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  70794. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  70795. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  70796. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  70797. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  70798. ;
  70799. var TonemapPostProcess = /** @class */ (function (_super) {
  70800. __extends(TonemapPostProcess, _super);
  70801. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  70802. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  70803. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  70804. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  70805. _this._operator = _operator;
  70806. _this.exposureAdjustment = exposureAdjustment;
  70807. var defines = "#define ";
  70808. if (_this._operator === TonemappingOperator.Hable)
  70809. defines += "HABLE_TONEMAPPING";
  70810. else if (_this._operator === TonemappingOperator.Reinhard)
  70811. defines += "REINHARD_TONEMAPPING";
  70812. else if (_this._operator === TonemappingOperator.HejiDawson)
  70813. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  70814. else if (_this._operator === TonemappingOperator.Photographic)
  70815. defines += "PHOTOGRAPHIC_TONEMAPPING";
  70816. //sadly a second call to create the effect.
  70817. _this.updateEffect(defines);
  70818. _this.onApply = function (effect) {
  70819. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  70820. };
  70821. return _this;
  70822. }
  70823. return TonemapPostProcess;
  70824. }(BABYLON.PostProcess));
  70825. BABYLON.TonemapPostProcess = TonemapPostProcess;
  70826. })(BABYLON || (BABYLON = {}));
  70827. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  70828. var BABYLON;
  70829. (function (BABYLON) {
  70830. var DisplayPassPostProcess = /** @class */ (function (_super) {
  70831. __extends(DisplayPassPostProcess, _super);
  70832. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  70833. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  70834. }
  70835. return DisplayPassPostProcess;
  70836. }(BABYLON.PostProcess));
  70837. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  70838. })(BABYLON || (BABYLON = {}));
  70839. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  70840. var BABYLON;
  70841. (function (BABYLON) {
  70842. var HighlightsPostProcess = /** @class */ (function (_super) {
  70843. __extends(HighlightsPostProcess, _super);
  70844. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  70845. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  70846. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  70847. }
  70848. return HighlightsPostProcess;
  70849. }(BABYLON.PostProcess));
  70850. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  70851. })(BABYLON || (BABYLON = {}));
  70852. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  70853. var BABYLON;
  70854. (function (BABYLON) {
  70855. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  70856. __extends(ImageProcessingPostProcess, _super);
  70857. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  70858. if (camera === void 0) { camera = null; }
  70859. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  70860. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  70861. _this._fromLinearSpace = true;
  70862. /**
  70863. * Defines cache preventing GC.
  70864. */
  70865. _this._defines = {
  70866. IMAGEPROCESSING: false,
  70867. VIGNETTE: false,
  70868. VIGNETTEBLENDMODEMULTIPLY: false,
  70869. VIGNETTEBLENDMODEOPAQUE: false,
  70870. TONEMAPPING: false,
  70871. CONTRAST: false,
  70872. COLORCURVES: false,
  70873. COLORGRADING: false,
  70874. COLORGRADING3D: false,
  70875. FROMLINEARSPACE: false,
  70876. SAMPLER3DGREENDEPTH: false,
  70877. SAMPLER3DBGRMAP: false,
  70878. IMAGEPROCESSINGPOSTPROCESS: false,
  70879. EXPOSURE: false,
  70880. GRAIN: false,
  70881. };
  70882. // Setup the configuration as forced by the constructor. This would then not force the
  70883. // scene materials output in linear space and let untouched the default forward pass.
  70884. if (imageProcessingConfiguration) {
  70885. imageProcessingConfiguration.applyByPostProcess = true;
  70886. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  70887. // This will cause the shader to be compiled
  70888. _this.fromLinearSpace = false;
  70889. }
  70890. else {
  70891. _this._attachImageProcessingConfiguration(null, true);
  70892. _this.imageProcessingConfiguration.applyByPostProcess = true;
  70893. }
  70894. _this.onApply = function (effect) {
  70895. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  70896. };
  70897. return _this;
  70898. }
  70899. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  70900. /**
  70901. * Gets the image processing configuration used either in this material.
  70902. */
  70903. get: function () {
  70904. return this._imageProcessingConfiguration;
  70905. },
  70906. /**
  70907. * Sets the Default image processing configuration used either in the this material.
  70908. *
  70909. * If sets to null, the scene one is in use.
  70910. */
  70911. set: function (value) {
  70912. this._attachImageProcessingConfiguration(value);
  70913. },
  70914. enumerable: true,
  70915. configurable: true
  70916. });
  70917. /**
  70918. * Attaches a new image processing configuration to the PBR Material.
  70919. * @param configuration
  70920. */
  70921. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  70922. var _this = this;
  70923. if (doNotBuild === void 0) { doNotBuild = false; }
  70924. if (configuration === this._imageProcessingConfiguration) {
  70925. return;
  70926. }
  70927. // Detaches observer.
  70928. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  70929. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  70930. }
  70931. // Pick the scene configuration if needed.
  70932. if (!configuration) {
  70933. var scene = null;
  70934. var engine = this.getEngine();
  70935. var camera = this.getCamera();
  70936. if (camera) {
  70937. scene = camera.getScene();
  70938. }
  70939. else if (engine && engine.scenes) {
  70940. var scenes = engine.scenes;
  70941. scene = scenes[scenes.length - 1];
  70942. }
  70943. else {
  70944. scene = BABYLON.Engine.LastCreatedScene;
  70945. }
  70946. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  70947. }
  70948. else {
  70949. this._imageProcessingConfiguration = configuration;
  70950. }
  70951. // Attaches observer.
  70952. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  70953. _this._updateParameters();
  70954. });
  70955. // Ensure the effect will be rebuilt.
  70956. if (!doNotBuild) {
  70957. this._updateParameters();
  70958. }
  70959. };
  70960. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  70961. /**
  70962. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  70963. */
  70964. get: function () {
  70965. return this.imageProcessingConfiguration.colorCurves;
  70966. },
  70967. /**
  70968. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  70969. */
  70970. set: function (value) {
  70971. this.imageProcessingConfiguration.colorCurves = value;
  70972. },
  70973. enumerable: true,
  70974. configurable: true
  70975. });
  70976. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  70977. /**
  70978. * Gets wether the color curves effect is enabled.
  70979. */
  70980. get: function () {
  70981. return this.imageProcessingConfiguration.colorCurvesEnabled;
  70982. },
  70983. /**
  70984. * Sets wether the color curves effect is enabled.
  70985. */
  70986. set: function (value) {
  70987. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  70988. },
  70989. enumerable: true,
  70990. configurable: true
  70991. });
  70992. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  70993. /**
  70994. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  70995. */
  70996. get: function () {
  70997. return this.imageProcessingConfiguration.colorGradingTexture;
  70998. },
  70999. /**
  71000. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  71001. */
  71002. set: function (value) {
  71003. this.imageProcessingConfiguration.colorGradingTexture = value;
  71004. },
  71005. enumerable: true,
  71006. configurable: true
  71007. });
  71008. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  71009. /**
  71010. * Gets wether the color grading effect is enabled.
  71011. */
  71012. get: function () {
  71013. return this.imageProcessingConfiguration.colorGradingEnabled;
  71014. },
  71015. /**
  71016. * Gets wether the color grading effect is enabled.
  71017. */
  71018. set: function (value) {
  71019. this.imageProcessingConfiguration.colorGradingEnabled = value;
  71020. },
  71021. enumerable: true,
  71022. configurable: true
  71023. });
  71024. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  71025. /**
  71026. * Gets exposure used in the effect.
  71027. */
  71028. get: function () {
  71029. return this.imageProcessingConfiguration.exposure;
  71030. },
  71031. /**
  71032. * Sets exposure used in the effect.
  71033. */
  71034. set: function (value) {
  71035. this.imageProcessingConfiguration.exposure = value;
  71036. },
  71037. enumerable: true,
  71038. configurable: true
  71039. });
  71040. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  71041. /**
  71042. * Gets wether tonemapping is enabled or not.
  71043. */
  71044. get: function () {
  71045. return this._imageProcessingConfiguration.toneMappingEnabled;
  71046. },
  71047. /**
  71048. * Sets wether tonemapping is enabled or not
  71049. */
  71050. set: function (value) {
  71051. this._imageProcessingConfiguration.toneMappingEnabled = value;
  71052. },
  71053. enumerable: true,
  71054. configurable: true
  71055. });
  71056. ;
  71057. ;
  71058. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  71059. /**
  71060. * Gets contrast used in the effect.
  71061. */
  71062. get: function () {
  71063. return this.imageProcessingConfiguration.contrast;
  71064. },
  71065. /**
  71066. * Sets contrast used in the effect.
  71067. */
  71068. set: function (value) {
  71069. this.imageProcessingConfiguration.contrast = value;
  71070. },
  71071. enumerable: true,
  71072. configurable: true
  71073. });
  71074. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  71075. /**
  71076. * Gets Vignette stretch size.
  71077. */
  71078. get: function () {
  71079. return this.imageProcessingConfiguration.vignetteStretch;
  71080. },
  71081. /**
  71082. * Sets Vignette stretch size.
  71083. */
  71084. set: function (value) {
  71085. this.imageProcessingConfiguration.vignetteStretch = value;
  71086. },
  71087. enumerable: true,
  71088. configurable: true
  71089. });
  71090. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  71091. /**
  71092. * Gets Vignette centre X Offset.
  71093. */
  71094. get: function () {
  71095. return this.imageProcessingConfiguration.vignetteCentreX;
  71096. },
  71097. /**
  71098. * Sets Vignette centre X Offset.
  71099. */
  71100. set: function (value) {
  71101. this.imageProcessingConfiguration.vignetteCentreX = value;
  71102. },
  71103. enumerable: true,
  71104. configurable: true
  71105. });
  71106. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  71107. /**
  71108. * Gets Vignette centre Y Offset.
  71109. */
  71110. get: function () {
  71111. return this.imageProcessingConfiguration.vignetteCentreY;
  71112. },
  71113. /**
  71114. * Sets Vignette centre Y Offset.
  71115. */
  71116. set: function (value) {
  71117. this.imageProcessingConfiguration.vignetteCentreY = value;
  71118. },
  71119. enumerable: true,
  71120. configurable: true
  71121. });
  71122. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  71123. /**
  71124. * Gets Vignette weight or intensity of the vignette effect.
  71125. */
  71126. get: function () {
  71127. return this.imageProcessingConfiguration.vignetteWeight;
  71128. },
  71129. /**
  71130. * Sets Vignette weight or intensity of the vignette effect.
  71131. */
  71132. set: function (value) {
  71133. this.imageProcessingConfiguration.vignetteWeight = value;
  71134. },
  71135. enumerable: true,
  71136. configurable: true
  71137. });
  71138. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  71139. /**
  71140. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  71141. * if vignetteEnabled is set to true.
  71142. */
  71143. get: function () {
  71144. return this.imageProcessingConfiguration.vignetteColor;
  71145. },
  71146. /**
  71147. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  71148. * if vignetteEnabled is set to true.
  71149. */
  71150. set: function (value) {
  71151. this.imageProcessingConfiguration.vignetteColor = value;
  71152. },
  71153. enumerable: true,
  71154. configurable: true
  71155. });
  71156. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  71157. /**
  71158. * Gets Camera field of view used by the Vignette effect.
  71159. */
  71160. get: function () {
  71161. return this.imageProcessingConfiguration.vignetteCameraFov;
  71162. },
  71163. /**
  71164. * Sets Camera field of view used by the Vignette effect.
  71165. */
  71166. set: function (value) {
  71167. this.imageProcessingConfiguration.vignetteCameraFov = value;
  71168. },
  71169. enumerable: true,
  71170. configurable: true
  71171. });
  71172. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  71173. /**
  71174. * Gets the vignette blend mode allowing different kind of effect.
  71175. */
  71176. get: function () {
  71177. return this.imageProcessingConfiguration.vignetteBlendMode;
  71178. },
  71179. /**
  71180. * Sets the vignette blend mode allowing different kind of effect.
  71181. */
  71182. set: function (value) {
  71183. this.imageProcessingConfiguration.vignetteBlendMode = value;
  71184. },
  71185. enumerable: true,
  71186. configurable: true
  71187. });
  71188. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  71189. /**
  71190. * Gets wether the vignette effect is enabled.
  71191. */
  71192. get: function () {
  71193. return this.imageProcessingConfiguration.vignetteEnabled;
  71194. },
  71195. /**
  71196. * Sets wether the vignette effect is enabled.
  71197. */
  71198. set: function (value) {
  71199. this.imageProcessingConfiguration.vignetteEnabled = value;
  71200. },
  71201. enumerable: true,
  71202. configurable: true
  71203. });
  71204. Object.defineProperty(ImageProcessingPostProcess.prototype, "grainEnabled", {
  71205. /**
  71206. * Gets wether the grain effect is enabled.
  71207. */
  71208. get: function () {
  71209. return this.imageProcessingConfiguration.grainEnabled;
  71210. },
  71211. /**
  71212. * Sets wether the grain effect is enabled.
  71213. */
  71214. set: function (value) {
  71215. this.imageProcessingConfiguration.grainEnabled = value;
  71216. },
  71217. enumerable: true,
  71218. configurable: true
  71219. });
  71220. Object.defineProperty(ImageProcessingPostProcess.prototype, "grainIntensity", {
  71221. /**
  71222. * Gets the grain effect's intensity.
  71223. */
  71224. get: function () {
  71225. return this.imageProcessingConfiguration.grainIntensity;
  71226. },
  71227. /**
  71228. * Sets the grain effect's intensity.
  71229. */
  71230. set: function (value) {
  71231. this.imageProcessingConfiguration.grainIntensity = value;
  71232. },
  71233. enumerable: true,
  71234. configurable: true
  71235. });
  71236. Object.defineProperty(ImageProcessingPostProcess.prototype, "grainAnimated", {
  71237. /**
  71238. * Gets wether the grain effect is animated.
  71239. */
  71240. get: function () {
  71241. return this.imageProcessingConfiguration.grainAnimated;
  71242. },
  71243. /**
  71244. * Sets wether the grain effect is animated.
  71245. */
  71246. set: function (value) {
  71247. this.imageProcessingConfiguration.grainAnimated = value;
  71248. },
  71249. enumerable: true,
  71250. configurable: true
  71251. });
  71252. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  71253. /**
  71254. * Gets wether the input of the processing is in Gamma or Linear Space.
  71255. */
  71256. get: function () {
  71257. return this._fromLinearSpace;
  71258. },
  71259. /**
  71260. * Sets wether the input of the processing is in Gamma or Linear Space.
  71261. */
  71262. set: function (value) {
  71263. if (this._fromLinearSpace === value) {
  71264. return;
  71265. }
  71266. this._fromLinearSpace = value;
  71267. this._updateParameters();
  71268. },
  71269. enumerable: true,
  71270. configurable: true
  71271. });
  71272. ImageProcessingPostProcess.prototype.getClassName = function () {
  71273. return "ImageProcessingPostProcess";
  71274. };
  71275. ImageProcessingPostProcess.prototype._updateParameters = function () {
  71276. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  71277. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  71278. var defines = "";
  71279. for (var define in this._defines) {
  71280. if (this._defines[define]) {
  71281. defines += "#define " + define + ";\r\n";
  71282. }
  71283. }
  71284. var samplers = ["textureSampler"];
  71285. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  71286. var uniforms = ["scale"];
  71287. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  71288. this.updateEffect(defines, uniforms, samplers);
  71289. };
  71290. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  71291. _super.prototype.dispose.call(this, camera);
  71292. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  71293. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  71294. }
  71295. this.imageProcessingConfiguration.applyByPostProcess = false;
  71296. };
  71297. __decorate([
  71298. BABYLON.serialize()
  71299. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  71300. return ImageProcessingPostProcess;
  71301. }(BABYLON.PostProcess));
  71302. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  71303. })(BABYLON || (BABYLON = {}));
  71304. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  71305. var BABYLON;
  71306. (function (BABYLON) {
  71307. var Bone = /** @class */ (function (_super) {
  71308. __extends(Bone, _super);
  71309. function Bone(name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  71310. if (parentBone === void 0) { parentBone = null; }
  71311. if (localMatrix === void 0) { localMatrix = null; }
  71312. if (restPose === void 0) { restPose = null; }
  71313. if (baseMatrix === void 0) { baseMatrix = null; }
  71314. if (index === void 0) { index = null; }
  71315. var _this = _super.call(this, name, skeleton.getScene()) || this;
  71316. _this.name = name;
  71317. _this.children = new Array();
  71318. _this.animations = new Array();
  71319. // Set this value to map this bone to a different index in the transform matrices.
  71320. // Set this value to -1 to exclude the bone from the transform matrices.
  71321. _this._index = null;
  71322. _this._worldTransform = new BABYLON.Matrix();
  71323. _this._absoluteTransform = new BABYLON.Matrix();
  71324. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  71325. _this._scaleMatrix = BABYLON.Matrix.Identity();
  71326. _this._scaleVector = BABYLON.Vector3.One();
  71327. _this._negateScaleChildren = BABYLON.Vector3.One();
  71328. _this._scalingDeterminant = 1;
  71329. _this._skeleton = skeleton;
  71330. _this._localMatrix = localMatrix ? localMatrix : BABYLON.Matrix.Identity();
  71331. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  71332. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  71333. _this._index = index;
  71334. skeleton.bones.push(_this);
  71335. _this.setParent(parentBone, false);
  71336. _this._updateDifferenceMatrix();
  71337. return _this;
  71338. }
  71339. Object.defineProperty(Bone.prototype, "_matrix", {
  71340. get: function () {
  71341. return this._localMatrix;
  71342. },
  71343. set: function (val) {
  71344. if (this._localMatrix) {
  71345. this._localMatrix.copyFrom(val);
  71346. }
  71347. else {
  71348. this._localMatrix = val;
  71349. }
  71350. },
  71351. enumerable: true,
  71352. configurable: true
  71353. });
  71354. // Members
  71355. Bone.prototype.getSkeleton = function () {
  71356. return this._skeleton;
  71357. };
  71358. Bone.prototype.getParent = function () {
  71359. return this._parent;
  71360. };
  71361. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  71362. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  71363. if (this._parent === parent) {
  71364. return;
  71365. }
  71366. if (this._parent) {
  71367. var index = this._parent.children.indexOf(this);
  71368. if (index !== -1) {
  71369. this._parent.children.splice(index, 1);
  71370. }
  71371. }
  71372. this._parent = parent;
  71373. if (this._parent) {
  71374. this._parent.children.push(this);
  71375. }
  71376. if (updateDifferenceMatrix) {
  71377. this._updateDifferenceMatrix();
  71378. }
  71379. };
  71380. Bone.prototype.getLocalMatrix = function () {
  71381. return this._localMatrix;
  71382. };
  71383. Bone.prototype.getBaseMatrix = function () {
  71384. return this._baseMatrix;
  71385. };
  71386. Bone.prototype.getRestPose = function () {
  71387. return this._restPose;
  71388. };
  71389. Bone.prototype.returnToRest = function () {
  71390. this.updateMatrix(this._restPose.clone());
  71391. };
  71392. Bone.prototype.getWorldMatrix = function () {
  71393. return this._worldTransform;
  71394. };
  71395. Bone.prototype.getInvertedAbsoluteTransform = function () {
  71396. return this._invertedAbsoluteTransform;
  71397. };
  71398. Bone.prototype.getAbsoluteTransform = function () {
  71399. return this._absoluteTransform;
  71400. };
  71401. Object.defineProperty(Bone.prototype, "position", {
  71402. // Properties (matches AbstractMesh properties)
  71403. get: function () {
  71404. return this.getPosition();
  71405. },
  71406. set: function (newPosition) {
  71407. this.setPosition(newPosition);
  71408. },
  71409. enumerable: true,
  71410. configurable: true
  71411. });
  71412. Object.defineProperty(Bone.prototype, "rotation", {
  71413. get: function () {
  71414. return this.getRotation();
  71415. },
  71416. set: function (newRotation) {
  71417. this.setRotation(newRotation);
  71418. },
  71419. enumerable: true,
  71420. configurable: true
  71421. });
  71422. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  71423. get: function () {
  71424. return this.getRotationQuaternion();
  71425. },
  71426. set: function (newRotation) {
  71427. this.setRotationQuaternion(newRotation);
  71428. },
  71429. enumerable: true,
  71430. configurable: true
  71431. });
  71432. Object.defineProperty(Bone.prototype, "scaling", {
  71433. get: function () {
  71434. return this.getScale();
  71435. },
  71436. set: function (newScaling) {
  71437. this.setScale(newScaling.x, newScaling.y, newScaling.z);
  71438. },
  71439. enumerable: true,
  71440. configurable: true
  71441. });
  71442. Object.defineProperty(Bone.prototype, "animationPropertiesOverride", {
  71443. /**
  71444. * Gets the animation properties override
  71445. */
  71446. get: function () {
  71447. return this._skeleton.animationPropertiesOverride;
  71448. },
  71449. enumerable: true,
  71450. configurable: true
  71451. });
  71452. // Methods
  71453. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  71454. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  71455. this._baseMatrix = matrix.clone();
  71456. this._localMatrix = matrix.clone();
  71457. this._skeleton._markAsDirty();
  71458. if (updateDifferenceMatrix) {
  71459. this._updateDifferenceMatrix();
  71460. }
  71461. };
  71462. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  71463. if (!rootMatrix) {
  71464. rootMatrix = this._baseMatrix;
  71465. }
  71466. if (this._parent) {
  71467. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  71468. }
  71469. else {
  71470. this._absoluteTransform.copyFrom(rootMatrix);
  71471. }
  71472. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  71473. for (var index = 0; index < this.children.length; index++) {
  71474. this.children[index]._updateDifferenceMatrix();
  71475. }
  71476. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  71477. };
  71478. Bone.prototype.markAsDirty = function () {
  71479. this._currentRenderId++;
  71480. this._skeleton._markAsDirty();
  71481. };
  71482. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  71483. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  71484. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  71485. // all animation may be coming from a library skeleton, so may need to create animation
  71486. if (this.animations.length === 0) {
  71487. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  71488. this.animations[0].setKeys([]);
  71489. }
  71490. // get animation info / verify there is such a range from the source bone
  71491. var sourceRange = source.animations[0].getRange(rangeName);
  71492. if (!sourceRange) {
  71493. return false;
  71494. }
  71495. var from = sourceRange.from;
  71496. var to = sourceRange.to;
  71497. var sourceKeys = source.animations[0].getKeys();
  71498. // rescaling prep
  71499. var sourceBoneLength = source.length;
  71500. var sourceParent = source.getParent();
  71501. var parent = this.getParent();
  71502. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  71503. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  71504. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  71505. var destKeys = this.animations[0].getKeys();
  71506. // loop vars declaration
  71507. var orig;
  71508. var origTranslation;
  71509. var mat;
  71510. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  71511. orig = sourceKeys[key];
  71512. if (orig.frame >= from && orig.frame <= to) {
  71513. if (rescaleAsRequired) {
  71514. mat = orig.value.clone();
  71515. // scale based on parent ratio, when bone has parent
  71516. if (parentScalingReqd) {
  71517. origTranslation = mat.getTranslation();
  71518. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  71519. // scale based on skeleton dimension ratio when root bone, and value is passed
  71520. }
  71521. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  71522. origTranslation = mat.getTranslation();
  71523. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  71524. // use original when root bone, and no data for skelDimensionsRatio
  71525. }
  71526. else {
  71527. mat = orig.value;
  71528. }
  71529. }
  71530. else {
  71531. mat = orig.value;
  71532. }
  71533. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  71534. }
  71535. }
  71536. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  71537. return true;
  71538. };
  71539. /**
  71540. * Translate the bone in local or world space.
  71541. * @param vec The amount to translate the bone.
  71542. * @param space The space that the translation is in.
  71543. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71544. */
  71545. Bone.prototype.translate = function (vec, space, mesh) {
  71546. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71547. var lm = this.getLocalMatrix();
  71548. if (space == BABYLON.Space.LOCAL) {
  71549. lm.m[12] += vec.x;
  71550. lm.m[13] += vec.y;
  71551. lm.m[14] += vec.z;
  71552. }
  71553. else {
  71554. var wm = null;
  71555. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  71556. if (mesh) {
  71557. wm = mesh.getWorldMatrix();
  71558. }
  71559. this._skeleton.computeAbsoluteTransforms();
  71560. var tmat = Bone._tmpMats[0];
  71561. var tvec = Bone._tmpVecs[0];
  71562. if (this._parent) {
  71563. if (mesh && wm) {
  71564. tmat.copyFrom(this._parent.getAbsoluteTransform());
  71565. tmat.multiplyToRef(wm, tmat);
  71566. }
  71567. else {
  71568. tmat.copyFrom(this._parent.getAbsoluteTransform());
  71569. }
  71570. }
  71571. tmat.m[12] = 0;
  71572. tmat.m[13] = 0;
  71573. tmat.m[14] = 0;
  71574. tmat.invert();
  71575. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  71576. lm.m[12] += tvec.x;
  71577. lm.m[13] += tvec.y;
  71578. lm.m[14] += tvec.z;
  71579. }
  71580. this.markAsDirty();
  71581. };
  71582. /**
  71583. * Set the postion of the bone in local or world space.
  71584. * @param position The position to set the bone.
  71585. * @param space The space that the position is in.
  71586. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71587. */
  71588. Bone.prototype.setPosition = function (position, space, mesh) {
  71589. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71590. var lm = this.getLocalMatrix();
  71591. if (space == BABYLON.Space.LOCAL) {
  71592. lm.m[12] = position.x;
  71593. lm.m[13] = position.y;
  71594. lm.m[14] = position.z;
  71595. }
  71596. else {
  71597. var wm = null;
  71598. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  71599. if (mesh) {
  71600. wm = mesh.getWorldMatrix();
  71601. }
  71602. this._skeleton.computeAbsoluteTransforms();
  71603. var tmat = Bone._tmpMats[0];
  71604. var vec = Bone._tmpVecs[0];
  71605. if (this._parent) {
  71606. if (mesh && wm) {
  71607. tmat.copyFrom(this._parent.getAbsoluteTransform());
  71608. tmat.multiplyToRef(wm, tmat);
  71609. }
  71610. else {
  71611. tmat.copyFrom(this._parent.getAbsoluteTransform());
  71612. }
  71613. }
  71614. tmat.invert();
  71615. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  71616. lm.m[12] = vec.x;
  71617. lm.m[13] = vec.y;
  71618. lm.m[14] = vec.z;
  71619. }
  71620. this.markAsDirty();
  71621. };
  71622. /**
  71623. * Set the absolute postion of the bone (world space).
  71624. * @param position The position to set the bone.
  71625. * @param mesh The mesh that this bone is attached to.
  71626. */
  71627. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  71628. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  71629. };
  71630. /**
  71631. * Set the scale of the bone on the x, y and z axes.
  71632. * @param x The scale of the bone on the x axis.
  71633. * @param x The scale of the bone on the y axis.
  71634. * @param z The scale of the bone on the z axis.
  71635. * @param scaleChildren Set this to true if children of the bone should be scaled.
  71636. */
  71637. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  71638. if (scaleChildren === void 0) { scaleChildren = false; }
  71639. if (this.animations[0] && !this.animations[0].hasRunningRuntimeAnimations) {
  71640. if (!scaleChildren) {
  71641. this._negateScaleChildren.x = 1 / x;
  71642. this._negateScaleChildren.y = 1 / y;
  71643. this._negateScaleChildren.z = 1 / z;
  71644. }
  71645. this._syncScaleVector();
  71646. }
  71647. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  71648. };
  71649. /**
  71650. * Scale the bone on the x, y and z axes.
  71651. * @param x The amount to scale the bone on the x axis.
  71652. * @param x The amount to scale the bone on the y axis.
  71653. * @param z The amount to scale the bone on the z axis.
  71654. * @param scaleChildren Set this to true if children of the bone should be scaled.
  71655. */
  71656. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  71657. if (scaleChildren === void 0) { scaleChildren = false; }
  71658. var locMat = this.getLocalMatrix();
  71659. var origLocMat = Bone._tmpMats[0];
  71660. origLocMat.copyFrom(locMat);
  71661. var origLocMatInv = Bone._tmpMats[1];
  71662. origLocMatInv.copyFrom(origLocMat);
  71663. origLocMatInv.invert();
  71664. var scaleMat = Bone._tmpMats[2];
  71665. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  71666. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  71667. this._scaleVector.x *= x;
  71668. this._scaleVector.y *= y;
  71669. this._scaleVector.z *= z;
  71670. locMat.multiplyToRef(origLocMatInv, locMat);
  71671. locMat.multiplyToRef(scaleMat, locMat);
  71672. locMat.multiplyToRef(origLocMat, locMat);
  71673. var parent = this.getParent();
  71674. if (parent) {
  71675. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  71676. }
  71677. else {
  71678. this.getAbsoluteTransform().copyFrom(locMat);
  71679. }
  71680. var len = this.children.length;
  71681. scaleMat.invert();
  71682. for (var i = 0; i < len; i++) {
  71683. var child = this.children[i];
  71684. var cm = child.getLocalMatrix();
  71685. cm.multiplyToRef(scaleMat, cm);
  71686. var lm = child.getLocalMatrix();
  71687. lm.m[12] *= x;
  71688. lm.m[13] *= y;
  71689. lm.m[14] *= z;
  71690. }
  71691. this.computeAbsoluteTransforms();
  71692. if (scaleChildren) {
  71693. for (var i = 0; i < len; i++) {
  71694. this.children[i].scale(x, y, z, scaleChildren);
  71695. }
  71696. }
  71697. this.markAsDirty();
  71698. };
  71699. /**
  71700. * Set the yaw, pitch, and roll of the bone in local or world space.
  71701. * @param yaw The rotation of the bone on the y axis.
  71702. * @param pitch The rotation of the bone on the x axis.
  71703. * @param roll The rotation of the bone on the z axis.
  71704. * @param space The space that the axes of rotation are in.
  71705. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71706. */
  71707. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  71708. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71709. var rotMat = Bone._tmpMats[0];
  71710. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  71711. var rotMatInv = Bone._tmpMats[1];
  71712. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  71713. rotMatInv.multiplyToRef(rotMat, rotMat);
  71714. this._rotateWithMatrix(rotMat, space, mesh);
  71715. };
  71716. /**
  71717. * Rotate the bone on an axis in local or world space.
  71718. * @param axis The axis to rotate the bone on.
  71719. * @param amount The amount to rotate the bone.
  71720. * @param space The space that the axis is in.
  71721. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71722. */
  71723. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  71724. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71725. var rmat = Bone._tmpMats[0];
  71726. rmat.m[12] = 0;
  71727. rmat.m[13] = 0;
  71728. rmat.m[14] = 0;
  71729. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  71730. this._rotateWithMatrix(rmat, space, mesh);
  71731. };
  71732. /**
  71733. * Set the rotation of the bone to a particular axis angle in local or world space.
  71734. * @param axis The axis to rotate the bone on.
  71735. * @param angle The angle that the bone should be rotated to.
  71736. * @param space The space that the axis is in.
  71737. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71738. */
  71739. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  71740. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71741. var rotMat = Bone._tmpMats[0];
  71742. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  71743. var rotMatInv = Bone._tmpMats[1];
  71744. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  71745. rotMatInv.multiplyToRef(rotMat, rotMat);
  71746. this._rotateWithMatrix(rotMat, space, mesh);
  71747. };
  71748. /**
  71749. * Set the euler rotation of the bone in local of world space.
  71750. * @param rotation The euler rotation that the bone should be set to.
  71751. * @param space The space that the rotation is in.
  71752. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71753. */
  71754. Bone.prototype.setRotation = function (rotation, space, mesh) {
  71755. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71756. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  71757. };
  71758. /**
  71759. * Set the quaternion rotation of the bone in local of world space.
  71760. * @param quat The quaternion rotation that the bone should be set to.
  71761. * @param space The space that the rotation is in.
  71762. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71763. */
  71764. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  71765. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71766. var rotMatInv = Bone._tmpMats[0];
  71767. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  71768. var rotMat = Bone._tmpMats[1];
  71769. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  71770. rotMatInv.multiplyToRef(rotMat, rotMat);
  71771. this._rotateWithMatrix(rotMat, space, mesh);
  71772. };
  71773. /**
  71774. * Set the rotation matrix of the bone in local of world space.
  71775. * @param rotMat The rotation matrix that the bone should be set to.
  71776. * @param space The space that the rotation is in.
  71777. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71778. */
  71779. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  71780. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71781. var rotMatInv = Bone._tmpMats[0];
  71782. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  71783. var rotMat2 = Bone._tmpMats[1];
  71784. rotMat2.copyFrom(rotMat);
  71785. rotMatInv.multiplyToRef(rotMat, rotMat2);
  71786. this._rotateWithMatrix(rotMat2, space, mesh);
  71787. };
  71788. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  71789. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71790. var lmat = this.getLocalMatrix();
  71791. var lx = lmat.m[12];
  71792. var ly = lmat.m[13];
  71793. var lz = lmat.m[14];
  71794. var parent = this.getParent();
  71795. var parentScale = Bone._tmpMats[3];
  71796. var parentScaleInv = Bone._tmpMats[4];
  71797. if (parent) {
  71798. if (space == BABYLON.Space.WORLD) {
  71799. if (mesh) {
  71800. parentScale.copyFrom(mesh.getWorldMatrix());
  71801. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  71802. }
  71803. else {
  71804. parentScale.copyFrom(parent.getAbsoluteTransform());
  71805. }
  71806. }
  71807. else {
  71808. parentScale = parent._scaleMatrix;
  71809. }
  71810. parentScaleInv.copyFrom(parentScale);
  71811. parentScaleInv.invert();
  71812. lmat.multiplyToRef(parentScale, lmat);
  71813. lmat.multiplyToRef(rmat, lmat);
  71814. lmat.multiplyToRef(parentScaleInv, lmat);
  71815. }
  71816. else {
  71817. if (space == BABYLON.Space.WORLD && mesh) {
  71818. parentScale.copyFrom(mesh.getWorldMatrix());
  71819. parentScaleInv.copyFrom(parentScale);
  71820. parentScaleInv.invert();
  71821. lmat.multiplyToRef(parentScale, lmat);
  71822. lmat.multiplyToRef(rmat, lmat);
  71823. lmat.multiplyToRef(parentScaleInv, lmat);
  71824. }
  71825. else {
  71826. lmat.multiplyToRef(rmat, lmat);
  71827. }
  71828. }
  71829. lmat.m[12] = lx;
  71830. lmat.m[13] = ly;
  71831. lmat.m[14] = lz;
  71832. this.computeAbsoluteTransforms();
  71833. this.markAsDirty();
  71834. };
  71835. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  71836. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71837. if (space == BABYLON.Space.WORLD) {
  71838. var scaleMatrix = Bone._tmpMats[2];
  71839. scaleMatrix.copyFrom(this._scaleMatrix);
  71840. rotMatInv.copyFrom(this.getAbsoluteTransform());
  71841. if (mesh) {
  71842. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  71843. var meshScale = Bone._tmpMats[3];
  71844. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  71845. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  71846. }
  71847. rotMatInv.invert();
  71848. scaleMatrix.m[0] *= this._scalingDeterminant;
  71849. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  71850. }
  71851. else {
  71852. rotMatInv.copyFrom(this.getLocalMatrix());
  71853. rotMatInv.invert();
  71854. var scaleMatrix = Bone._tmpMats[2];
  71855. scaleMatrix.copyFrom(this._scaleMatrix);
  71856. if (this._parent) {
  71857. var pscaleMatrix = Bone._tmpMats[3];
  71858. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  71859. pscaleMatrix.invert();
  71860. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  71861. }
  71862. else {
  71863. scaleMatrix.m[0] *= this._scalingDeterminant;
  71864. }
  71865. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  71866. }
  71867. };
  71868. /**
  71869. * Get the scale of the bone
  71870. * @returns the scale of the bone
  71871. */
  71872. Bone.prototype.getScale = function () {
  71873. return this._scaleVector.clone();
  71874. };
  71875. /**
  71876. * Copy the scale of the bone to a vector3.
  71877. * @param result The vector3 to copy the scale to
  71878. */
  71879. Bone.prototype.getScaleToRef = function (result) {
  71880. result.copyFrom(this._scaleVector);
  71881. };
  71882. /**
  71883. * Get the position of the bone in local or world space.
  71884. * @param space The space that the returned position is in.
  71885. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71886. * @returns The position of the bone
  71887. */
  71888. Bone.prototype.getPosition = function (space, mesh) {
  71889. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71890. if (mesh === void 0) { mesh = null; }
  71891. var pos = BABYLON.Vector3.Zero();
  71892. this.getPositionToRef(space, mesh, pos);
  71893. return pos;
  71894. };
  71895. /**
  71896. * Copy the position of the bone to a vector3 in local or world space.
  71897. * @param space The space that the returned position is in.
  71898. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71899. * @param result The vector3 to copy the position to.
  71900. */
  71901. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  71902. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71903. if (space == BABYLON.Space.LOCAL) {
  71904. var lm = this.getLocalMatrix();
  71905. result.x = lm.m[12];
  71906. result.y = lm.m[13];
  71907. result.z = lm.m[14];
  71908. }
  71909. else {
  71910. var wm = null;
  71911. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  71912. if (mesh) {
  71913. wm = mesh.getWorldMatrix();
  71914. }
  71915. this._skeleton.computeAbsoluteTransforms();
  71916. var tmat = Bone._tmpMats[0];
  71917. if (mesh && wm) {
  71918. tmat.copyFrom(this.getAbsoluteTransform());
  71919. tmat.multiplyToRef(wm, tmat);
  71920. }
  71921. else {
  71922. tmat = this.getAbsoluteTransform();
  71923. }
  71924. result.x = tmat.m[12];
  71925. result.y = tmat.m[13];
  71926. result.z = tmat.m[14];
  71927. }
  71928. };
  71929. /**
  71930. * Get the absolute position of the bone (world space).
  71931. * @param mesh The mesh that this bone is attached to.
  71932. * @returns The absolute position of the bone
  71933. */
  71934. Bone.prototype.getAbsolutePosition = function (mesh) {
  71935. if (mesh === void 0) { mesh = null; }
  71936. var pos = BABYLON.Vector3.Zero();
  71937. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  71938. return pos;
  71939. };
  71940. /**
  71941. * Copy the absolute position of the bone (world space) to the result param.
  71942. * @param mesh The mesh that this bone is attached to.
  71943. * @param result The vector3 to copy the absolute position to.
  71944. */
  71945. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  71946. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  71947. };
  71948. /**
  71949. * Compute the absolute transforms of this bone and its children.
  71950. */
  71951. Bone.prototype.computeAbsoluteTransforms = function () {
  71952. if (this._parent) {
  71953. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  71954. }
  71955. else {
  71956. this._absoluteTransform.copyFrom(this._localMatrix);
  71957. var poseMatrix = this._skeleton.getPoseMatrix();
  71958. if (poseMatrix) {
  71959. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  71960. }
  71961. }
  71962. var children = this.children;
  71963. var len = children.length;
  71964. for (var i = 0; i < len; i++) {
  71965. children[i].computeAbsoluteTransforms();
  71966. }
  71967. };
  71968. Bone.prototype._syncScaleVector = function () {
  71969. var lm = this.getLocalMatrix();
  71970. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  71971. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  71972. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  71973. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  71974. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  71975. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  71976. this._scaleVector.x = xs * Math.sqrt(xsq);
  71977. this._scaleVector.y = ys * Math.sqrt(ysq);
  71978. this._scaleVector.z = zs * Math.sqrt(zsq);
  71979. if (this._parent) {
  71980. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  71981. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  71982. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  71983. }
  71984. BABYLON.Matrix.FromValuesToRef(this._scaleVector.x, 0, 0, 0, 0, this._scaleVector.y, 0, 0, 0, 0, this._scaleVector.z, 0, 0, 0, 0, 1, this._scaleMatrix);
  71985. };
  71986. /**
  71987. * Get the world direction from an axis that is in the local space of the bone.
  71988. * @param localAxis The local direction that is used to compute the world direction.
  71989. * @param mesh The mesh that this bone is attached to.
  71990. * @returns The world direction
  71991. */
  71992. Bone.prototype.getDirection = function (localAxis, mesh) {
  71993. if (mesh === void 0) { mesh = null; }
  71994. var result = BABYLON.Vector3.Zero();
  71995. this.getDirectionToRef(localAxis, mesh, result);
  71996. return result;
  71997. };
  71998. /**
  71999. * Copy the world direction to a vector3 from an axis that is in the local space of the bone.
  72000. * @param localAxis The local direction that is used to compute the world direction.
  72001. * @param mesh The mesh that this bone is attached to.
  72002. * @param result The vector3 that the world direction will be copied to.
  72003. */
  72004. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  72005. if (mesh === void 0) { mesh = null; }
  72006. var wm = null;
  72007. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  72008. if (mesh) {
  72009. wm = mesh.getWorldMatrix();
  72010. }
  72011. this._skeleton.computeAbsoluteTransforms();
  72012. var mat = Bone._tmpMats[0];
  72013. mat.copyFrom(this.getAbsoluteTransform());
  72014. if (mesh && wm) {
  72015. mat.multiplyToRef(wm, mat);
  72016. }
  72017. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  72018. result.normalize();
  72019. };
  72020. /**
  72021. * Get the euler rotation of the bone in local or world space.
  72022. * @param space The space that the rotation should be in.
  72023. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72024. * @returns The euler rotation
  72025. */
  72026. Bone.prototype.getRotation = function (space, mesh) {
  72027. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72028. if (mesh === void 0) { mesh = null; }
  72029. var result = BABYLON.Vector3.Zero();
  72030. this.getRotationToRef(space, mesh, result);
  72031. return result;
  72032. };
  72033. /**
  72034. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space.
  72035. * @param space The space that the rotation should be in.
  72036. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72037. * @param result The vector3 that the rotation should be copied to.
  72038. */
  72039. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  72040. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72041. if (mesh === void 0) { mesh = null; }
  72042. var quat = Bone._tmpQuat;
  72043. this.getRotationQuaternionToRef(space, mesh, quat);
  72044. quat.toEulerAnglesToRef(result);
  72045. };
  72046. /**
  72047. * Get the quaternion rotation of the bone in either local or world space.
  72048. * @param space The space that the rotation should be in.
  72049. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72050. * @returns The quaternion rotation
  72051. */
  72052. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  72053. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72054. if (mesh === void 0) { mesh = null; }
  72055. var result = BABYLON.Quaternion.Identity();
  72056. this.getRotationQuaternionToRef(space, mesh, result);
  72057. return result;
  72058. };
  72059. /**
  72060. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space.
  72061. * @param space The space that the rotation should be in.
  72062. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72063. * @param result The quaternion that the rotation should be copied to.
  72064. */
  72065. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  72066. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72067. if (mesh === void 0) { mesh = null; }
  72068. if (space == BABYLON.Space.LOCAL) {
  72069. this.getLocalMatrix().decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  72070. }
  72071. else {
  72072. var mat = Bone._tmpMats[0];
  72073. var amat = this.getAbsoluteTransform();
  72074. if (mesh) {
  72075. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  72076. }
  72077. else {
  72078. mat.copyFrom(amat);
  72079. }
  72080. mat.m[0] *= this._scalingDeterminant;
  72081. mat.m[1] *= this._scalingDeterminant;
  72082. mat.m[2] *= this._scalingDeterminant;
  72083. mat.decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  72084. }
  72085. };
  72086. /**
  72087. * Get the rotation matrix of the bone in local or world space.
  72088. * @param space The space that the rotation should be in.
  72089. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72090. * @returns The rotation matrix
  72091. */
  72092. Bone.prototype.getRotationMatrix = function (space, mesh) {
  72093. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72094. var result = BABYLON.Matrix.Identity();
  72095. this.getRotationMatrixToRef(space, mesh, result);
  72096. return result;
  72097. };
  72098. /**
  72099. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space.
  72100. * @param space The space that the rotation should be in.
  72101. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72102. * @param result The quaternion that the rotation should be copied to.
  72103. */
  72104. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  72105. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72106. if (space == BABYLON.Space.LOCAL) {
  72107. this.getLocalMatrix().getRotationMatrixToRef(result);
  72108. }
  72109. else {
  72110. var mat = Bone._tmpMats[0];
  72111. var amat = this.getAbsoluteTransform();
  72112. if (mesh) {
  72113. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  72114. }
  72115. else {
  72116. mat.copyFrom(amat);
  72117. }
  72118. mat.m[0] *= this._scalingDeterminant;
  72119. mat.m[1] *= this._scalingDeterminant;
  72120. mat.m[2] *= this._scalingDeterminant;
  72121. mat.getRotationMatrixToRef(result);
  72122. }
  72123. };
  72124. /**
  72125. * Get the world position of a point that is in the local space of the bone.
  72126. * @param position The local position
  72127. * @param mesh The mesh that this bone is attached to.
  72128. * @returns The world position
  72129. */
  72130. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  72131. if (mesh === void 0) { mesh = null; }
  72132. var result = BABYLON.Vector3.Zero();
  72133. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  72134. return result;
  72135. };
  72136. /**
  72137. * Get the world position of a point that is in the local space of the bone and copy it to the result param.
  72138. * @param position The local position
  72139. * @param mesh The mesh that this bone is attached to.
  72140. * @param result The vector3 that the world position should be copied to.
  72141. */
  72142. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  72143. if (mesh === void 0) { mesh = null; }
  72144. var wm = null;
  72145. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  72146. if (mesh) {
  72147. wm = mesh.getWorldMatrix();
  72148. }
  72149. this._skeleton.computeAbsoluteTransforms();
  72150. var tmat = Bone._tmpMats[0];
  72151. if (mesh && wm) {
  72152. tmat.copyFrom(this.getAbsoluteTransform());
  72153. tmat.multiplyToRef(wm, tmat);
  72154. }
  72155. else {
  72156. tmat = this.getAbsoluteTransform();
  72157. }
  72158. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  72159. };
  72160. /**
  72161. * Get the local position of a point that is in world space.
  72162. * @param position The world position
  72163. * @param mesh The mesh that this bone is attached to.
  72164. * @returns The local position
  72165. */
  72166. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  72167. if (mesh === void 0) { mesh = null; }
  72168. var result = BABYLON.Vector3.Zero();
  72169. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  72170. return result;
  72171. };
  72172. /**
  72173. * Get the local position of a point that is in world space and copy it to the result param.
  72174. * @param position The world position
  72175. * @param mesh The mesh that this bone is attached to.
  72176. * @param result The vector3 that the local position should be copied to.
  72177. */
  72178. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  72179. if (mesh === void 0) { mesh = null; }
  72180. var wm = null;
  72181. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  72182. if (mesh) {
  72183. wm = mesh.getWorldMatrix();
  72184. }
  72185. this._skeleton.computeAbsoluteTransforms();
  72186. var tmat = Bone._tmpMats[0];
  72187. tmat.copyFrom(this.getAbsoluteTransform());
  72188. if (mesh && wm) {
  72189. tmat.multiplyToRef(wm, tmat);
  72190. }
  72191. tmat.invert();
  72192. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  72193. };
  72194. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  72195. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  72196. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  72197. return Bone;
  72198. }(BABYLON.Node));
  72199. BABYLON.Bone = Bone;
  72200. })(BABYLON || (BABYLON = {}));
  72201. //# sourceMappingURL=babylon.bone.js.map
  72202. var BABYLON;
  72203. (function (BABYLON) {
  72204. var BoneIKController = /** @class */ (function () {
  72205. function BoneIKController(mesh, bone, options) {
  72206. this.targetPosition = BABYLON.Vector3.Zero();
  72207. this.poleTargetPosition = BABYLON.Vector3.Zero();
  72208. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  72209. this.poleAngle = 0;
  72210. this.slerpAmount = 1;
  72211. this._bone1Quat = BABYLON.Quaternion.Identity();
  72212. this._bone1Mat = BABYLON.Matrix.Identity();
  72213. this._bone2Ang = Math.PI;
  72214. this._maxAngle = Math.PI;
  72215. this._rightHandedSystem = false;
  72216. this._bendAxis = BABYLON.Vector3.Right();
  72217. this._slerping = false;
  72218. this._adjustRoll = 0;
  72219. this._bone2 = bone;
  72220. this._bone1 = bone.getParent();
  72221. if (!this._bone1) {
  72222. return;
  72223. }
  72224. this.mesh = mesh;
  72225. var bonePos = bone.getPosition();
  72226. if (bone.getAbsoluteTransform().determinant() > 0) {
  72227. this._rightHandedSystem = true;
  72228. this._bendAxis.x = 0;
  72229. this._bendAxis.y = 0;
  72230. this._bendAxis.z = -1;
  72231. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  72232. this._adjustRoll = Math.PI * .5;
  72233. this._bendAxis.z = 1;
  72234. }
  72235. }
  72236. if (this._bone1.length) {
  72237. var boneScale1 = this._bone1.getScale();
  72238. var boneScale2 = this._bone2.getScale();
  72239. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  72240. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  72241. }
  72242. else if (this._bone1.children[0]) {
  72243. mesh.computeWorldMatrix(true);
  72244. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  72245. var pos2 = this._bone2.getAbsolutePosition(mesh);
  72246. var pos3 = this._bone1.getAbsolutePosition(mesh);
  72247. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  72248. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  72249. }
  72250. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  72251. this.maxAngle = Math.PI;
  72252. if (options) {
  72253. if (options.targetMesh) {
  72254. this.targetMesh = options.targetMesh;
  72255. this.targetMesh.computeWorldMatrix(true);
  72256. }
  72257. if (options.poleTargetMesh) {
  72258. this.poleTargetMesh = options.poleTargetMesh;
  72259. this.poleTargetMesh.computeWorldMatrix(true);
  72260. }
  72261. else if (options.poleTargetBone) {
  72262. this.poleTargetBone = options.poleTargetBone;
  72263. }
  72264. else if (this._bone1.getParent()) {
  72265. this.poleTargetBone = this._bone1.getParent();
  72266. }
  72267. if (options.poleTargetLocalOffset) {
  72268. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  72269. }
  72270. if (options.poleAngle) {
  72271. this.poleAngle = options.poleAngle;
  72272. }
  72273. if (options.bendAxis) {
  72274. this._bendAxis.copyFrom(options.bendAxis);
  72275. }
  72276. if (options.maxAngle) {
  72277. this.maxAngle = options.maxAngle;
  72278. }
  72279. if (options.slerpAmount) {
  72280. this.slerpAmount = options.slerpAmount;
  72281. }
  72282. }
  72283. }
  72284. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  72285. get: function () {
  72286. return this._maxAngle;
  72287. },
  72288. set: function (value) {
  72289. this._setMaxAngle(value);
  72290. },
  72291. enumerable: true,
  72292. configurable: true
  72293. });
  72294. BoneIKController.prototype._setMaxAngle = function (ang) {
  72295. if (ang < 0) {
  72296. ang = 0;
  72297. }
  72298. if (ang > Math.PI || ang == undefined) {
  72299. ang = Math.PI;
  72300. }
  72301. this._maxAngle = ang;
  72302. var a = this._bone1Length;
  72303. var b = this._bone2Length;
  72304. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  72305. };
  72306. BoneIKController.prototype.update = function () {
  72307. var bone1 = this._bone1;
  72308. if (!bone1) {
  72309. return;
  72310. }
  72311. var target = this.targetPosition;
  72312. var poleTarget = this.poleTargetPosition;
  72313. var mat1 = BoneIKController._tmpMats[0];
  72314. var mat2 = BoneIKController._tmpMats[1];
  72315. if (this.targetMesh) {
  72316. target.copyFrom(this.targetMesh.getAbsolutePosition());
  72317. }
  72318. if (this.poleTargetBone) {
  72319. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  72320. }
  72321. else if (this.poleTargetMesh) {
  72322. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  72323. }
  72324. var bonePos = BoneIKController._tmpVecs[0];
  72325. var zaxis = BoneIKController._tmpVecs[1];
  72326. var xaxis = BoneIKController._tmpVecs[2];
  72327. var yaxis = BoneIKController._tmpVecs[3];
  72328. var upAxis = BoneIKController._tmpVecs[4];
  72329. var _tmpQuat = BoneIKController._tmpQuat;
  72330. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  72331. poleTarget.subtractToRef(bonePos, upAxis);
  72332. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  72333. upAxis.y = 1;
  72334. }
  72335. else {
  72336. upAxis.normalize();
  72337. }
  72338. target.subtractToRef(bonePos, yaxis);
  72339. yaxis.normalize();
  72340. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  72341. zaxis.normalize();
  72342. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  72343. xaxis.normalize();
  72344. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  72345. var a = this._bone1Length;
  72346. var b = this._bone2Length;
  72347. var c = BABYLON.Vector3.Distance(bonePos, target);
  72348. if (this._maxReach > 0) {
  72349. c = Math.min(this._maxReach, c);
  72350. }
  72351. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  72352. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  72353. if (acosa > 1) {
  72354. acosa = 1;
  72355. }
  72356. if (acosb > 1) {
  72357. acosb = 1;
  72358. }
  72359. if (acosa < -1) {
  72360. acosa = -1;
  72361. }
  72362. if (acosb < -1) {
  72363. acosb = -1;
  72364. }
  72365. var angA = Math.acos(acosa);
  72366. var angB = Math.acos(acosb);
  72367. var angC = -angA - angB;
  72368. if (this._rightHandedSystem) {
  72369. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  72370. mat2.multiplyToRef(mat1, mat1);
  72371. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  72372. mat2.multiplyToRef(mat1, mat1);
  72373. }
  72374. else {
  72375. var _tmpVec = BoneIKController._tmpVecs[5];
  72376. _tmpVec.copyFrom(this._bendAxis);
  72377. _tmpVec.x *= -1;
  72378. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  72379. mat2.multiplyToRef(mat1, mat1);
  72380. }
  72381. if (this.poleAngle) {
  72382. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  72383. mat1.multiplyToRef(mat2, mat1);
  72384. }
  72385. if (this._bone1) {
  72386. if (this.slerpAmount < 1) {
  72387. if (!this._slerping) {
  72388. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  72389. }
  72390. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  72391. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  72392. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  72393. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  72394. this._slerping = true;
  72395. }
  72396. else {
  72397. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  72398. this._bone1Mat.copyFrom(mat1);
  72399. this._slerping = false;
  72400. }
  72401. }
  72402. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  72403. this._bone2Ang = angC;
  72404. };
  72405. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  72406. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  72407. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  72408. return BoneIKController;
  72409. }());
  72410. BABYLON.BoneIKController = BoneIKController;
  72411. })(BABYLON || (BABYLON = {}));
  72412. //# sourceMappingURL=babylon.boneIKController.js.map
  72413. var BABYLON;
  72414. (function (BABYLON) {
  72415. var BoneLookController = /** @class */ (function () {
  72416. /**
  72417. * Create a BoneLookController
  72418. * @param mesh the mesh that the bone belongs to
  72419. * @param bone the bone that will be looking to the target
  72420. * @param target the target Vector3 to look at
  72421. * @param settings optional settings:
  72422. * - maxYaw: the maximum angle the bone will yaw to
  72423. * - minYaw: the minimum angle the bone will yaw to
  72424. * - maxPitch: the maximum angle the bone will pitch to
  72425. * - minPitch: the minimum angle the bone will yaw to
  72426. * - slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  72427. * - upAxis: the up axis of the coordinate system
  72428. * - upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  72429. * - yawAxis: set yawAxis if the bone does not yaw on the y axis
  72430. * - pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  72431. * - adjustYaw: used to make an adjustment to the yaw of the bone
  72432. * - adjustPitch: used to make an adjustment to the pitch of the bone
  72433. * - adjustRoll: used to make an adjustment to the roll of the bone
  72434. **/
  72435. function BoneLookController(mesh, bone, target, options) {
  72436. /**
  72437. * The up axis of the coordinate system that is used when the bone is rotated.
  72438. */
  72439. this.upAxis = BABYLON.Vector3.Up();
  72440. /**
  72441. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  72442. */
  72443. this.upAxisSpace = BABYLON.Space.LOCAL;
  72444. /**
  72445. * Used to make an adjustment to the yaw of the bone.
  72446. */
  72447. this.adjustYaw = 0;
  72448. /**
  72449. * Used to make an adjustment to the pitch of the bone.
  72450. */
  72451. this.adjustPitch = 0;
  72452. /**
  72453. * Used to make an adjustment to the roll of the bone.
  72454. */
  72455. this.adjustRoll = 0;
  72456. /**
  72457. * The amount to slerp (spherical linear interpolation) to the target. Set this to a value between 0 and 1 (a value of 1 disables slerp).
  72458. */
  72459. this.slerpAmount = 1;
  72460. this._boneQuat = BABYLON.Quaternion.Identity();
  72461. this._slerping = false;
  72462. this._firstFrameSkipped = false;
  72463. this._fowardAxis = BABYLON.Vector3.Forward();
  72464. this.mesh = mesh;
  72465. this.bone = bone;
  72466. this.target = target;
  72467. if (options) {
  72468. if (options.adjustYaw) {
  72469. this.adjustYaw = options.adjustYaw;
  72470. }
  72471. if (options.adjustPitch) {
  72472. this.adjustPitch = options.adjustPitch;
  72473. }
  72474. if (options.adjustRoll) {
  72475. this.adjustRoll = options.adjustRoll;
  72476. }
  72477. if (options.maxYaw != null) {
  72478. this.maxYaw = options.maxYaw;
  72479. }
  72480. else {
  72481. this.maxYaw = Math.PI;
  72482. }
  72483. if (options.minYaw != null) {
  72484. this.minYaw = options.minYaw;
  72485. }
  72486. else {
  72487. this.minYaw = -Math.PI;
  72488. }
  72489. if (options.maxPitch != null) {
  72490. this.maxPitch = options.maxPitch;
  72491. }
  72492. else {
  72493. this.maxPitch = Math.PI;
  72494. }
  72495. if (options.minPitch != null) {
  72496. this.minPitch = options.minPitch;
  72497. }
  72498. else {
  72499. this.minPitch = -Math.PI;
  72500. }
  72501. if (options.slerpAmount != null) {
  72502. this.slerpAmount = options.slerpAmount;
  72503. }
  72504. if (options.upAxis != null) {
  72505. this.upAxis = options.upAxis;
  72506. }
  72507. if (options.upAxisSpace != null) {
  72508. this.upAxisSpace = options.upAxisSpace;
  72509. }
  72510. if (options.yawAxis != null || options.pitchAxis != null) {
  72511. var newYawAxis = BABYLON.Axis.Y;
  72512. var newPitchAxis = BABYLON.Axis.X;
  72513. if (options.yawAxis != null) {
  72514. newYawAxis = options.yawAxis.clone();
  72515. newYawAxis.normalize();
  72516. }
  72517. if (options.pitchAxis != null) {
  72518. newPitchAxis = options.pitchAxis.clone();
  72519. newPitchAxis.normalize();
  72520. }
  72521. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  72522. this._transformYawPitch = BABYLON.Matrix.Identity();
  72523. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  72524. this._transformYawPitchInv = this._transformYawPitch.clone();
  72525. this._transformYawPitch.invert();
  72526. }
  72527. }
  72528. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  72529. this.upAxisSpace = BABYLON.Space.LOCAL;
  72530. }
  72531. }
  72532. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  72533. /**
  72534. * Get/set the minimum yaw angle that the bone can look to.
  72535. */
  72536. get: function () {
  72537. return this._minYaw;
  72538. },
  72539. set: function (value) {
  72540. this._minYaw = value;
  72541. this._minYawSin = Math.sin(value);
  72542. this._minYawCos = Math.cos(value);
  72543. if (this._maxYaw != null) {
  72544. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  72545. this._yawRange = this._maxYaw - this._minYaw;
  72546. }
  72547. },
  72548. enumerable: true,
  72549. configurable: true
  72550. });
  72551. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  72552. /**
  72553. * Get/set the maximum yaw angle that the bone can look to.
  72554. */
  72555. get: function () {
  72556. return this._maxYaw;
  72557. },
  72558. set: function (value) {
  72559. this._maxYaw = value;
  72560. this._maxYawSin = Math.sin(value);
  72561. this._maxYawCos = Math.cos(value);
  72562. if (this._minYaw != null) {
  72563. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  72564. this._yawRange = this._maxYaw - this._minYaw;
  72565. }
  72566. },
  72567. enumerable: true,
  72568. configurable: true
  72569. });
  72570. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  72571. /**
  72572. * Get/set the minimum pitch angle that the bone can look to.
  72573. */
  72574. get: function () {
  72575. return this._minPitch;
  72576. },
  72577. set: function (value) {
  72578. this._minPitch = value;
  72579. this._minPitchTan = Math.tan(value);
  72580. },
  72581. enumerable: true,
  72582. configurable: true
  72583. });
  72584. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  72585. /**
  72586. * Get/set the maximum pitch angle that the bone can look to.
  72587. */
  72588. get: function () {
  72589. return this._maxPitch;
  72590. },
  72591. set: function (value) {
  72592. this._maxPitch = value;
  72593. this._maxPitchTan = Math.tan(value);
  72594. },
  72595. enumerable: true,
  72596. configurable: true
  72597. });
  72598. /**
  72599. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender()).
  72600. */
  72601. BoneLookController.prototype.update = function () {
  72602. //skip the first frame when slerping so that the mesh rotation is correct
  72603. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  72604. this._firstFrameSkipped = true;
  72605. return;
  72606. }
  72607. var bone = this.bone;
  72608. var bonePos = BoneLookController._tmpVecs[0];
  72609. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  72610. var target = this.target;
  72611. var _tmpMat1 = BoneLookController._tmpMats[0];
  72612. var _tmpMat2 = BoneLookController._tmpMats[1];
  72613. var mesh = this.mesh;
  72614. var parentBone = bone.getParent();
  72615. var upAxis = BoneLookController._tmpVecs[1];
  72616. upAxis.copyFrom(this.upAxis);
  72617. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  72618. if (this._transformYawPitch) {
  72619. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  72620. }
  72621. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  72622. }
  72623. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  72624. mesh.getDirectionToRef(upAxis, upAxis);
  72625. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  72626. upAxis.normalize();
  72627. }
  72628. }
  72629. var checkYaw = false;
  72630. var checkPitch = false;
  72631. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  72632. checkYaw = true;
  72633. }
  72634. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  72635. checkPitch = true;
  72636. }
  72637. if (checkYaw || checkPitch) {
  72638. var spaceMat = BoneLookController._tmpMats[2];
  72639. var spaceMatInv = BoneLookController._tmpMats[3];
  72640. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  72641. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  72642. }
  72643. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  72644. spaceMat.copyFrom(mesh.getWorldMatrix());
  72645. }
  72646. else {
  72647. var forwardAxis = BoneLookController._tmpVecs[2];
  72648. forwardAxis.copyFrom(this._fowardAxis);
  72649. if (this._transformYawPitch) {
  72650. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  72651. }
  72652. if (parentBone) {
  72653. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  72654. }
  72655. else {
  72656. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  72657. }
  72658. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  72659. rightAxis.normalize();
  72660. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  72661. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  72662. }
  72663. spaceMat.invertToRef(spaceMatInv);
  72664. var xzlen = null;
  72665. if (checkPitch) {
  72666. var localTarget = BoneLookController._tmpVecs[3];
  72667. target.subtractToRef(bonePos, localTarget);
  72668. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  72669. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  72670. var pitch = Math.atan2(localTarget.y, xzlen);
  72671. var newPitch = pitch;
  72672. if (pitch > this._maxPitch) {
  72673. localTarget.y = this._maxPitchTan * xzlen;
  72674. newPitch = this._maxPitch;
  72675. }
  72676. else if (pitch < this._minPitch) {
  72677. localTarget.y = this._minPitchTan * xzlen;
  72678. newPitch = this._minPitch;
  72679. }
  72680. if (pitch != newPitch) {
  72681. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  72682. localTarget.addInPlace(bonePos);
  72683. target = localTarget;
  72684. }
  72685. }
  72686. if (checkYaw) {
  72687. var localTarget = BoneLookController._tmpVecs[4];
  72688. target.subtractToRef(bonePos, localTarget);
  72689. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  72690. var yaw = Math.atan2(localTarget.x, localTarget.z);
  72691. var newYaw = yaw;
  72692. if (yaw > this._maxYaw || yaw < this._minYaw) {
  72693. if (xzlen == null) {
  72694. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  72695. }
  72696. if (this._yawRange > Math.PI) {
  72697. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  72698. localTarget.z = this._maxYawCos * xzlen;
  72699. localTarget.x = this._maxYawSin * xzlen;
  72700. newYaw = this._maxYaw;
  72701. }
  72702. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  72703. localTarget.z = this._minYawCos * xzlen;
  72704. localTarget.x = this._minYawSin * xzlen;
  72705. newYaw = this._minYaw;
  72706. }
  72707. }
  72708. else {
  72709. if (yaw > this._maxYaw) {
  72710. localTarget.z = this._maxYawCos * xzlen;
  72711. localTarget.x = this._maxYawSin * xzlen;
  72712. newYaw = this._maxYaw;
  72713. }
  72714. else if (yaw < this._minYaw) {
  72715. localTarget.z = this._minYawCos * xzlen;
  72716. localTarget.x = this._minYawSin * xzlen;
  72717. newYaw = this._minYaw;
  72718. }
  72719. }
  72720. }
  72721. if (this._slerping && this._yawRange > Math.PI) {
  72722. //are we going to be crossing into the min/max region?
  72723. var boneFwd = BoneLookController._tmpVecs[8];
  72724. boneFwd.copyFrom(BABYLON.Axis.Z);
  72725. if (this._transformYawPitch) {
  72726. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  72727. }
  72728. var boneRotMat = BoneLookController._tmpMats[4];
  72729. this._boneQuat.toRotationMatrix(boneRotMat);
  72730. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  72731. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  72732. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  72733. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  72734. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  72735. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  72736. if (angBtwTar > angBtwMidYaw) {
  72737. if (xzlen == null) {
  72738. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  72739. }
  72740. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  72741. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  72742. if (angBtwMin < angBtwMax) {
  72743. newYaw = boneYaw + Math.PI * .75;
  72744. localTarget.z = Math.cos(newYaw) * xzlen;
  72745. localTarget.x = Math.sin(newYaw) * xzlen;
  72746. }
  72747. else {
  72748. newYaw = boneYaw - Math.PI * .75;
  72749. localTarget.z = Math.cos(newYaw) * xzlen;
  72750. localTarget.x = Math.sin(newYaw) * xzlen;
  72751. }
  72752. }
  72753. }
  72754. if (yaw != newYaw) {
  72755. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  72756. localTarget.addInPlace(bonePos);
  72757. target = localTarget;
  72758. }
  72759. }
  72760. }
  72761. var zaxis = BoneLookController._tmpVecs[5];
  72762. var xaxis = BoneLookController._tmpVecs[6];
  72763. var yaxis = BoneLookController._tmpVecs[7];
  72764. var _tmpQuat = BoneLookController._tmpQuat;
  72765. target.subtractToRef(bonePos, zaxis);
  72766. zaxis.normalize();
  72767. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  72768. xaxis.normalize();
  72769. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  72770. yaxis.normalize();
  72771. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  72772. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  72773. return;
  72774. }
  72775. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  72776. return;
  72777. }
  72778. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  72779. return;
  72780. }
  72781. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  72782. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  72783. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  72784. }
  72785. if (this.slerpAmount < 1) {
  72786. if (!this._slerping) {
  72787. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  72788. }
  72789. if (this._transformYawPitch) {
  72790. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  72791. }
  72792. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  72793. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  72794. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  72795. this._slerping = true;
  72796. }
  72797. else {
  72798. if (this._transformYawPitch) {
  72799. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  72800. }
  72801. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  72802. this._slerping = false;
  72803. }
  72804. };
  72805. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  72806. var angDiff = ang2 - ang1;
  72807. angDiff %= Math.PI * 2;
  72808. if (angDiff > Math.PI) {
  72809. angDiff -= Math.PI * 2;
  72810. }
  72811. else if (angDiff < -Math.PI) {
  72812. angDiff += Math.PI * 2;
  72813. }
  72814. return angDiff;
  72815. };
  72816. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  72817. ang1 %= (2 * Math.PI);
  72818. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  72819. ang2 %= (2 * Math.PI);
  72820. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  72821. var ab = 0;
  72822. if (ang1 < ang2) {
  72823. ab = ang2 - ang1;
  72824. }
  72825. else {
  72826. ab = ang1 - ang2;
  72827. }
  72828. if (ab > Math.PI) {
  72829. ab = Math.PI * 2 - ab;
  72830. }
  72831. return ab;
  72832. };
  72833. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  72834. ang %= (2 * Math.PI);
  72835. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  72836. ang1 %= (2 * Math.PI);
  72837. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  72838. ang2 %= (2 * Math.PI);
  72839. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  72840. if (ang1 < ang2) {
  72841. if (ang > ang1 && ang < ang2) {
  72842. return true;
  72843. }
  72844. }
  72845. else {
  72846. if (ang > ang2 && ang < ang1) {
  72847. return true;
  72848. }
  72849. }
  72850. return false;
  72851. };
  72852. BoneLookController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  72853. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  72854. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  72855. return BoneLookController;
  72856. }());
  72857. BABYLON.BoneLookController = BoneLookController;
  72858. })(BABYLON || (BABYLON = {}));
  72859. //# sourceMappingURL=babylon.boneLookController.js.map
  72860. var BABYLON;
  72861. (function (BABYLON) {
  72862. var Skeleton = /** @class */ (function () {
  72863. function Skeleton(name, id, scene) {
  72864. this.name = name;
  72865. this.id = id;
  72866. this.bones = new Array();
  72867. this.needInitialSkinMatrix = false;
  72868. this._isDirty = true;
  72869. this._meshesWithPoseMatrix = new Array();
  72870. this._identity = BABYLON.Matrix.Identity();
  72871. this._ranges = {};
  72872. this._lastAbsoluteTransformsUpdateId = -1;
  72873. /**
  72874. * Specifies if the skeleton should be serialized.
  72875. */
  72876. this.doNotSerialize = false;
  72877. // Events
  72878. /**
  72879. * An event triggered before computing the skeleton's matrices
  72880. * @type {BABYLON.Observable}
  72881. */
  72882. this.onBeforeComputeObservable = new BABYLON.Observable();
  72883. this.bones = [];
  72884. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  72885. scene.skeletons.push(this);
  72886. //make sure it will recalculate the matrix next time prepare is called.
  72887. this._isDirty = true;
  72888. }
  72889. // Members
  72890. Skeleton.prototype.getTransformMatrices = function (mesh) {
  72891. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  72892. return mesh._bonesTransformMatrices;
  72893. }
  72894. if (!this._transformMatrices) {
  72895. this.prepare();
  72896. }
  72897. return this._transformMatrices;
  72898. };
  72899. Skeleton.prototype.getScene = function () {
  72900. return this._scene;
  72901. };
  72902. // Methods
  72903. /**
  72904. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  72905. */
  72906. Skeleton.prototype.toString = function (fullDetails) {
  72907. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  72908. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  72909. if (fullDetails) {
  72910. ret += ", Ranges: {";
  72911. var first = true;
  72912. for (var name_1 in this._ranges) {
  72913. if (first) {
  72914. ret += ", ";
  72915. first = false;
  72916. }
  72917. ret += name_1;
  72918. }
  72919. ret += "}";
  72920. }
  72921. return ret;
  72922. };
  72923. /**
  72924. * Get bone's index searching by name
  72925. * @param {string} name is bone's name to search for
  72926. * @return {number} Indice of the bone. Returns -1 if not found
  72927. */
  72928. Skeleton.prototype.getBoneIndexByName = function (name) {
  72929. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  72930. if (this.bones[boneIndex].name === name) {
  72931. return boneIndex;
  72932. }
  72933. }
  72934. return -1;
  72935. };
  72936. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  72937. // check name not already in use
  72938. if (!this._ranges[name]) {
  72939. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  72940. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  72941. if (this.bones[i].animations[0]) {
  72942. this.bones[i].animations[0].createRange(name, from, to);
  72943. }
  72944. }
  72945. }
  72946. };
  72947. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  72948. if (deleteFrames === void 0) { deleteFrames = true; }
  72949. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  72950. if (this.bones[i].animations[0]) {
  72951. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  72952. }
  72953. }
  72954. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  72955. };
  72956. Skeleton.prototype.getAnimationRange = function (name) {
  72957. return this._ranges[name];
  72958. };
  72959. /**
  72960. * Returns as an Array, all AnimationRanges defined on this skeleton
  72961. */
  72962. Skeleton.prototype.getAnimationRanges = function () {
  72963. var animationRanges = [];
  72964. var name;
  72965. var i = 0;
  72966. for (name in this._ranges) {
  72967. animationRanges[i] = this._ranges[name];
  72968. i++;
  72969. }
  72970. return animationRanges;
  72971. };
  72972. /**
  72973. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  72974. */
  72975. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  72976. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  72977. if (this._ranges[name] || !source.getAnimationRange(name)) {
  72978. return false;
  72979. }
  72980. var ret = true;
  72981. var frameOffset = this._getHighestAnimationFrame() + 1;
  72982. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  72983. var boneDict = {};
  72984. var sourceBones = source.bones;
  72985. var nBones;
  72986. var i;
  72987. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  72988. boneDict[sourceBones[i].name] = sourceBones[i];
  72989. }
  72990. if (this.bones.length !== sourceBones.length) {
  72991. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  72992. ret = false;
  72993. }
  72994. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  72995. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  72996. var boneName = this.bones[i].name;
  72997. var sourceBone = boneDict[boneName];
  72998. if (sourceBone) {
  72999. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  73000. }
  73001. else {
  73002. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  73003. ret = false;
  73004. }
  73005. }
  73006. // do not call createAnimationRange(), since it also is done to bones, which was already done
  73007. var range = source.getAnimationRange(name);
  73008. if (range) {
  73009. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  73010. }
  73011. return ret;
  73012. };
  73013. Skeleton.prototype.returnToRest = function () {
  73014. for (var index = 0; index < this.bones.length; index++) {
  73015. this.bones[index].returnToRest();
  73016. }
  73017. };
  73018. Skeleton.prototype._getHighestAnimationFrame = function () {
  73019. var ret = 0;
  73020. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  73021. if (this.bones[i].animations[0]) {
  73022. var highest = this.bones[i].animations[0].getHighestFrame();
  73023. if (ret < highest) {
  73024. ret = highest;
  73025. }
  73026. }
  73027. }
  73028. return ret;
  73029. };
  73030. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  73031. var range = this.getAnimationRange(name);
  73032. if (!range) {
  73033. return null;
  73034. }
  73035. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  73036. };
  73037. Skeleton.prototype._markAsDirty = function () {
  73038. this._isDirty = true;
  73039. };
  73040. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  73041. this._meshesWithPoseMatrix.push(mesh);
  73042. };
  73043. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  73044. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  73045. if (index > -1) {
  73046. this._meshesWithPoseMatrix.splice(index, 1);
  73047. }
  73048. };
  73049. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  73050. this.onBeforeComputeObservable.notifyObservers(this);
  73051. for (var index = 0; index < this.bones.length; index++) {
  73052. var bone = this.bones[index];
  73053. var parentBone = bone.getParent();
  73054. if (parentBone) {
  73055. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  73056. }
  73057. else {
  73058. if (initialSkinMatrix) {
  73059. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  73060. }
  73061. else {
  73062. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  73063. }
  73064. }
  73065. if (bone._index !== -1) {
  73066. var mappedIndex = bone._index === null ? index : bone._index;
  73067. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  73068. }
  73069. }
  73070. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  73071. };
  73072. Skeleton.prototype.prepare = function () {
  73073. if (!this._isDirty) {
  73074. return;
  73075. }
  73076. if (this.needInitialSkinMatrix) {
  73077. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  73078. var mesh = this._meshesWithPoseMatrix[index];
  73079. var poseMatrix = mesh.getPoseMatrix();
  73080. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  73081. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  73082. }
  73083. if (this._synchronizedWithMesh !== mesh) {
  73084. this._synchronizedWithMesh = mesh;
  73085. // Prepare bones
  73086. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  73087. var bone = this.bones[boneIndex];
  73088. if (!bone.getParent()) {
  73089. var matrix = bone.getBaseMatrix();
  73090. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  73091. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  73092. }
  73093. }
  73094. }
  73095. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  73096. }
  73097. }
  73098. else {
  73099. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  73100. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  73101. }
  73102. this._computeTransformMatrices(this._transformMatrices, null);
  73103. }
  73104. this._isDirty = false;
  73105. this._scene._activeBones.addCount(this.bones.length, false);
  73106. };
  73107. Skeleton.prototype.getAnimatables = function () {
  73108. if (!this._animatables || this._animatables.length !== this.bones.length) {
  73109. this._animatables = [];
  73110. for (var index = 0; index < this.bones.length; index++) {
  73111. this._animatables.push(this.bones[index]);
  73112. }
  73113. }
  73114. return this._animatables;
  73115. };
  73116. Skeleton.prototype.clone = function (name, id) {
  73117. var result = new Skeleton(name, id || name, this._scene);
  73118. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  73119. for (var index = 0; index < this.bones.length; index++) {
  73120. var source = this.bones[index];
  73121. var parentBone = null;
  73122. var parent_1 = source.getParent();
  73123. if (parent_1) {
  73124. var parentIndex = this.bones.indexOf(parent_1);
  73125. parentBone = result.bones[parentIndex];
  73126. }
  73127. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  73128. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  73129. }
  73130. if (this._ranges) {
  73131. result._ranges = {};
  73132. for (var rangeName in this._ranges) {
  73133. var range = this._ranges[rangeName];
  73134. if (range) {
  73135. result._ranges[rangeName] = range.clone();
  73136. }
  73137. }
  73138. }
  73139. this._isDirty = true;
  73140. return result;
  73141. };
  73142. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  73143. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  73144. this.bones.forEach(function (bone) {
  73145. bone.animations.forEach(function (animation) {
  73146. animation.enableBlending = true;
  73147. animation.blendingSpeed = blendingSpeed;
  73148. });
  73149. });
  73150. };
  73151. Skeleton.prototype.dispose = function () {
  73152. this._meshesWithPoseMatrix = [];
  73153. // Animations
  73154. this.getScene().stopAnimation(this);
  73155. // Remove from scene
  73156. this.getScene().removeSkeleton(this);
  73157. };
  73158. Skeleton.prototype.serialize = function () {
  73159. var serializationObject = {};
  73160. serializationObject.name = this.name;
  73161. serializationObject.id = this.id;
  73162. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  73163. serializationObject.bones = [];
  73164. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  73165. for (var index = 0; index < this.bones.length; index++) {
  73166. var bone = this.bones[index];
  73167. var parent_2 = bone.getParent();
  73168. var serializedBone = {
  73169. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  73170. name: bone.name,
  73171. matrix: bone.getBaseMatrix().toArray(),
  73172. rest: bone.getRestPose().toArray()
  73173. };
  73174. serializationObject.bones.push(serializedBone);
  73175. if (bone.length) {
  73176. serializedBone.length = bone.length;
  73177. }
  73178. if (bone.animations && bone.animations.length > 0) {
  73179. serializedBone.animation = bone.animations[0].serialize();
  73180. }
  73181. serializationObject.ranges = [];
  73182. for (var name in this._ranges) {
  73183. var source = this._ranges[name];
  73184. if (!source) {
  73185. continue;
  73186. }
  73187. var range = {};
  73188. range.name = name;
  73189. range.from = source.from;
  73190. range.to = source.to;
  73191. serializationObject.ranges.push(range);
  73192. }
  73193. }
  73194. return serializationObject;
  73195. };
  73196. Skeleton.Parse = function (parsedSkeleton, scene) {
  73197. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  73198. if (parsedSkeleton.dimensionsAtRest) {
  73199. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  73200. }
  73201. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  73202. var index;
  73203. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  73204. var parsedBone = parsedSkeleton.bones[index];
  73205. var parentBone = null;
  73206. if (parsedBone.parentBoneIndex > -1) {
  73207. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  73208. }
  73209. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  73210. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  73211. if (parsedBone.length) {
  73212. bone.length = parsedBone.length;
  73213. }
  73214. if (parsedBone.animation) {
  73215. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  73216. }
  73217. }
  73218. // placed after bones, so createAnimationRange can cascade down
  73219. if (parsedSkeleton.ranges) {
  73220. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  73221. var data = parsedSkeleton.ranges[index];
  73222. skeleton.createAnimationRange(data.name, data.from, data.to);
  73223. }
  73224. }
  73225. return skeleton;
  73226. };
  73227. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  73228. if (forceUpdate === void 0) { forceUpdate = false; }
  73229. var renderId = this._scene.getRenderId();
  73230. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  73231. this.bones[0].computeAbsoluteTransforms();
  73232. this._lastAbsoluteTransformsUpdateId = renderId;
  73233. }
  73234. };
  73235. Skeleton.prototype.getPoseMatrix = function () {
  73236. var poseMatrix = null;
  73237. if (this._meshesWithPoseMatrix.length > 0) {
  73238. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  73239. }
  73240. return poseMatrix;
  73241. };
  73242. Skeleton.prototype.sortBones = function () {
  73243. var bones = new Array();
  73244. var visited = new Array(this.bones.length);
  73245. for (var index = 0; index < this.bones.length; index++) {
  73246. this._sortBones(index, bones, visited);
  73247. }
  73248. this.bones = bones;
  73249. };
  73250. Skeleton.prototype._sortBones = function (index, bones, visited) {
  73251. if (visited[index]) {
  73252. return;
  73253. }
  73254. visited[index] = true;
  73255. var bone = this.bones[index];
  73256. if (bone._index === undefined) {
  73257. bone._index = index;
  73258. }
  73259. var parentBone = bone.getParent();
  73260. if (parentBone) {
  73261. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  73262. }
  73263. bones.push(bone);
  73264. };
  73265. return Skeleton;
  73266. }());
  73267. BABYLON.Skeleton = Skeleton;
  73268. })(BABYLON || (BABYLON = {}));
  73269. //# sourceMappingURL=babylon.skeleton.js.map
  73270. var BABYLON;
  73271. (function (BABYLON) {
  73272. var SphericalPolynomial = /** @class */ (function () {
  73273. function SphericalPolynomial() {
  73274. this.x = BABYLON.Vector3.Zero();
  73275. this.y = BABYLON.Vector3.Zero();
  73276. this.z = BABYLON.Vector3.Zero();
  73277. this.xx = BABYLON.Vector3.Zero();
  73278. this.yy = BABYLON.Vector3.Zero();
  73279. this.zz = BABYLON.Vector3.Zero();
  73280. this.xy = BABYLON.Vector3.Zero();
  73281. this.yz = BABYLON.Vector3.Zero();
  73282. this.zx = BABYLON.Vector3.Zero();
  73283. }
  73284. SphericalPolynomial.prototype.addAmbient = function (color) {
  73285. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  73286. this.xx = this.xx.add(colorVector);
  73287. this.yy = this.yy.add(colorVector);
  73288. this.zz = this.zz.add(colorVector);
  73289. };
  73290. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  73291. var result = new SphericalPolynomial();
  73292. result.x = harmonics.L11.scale(1.02333);
  73293. result.y = harmonics.L1_1.scale(1.02333);
  73294. result.z = harmonics.L10.scale(1.02333);
  73295. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  73296. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  73297. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  73298. result.yz = harmonics.L2_1.scale(0.858086);
  73299. result.zx = harmonics.L21.scale(0.858086);
  73300. result.xy = harmonics.L2_2.scale(0.858086);
  73301. result.scale(1.0 / Math.PI);
  73302. return result;
  73303. };
  73304. SphericalPolynomial.prototype.scale = function (scale) {
  73305. this.x = this.x.scale(scale);
  73306. this.y = this.y.scale(scale);
  73307. this.z = this.z.scale(scale);
  73308. this.xx = this.xx.scale(scale);
  73309. this.yy = this.yy.scale(scale);
  73310. this.zz = this.zz.scale(scale);
  73311. this.yz = this.yz.scale(scale);
  73312. this.zx = this.zx.scale(scale);
  73313. this.xy = this.xy.scale(scale);
  73314. };
  73315. return SphericalPolynomial;
  73316. }());
  73317. BABYLON.SphericalPolynomial = SphericalPolynomial;
  73318. var SphericalHarmonics = /** @class */ (function () {
  73319. function SphericalHarmonics() {
  73320. this.L00 = BABYLON.Vector3.Zero();
  73321. this.L1_1 = BABYLON.Vector3.Zero();
  73322. this.L10 = BABYLON.Vector3.Zero();
  73323. this.L11 = BABYLON.Vector3.Zero();
  73324. this.L2_2 = BABYLON.Vector3.Zero();
  73325. this.L2_1 = BABYLON.Vector3.Zero();
  73326. this.L20 = BABYLON.Vector3.Zero();
  73327. this.L21 = BABYLON.Vector3.Zero();
  73328. this.L22 = BABYLON.Vector3.Zero();
  73329. }
  73330. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  73331. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  73332. var c = colorVector.scale(deltaSolidAngle);
  73333. this.L00 = this.L00.add(c.scale(0.282095));
  73334. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  73335. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  73336. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  73337. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  73338. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  73339. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  73340. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  73341. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  73342. };
  73343. SphericalHarmonics.prototype.scale = function (scale) {
  73344. this.L00 = this.L00.scale(scale);
  73345. this.L1_1 = this.L1_1.scale(scale);
  73346. this.L10 = this.L10.scale(scale);
  73347. this.L11 = this.L11.scale(scale);
  73348. this.L2_2 = this.L2_2.scale(scale);
  73349. this.L2_1 = this.L2_1.scale(scale);
  73350. this.L20 = this.L20.scale(scale);
  73351. this.L21 = this.L21.scale(scale);
  73352. this.L22 = this.L22.scale(scale);
  73353. };
  73354. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  73355. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  73356. //
  73357. // E_lm = A_l * L_lm
  73358. //
  73359. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  73360. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  73361. // the scaling factors are given in equation 9.
  73362. // Constant (Band 0)
  73363. this.L00 = this.L00.scale(3.141593);
  73364. // Linear (Band 1)
  73365. this.L1_1 = this.L1_1.scale(2.094395);
  73366. this.L10 = this.L10.scale(2.094395);
  73367. this.L11 = this.L11.scale(2.094395);
  73368. // Quadratic (Band 2)
  73369. this.L2_2 = this.L2_2.scale(0.785398);
  73370. this.L2_1 = this.L2_1.scale(0.785398);
  73371. this.L20 = this.L20.scale(0.785398);
  73372. this.L21 = this.L21.scale(0.785398);
  73373. this.L22 = this.L22.scale(0.785398);
  73374. };
  73375. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  73376. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  73377. // L = (1/pi) * E * rho
  73378. //
  73379. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  73380. this.scale(1.0 / Math.PI);
  73381. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  73382. // (The pixel shader must apply albedo after texture fetches, etc).
  73383. };
  73384. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  73385. var result = new SphericalHarmonics();
  73386. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  73387. result.L1_1 = polynomial.y.scale(0.977204);
  73388. result.L10 = polynomial.z.scale(0.977204);
  73389. result.L11 = polynomial.x.scale(0.977204);
  73390. result.L2_2 = polynomial.xy.scale(1.16538);
  73391. result.L2_1 = polynomial.yz.scale(1.16538);
  73392. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  73393. result.L21 = polynomial.zx.scale(1.16538);
  73394. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  73395. result.scale(Math.PI);
  73396. return result;
  73397. };
  73398. return SphericalHarmonics;
  73399. }());
  73400. BABYLON.SphericalHarmonics = SphericalHarmonics;
  73401. })(BABYLON || (BABYLON = {}));
  73402. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  73403. var BABYLON;
  73404. (function (BABYLON) {
  73405. var FileFaceOrientation = /** @class */ (function () {
  73406. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  73407. this.name = name;
  73408. this.worldAxisForNormal = worldAxisForNormal;
  73409. this.worldAxisForFileX = worldAxisForFileX;
  73410. this.worldAxisForFileY = worldAxisForFileY;
  73411. }
  73412. return FileFaceOrientation;
  73413. }());
  73414. ;
  73415. /**
  73416. * Helper class dealing with the extraction of spherical polynomial dataArray
  73417. * from a cube map.
  73418. */
  73419. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  73420. function CubeMapToSphericalPolynomialTools() {
  73421. }
  73422. /**
  73423. * Converts a texture to the according Spherical Polynomial data.
  73424. * This extracts the first 3 orders only as they are the only one used in the lighting.
  73425. *
  73426. * @param texture The texture to extract the information from.
  73427. * @return The Spherical Polynomial data.
  73428. */
  73429. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  73430. if (!texture.isCube) {
  73431. // Only supports cube Textures currently.
  73432. return null;
  73433. }
  73434. var size = texture.getSize().width;
  73435. var right = texture.readPixels(0);
  73436. var left = texture.readPixels(1);
  73437. var up;
  73438. var down;
  73439. if (texture.isRenderTarget) {
  73440. up = texture.readPixels(3);
  73441. down = texture.readPixels(2);
  73442. }
  73443. else {
  73444. up = texture.readPixels(2);
  73445. down = texture.readPixels(3);
  73446. }
  73447. var front = texture.readPixels(4);
  73448. var back = texture.readPixels(5);
  73449. var gammaSpace = texture.gammaSpace;
  73450. // Always read as RGBA.
  73451. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  73452. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  73453. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  73454. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  73455. }
  73456. var cubeInfo = {
  73457. size: size,
  73458. right: right,
  73459. left: left,
  73460. up: up,
  73461. down: down,
  73462. front: front,
  73463. back: back,
  73464. format: format,
  73465. type: type,
  73466. gammaSpace: gammaSpace,
  73467. };
  73468. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  73469. };
  73470. /**
  73471. * Converts a cubemap to the according Spherical Polynomial data.
  73472. * This extracts the first 3 orders only as they are the only one used in the lighting.
  73473. *
  73474. * @param cubeInfo The Cube map to extract the information from.
  73475. * @return The Spherical Polynomial data.
  73476. */
  73477. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  73478. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  73479. var totalSolidAngle = 0.0;
  73480. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  73481. var du = 2.0 / cubeInfo.size;
  73482. var dv = du;
  73483. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  73484. var minUV = du * 0.5 - 1.0;
  73485. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  73486. var fileFace = this.FileFaces[faceIndex];
  73487. var dataArray = cubeInfo[fileFace.name];
  73488. var v = minUV;
  73489. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  73490. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  73491. // Because SP is still linear, so summation is fine in that basis.
  73492. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  73493. for (var y = 0; y < cubeInfo.size; y++) {
  73494. var u = minUV;
  73495. for (var x = 0; x < cubeInfo.size; x++) {
  73496. // World direction (not normalised)
  73497. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  73498. worldDirection.normalize();
  73499. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  73500. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  73501. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  73502. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  73503. // Handle Integer types.
  73504. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  73505. r /= 255;
  73506. g /= 255;
  73507. b /= 255;
  73508. }
  73509. // Handle Gamma space textures.
  73510. if (cubeInfo.gammaSpace) {
  73511. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  73512. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  73513. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  73514. }
  73515. var color = new BABYLON.Color3(r, g, b);
  73516. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  73517. totalSolidAngle += deltaSolidAngle;
  73518. u += du;
  73519. }
  73520. v += dv;
  73521. }
  73522. }
  73523. // Solid angle for entire sphere is 4*pi
  73524. var sphereSolidAngle = 4.0 * Math.PI;
  73525. // Adjust the solid angle to allow for how many faces we processed.
  73526. var facesProcessed = 6.0;
  73527. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  73528. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  73529. // This is needed because the numerical integration over the cube uses a
  73530. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  73531. // and also to compensate for accumulative error due to float precision in the summation.
  73532. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  73533. sphericalHarmonics.scale(correctionFactor);
  73534. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  73535. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  73536. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  73537. };
  73538. CubeMapToSphericalPolynomialTools.FileFaces = [
  73539. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  73540. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  73541. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  73542. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  73543. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  73544. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  73545. ];
  73546. return CubeMapToSphericalPolynomialTools;
  73547. }());
  73548. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  73549. })(BABYLON || (BABYLON = {}));
  73550. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  73551. var BABYLON;
  73552. (function (BABYLON) {
  73553. /**
  73554. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  73555. */
  73556. var PanoramaToCubeMapTools = /** @class */ (function () {
  73557. function PanoramaToCubeMapTools() {
  73558. }
  73559. /**
  73560. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  73561. *
  73562. * @param float32Array The source data.
  73563. * @param inputWidth The width of the input panorama.
  73564. * @param inputhHeight The height of the input panorama.
  73565. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  73566. * @return The cubemap data
  73567. */
  73568. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  73569. if (!float32Array) {
  73570. throw "ConvertPanoramaToCubemap: input cannot be null";
  73571. }
  73572. if (float32Array.length != inputWidth * inputHeight * 3) {
  73573. throw "ConvertPanoramaToCubemap: input size is wrong";
  73574. }
  73575. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  73576. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  73577. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  73578. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  73579. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  73580. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  73581. return {
  73582. front: textureFront,
  73583. back: textureBack,
  73584. left: textureLeft,
  73585. right: textureRight,
  73586. up: textureUp,
  73587. down: textureDown,
  73588. size: size,
  73589. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  73590. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  73591. gammaSpace: false,
  73592. };
  73593. };
  73594. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  73595. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  73596. var textureArray = new Float32Array(buffer);
  73597. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  73598. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  73599. var dy = 1 / texSize;
  73600. var fy = 0;
  73601. for (var y = 0; y < texSize; y++) {
  73602. var xv1 = faceData[0];
  73603. var xv2 = faceData[2];
  73604. for (var x = 0; x < texSize; x++) {
  73605. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  73606. v.normalize();
  73607. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  73608. // 3 channels per pixels
  73609. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  73610. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  73611. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  73612. xv1 = xv1.add(rotDX1);
  73613. xv2 = xv2.add(rotDX2);
  73614. }
  73615. fy += dy;
  73616. }
  73617. return textureArray;
  73618. };
  73619. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  73620. var theta = Math.atan2(vDir.z, vDir.x);
  73621. var phi = Math.acos(vDir.y);
  73622. while (theta < -Math.PI)
  73623. theta += 2 * Math.PI;
  73624. while (theta > Math.PI)
  73625. theta -= 2 * Math.PI;
  73626. var dx = theta / Math.PI;
  73627. var dy = phi / Math.PI;
  73628. // recenter.
  73629. dx = dx * 0.5 + 0.5;
  73630. var px = Math.round(dx * inputWidth);
  73631. if (px < 0)
  73632. px = 0;
  73633. else if (px >= inputWidth)
  73634. px = inputWidth - 1;
  73635. var py = Math.round(dy * inputHeight);
  73636. if (py < 0)
  73637. py = 0;
  73638. else if (py >= inputHeight)
  73639. py = inputHeight - 1;
  73640. var inputY = (inputHeight - py - 1);
  73641. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  73642. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  73643. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  73644. return {
  73645. r: r,
  73646. g: g,
  73647. b: b
  73648. };
  73649. };
  73650. PanoramaToCubeMapTools.FACE_FRONT = [
  73651. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  73652. new BABYLON.Vector3(1.0, -1.0, -1.0),
  73653. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  73654. new BABYLON.Vector3(1.0, 1.0, -1.0)
  73655. ];
  73656. PanoramaToCubeMapTools.FACE_BACK = [
  73657. new BABYLON.Vector3(1.0, -1.0, 1.0),
  73658. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  73659. new BABYLON.Vector3(1.0, 1.0, 1.0),
  73660. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  73661. ];
  73662. PanoramaToCubeMapTools.FACE_RIGHT = [
  73663. new BABYLON.Vector3(1.0, -1.0, -1.0),
  73664. new BABYLON.Vector3(1.0, -1.0, 1.0),
  73665. new BABYLON.Vector3(1.0, 1.0, -1.0),
  73666. new BABYLON.Vector3(1.0, 1.0, 1.0)
  73667. ];
  73668. PanoramaToCubeMapTools.FACE_LEFT = [
  73669. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  73670. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  73671. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  73672. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  73673. ];
  73674. PanoramaToCubeMapTools.FACE_DOWN = [
  73675. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  73676. new BABYLON.Vector3(1.0, 1.0, -1.0),
  73677. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  73678. new BABYLON.Vector3(1.0, 1.0, 1.0)
  73679. ];
  73680. PanoramaToCubeMapTools.FACE_UP = [
  73681. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  73682. new BABYLON.Vector3(1.0, -1.0, 1.0),
  73683. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  73684. new BABYLON.Vector3(1.0, -1.0, -1.0)
  73685. ];
  73686. return PanoramaToCubeMapTools;
  73687. }());
  73688. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  73689. })(BABYLON || (BABYLON = {}));
  73690. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  73691. var BABYLON;
  73692. (function (BABYLON) {
  73693. ;
  73694. /**
  73695. * This groups tools to convert HDR texture to native colors array.
  73696. */
  73697. var HDRTools = /** @class */ (function () {
  73698. function HDRTools() {
  73699. }
  73700. HDRTools.Ldexp = function (mantissa, exponent) {
  73701. if (exponent > 1023) {
  73702. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  73703. }
  73704. if (exponent < -1074) {
  73705. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  73706. }
  73707. return mantissa * Math.pow(2, exponent);
  73708. };
  73709. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  73710. if (exponent > 0) {
  73711. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  73712. float32array[index + 0] = red * exponent;
  73713. float32array[index + 1] = green * exponent;
  73714. float32array[index + 2] = blue * exponent;
  73715. }
  73716. else {
  73717. float32array[index + 0] = 0;
  73718. float32array[index + 1] = 0;
  73719. float32array[index + 2] = 0;
  73720. }
  73721. };
  73722. HDRTools.readStringLine = function (uint8array, startIndex) {
  73723. var line = "";
  73724. var character = "";
  73725. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  73726. character = String.fromCharCode(uint8array[i]);
  73727. if (character == "\n") {
  73728. break;
  73729. }
  73730. line += character;
  73731. }
  73732. return line;
  73733. };
  73734. /**
  73735. * Reads header information from an RGBE texture stored in a native array.
  73736. * More information on this format are available here:
  73737. * https://en.wikipedia.org/wiki/RGBE_image_format
  73738. *
  73739. * @param uint8array The binary file stored in native array.
  73740. * @return The header information.
  73741. */
  73742. HDRTools.RGBE_ReadHeader = function (uint8array) {
  73743. var height = 0;
  73744. var width = 0;
  73745. var line = this.readStringLine(uint8array, 0);
  73746. if (line[0] != '#' || line[1] != '?') {
  73747. throw "Bad HDR Format.";
  73748. }
  73749. var endOfHeader = false;
  73750. var findFormat = false;
  73751. var lineIndex = 0;
  73752. do {
  73753. lineIndex += (line.length + 1);
  73754. line = this.readStringLine(uint8array, lineIndex);
  73755. if (line == "FORMAT=32-bit_rle_rgbe") {
  73756. findFormat = true;
  73757. }
  73758. else if (line.length == 0) {
  73759. endOfHeader = true;
  73760. }
  73761. } while (!endOfHeader);
  73762. if (!findFormat) {
  73763. throw "HDR Bad header format, unsupported FORMAT";
  73764. }
  73765. lineIndex += (line.length + 1);
  73766. line = this.readStringLine(uint8array, lineIndex);
  73767. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  73768. var match = sizeRegexp.exec(line);
  73769. // TODO. Support +Y and -X if needed.
  73770. if (!match || match.length < 3) {
  73771. throw "HDR Bad header format, no size";
  73772. }
  73773. width = parseInt(match[2]);
  73774. height = parseInt(match[1]);
  73775. if (width < 8 || width > 0x7fff) {
  73776. throw "HDR Bad header format, unsupported size";
  73777. }
  73778. lineIndex += (line.length + 1);
  73779. return {
  73780. height: height,
  73781. width: width,
  73782. dataPosition: lineIndex
  73783. };
  73784. };
  73785. /**
  73786. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  73787. * This RGBE texture needs to store the information as a panorama.
  73788. *
  73789. * More information on this format are available here:
  73790. * https://en.wikipedia.org/wiki/RGBE_image_format
  73791. *
  73792. * @param buffer The binary file stored in an array buffer.
  73793. * @param size The expected size of the extracted cubemap.
  73794. * @return The Cube Map information.
  73795. */
  73796. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  73797. var uint8array = new Uint8Array(buffer);
  73798. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  73799. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  73800. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  73801. return cubeMapData;
  73802. };
  73803. /**
  73804. * Returns the pixels data extracted from an RGBE texture.
  73805. * This pixels will be stored left to right up to down in the R G B order in one array.
  73806. *
  73807. * More information on this format are available here:
  73808. * https://en.wikipedia.org/wiki/RGBE_image_format
  73809. *
  73810. * @param uint8array The binary file stored in an array buffer.
  73811. * @param hdrInfo The header information of the file.
  73812. * @return The pixels data in RGB right to left up to down order.
  73813. */
  73814. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  73815. // Keep for multi format supports.
  73816. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  73817. };
  73818. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  73819. var num_scanlines = hdrInfo.height;
  73820. var scanline_width = hdrInfo.width;
  73821. var a, b, c, d, count;
  73822. var dataIndex = hdrInfo.dataPosition;
  73823. var index = 0, endIndex = 0, i = 0;
  73824. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  73825. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  73826. // 3 channels of 4 bytes per pixel in float.
  73827. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  73828. var resultArray = new Float32Array(resultBuffer);
  73829. // read in each successive scanline
  73830. while (num_scanlines > 0) {
  73831. a = uint8array[dataIndex++];
  73832. b = uint8array[dataIndex++];
  73833. c = uint8array[dataIndex++];
  73834. d = uint8array[dataIndex++];
  73835. if (a != 2 || b != 2 || (c & 0x80)) {
  73836. // this file is not run length encoded
  73837. throw "HDR Bad header format, not RLE";
  73838. }
  73839. if (((c << 8) | d) != scanline_width) {
  73840. throw "HDR Bad header format, wrong scan line width";
  73841. }
  73842. index = 0;
  73843. // read each of the four channels for the scanline into the buffer
  73844. for (i = 0; i < 4; i++) {
  73845. endIndex = (i + 1) * scanline_width;
  73846. while (index < endIndex) {
  73847. a = uint8array[dataIndex++];
  73848. b = uint8array[dataIndex++];
  73849. if (a > 128) {
  73850. // a run of the same value
  73851. count = a - 128;
  73852. if ((count == 0) || (count > endIndex - index)) {
  73853. throw "HDR Bad Format, bad scanline data (run)";
  73854. }
  73855. while (count-- > 0) {
  73856. scanLineArray[index++] = b;
  73857. }
  73858. }
  73859. else {
  73860. // a non-run
  73861. count = a;
  73862. if ((count == 0) || (count > endIndex - index)) {
  73863. throw "HDR Bad Format, bad scanline data (non-run)";
  73864. }
  73865. scanLineArray[index++] = b;
  73866. if (--count > 0) {
  73867. for (var j = 0; j < count; j++) {
  73868. scanLineArray[index++] = uint8array[dataIndex++];
  73869. }
  73870. }
  73871. }
  73872. }
  73873. }
  73874. // now convert data from buffer into floats
  73875. for (i = 0; i < scanline_width; i++) {
  73876. a = scanLineArray[i];
  73877. b = scanLineArray[i + scanline_width];
  73878. c = scanLineArray[i + 2 * scanline_width];
  73879. d = scanLineArray[i + 3 * scanline_width];
  73880. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  73881. }
  73882. num_scanlines--;
  73883. }
  73884. return resultArray;
  73885. };
  73886. return HDRTools;
  73887. }());
  73888. BABYLON.HDRTools = HDRTools;
  73889. })(BABYLON || (BABYLON = {}));
  73890. //# sourceMappingURL=babylon.hdr.js.map
  73891. var BABYLON;
  73892. (function (BABYLON) {
  73893. /**
  73894. * This represents a texture coming from an HDR input.
  73895. *
  73896. * The only supported format is currently panorama picture stored in RGBE format.
  73897. * Example of such files can be found on HDRLib: http://hdrlib.com/
  73898. */
  73899. var HDRCubeTexture = /** @class */ (function (_super) {
  73900. __extends(HDRCubeTexture, _super);
  73901. /**
  73902. * Instantiates an HDRTexture from the following parameters.
  73903. *
  73904. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  73905. * @param scene The scene the texture will be used in
  73906. * @param size The cubemap desired size (the more it increases the longer the generation will be) If the size is omitted this implies you are using a preprocessed cubemap.
  73907. * @param noMipmap Forces to not generate the mipmap if true
  73908. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  73909. * @param useInGammaSpace Specifies if the texture will be use in gamma or linear space (the PBR material requires those texture in linear space, but the standard material would require them in Gamma space)
  73910. * @param usePMREMGenerator Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  73911. */
  73912. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  73913. if (noMipmap === void 0) { noMipmap = false; }
  73914. if (generateHarmonics === void 0) { generateHarmonics = true; }
  73915. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  73916. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  73917. if (onLoad === void 0) { onLoad = null; }
  73918. if (onError === void 0) { onError = null; }
  73919. var _this = _super.call(this, scene) || this;
  73920. _this._useInGammaSpace = false;
  73921. _this._generateHarmonics = true;
  73922. _this._isBABYLONPreprocessed = false;
  73923. _this._onLoad = null;
  73924. _this._onError = null;
  73925. /**
  73926. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  73927. */
  73928. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  73929. /**
  73930. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  73931. * This is usefull at run time to apply the good shader.
  73932. */
  73933. _this.isPMREM = false;
  73934. _this._isBlocking = true;
  73935. /**
  73936. * Gets or sets the center of the bounding box associated with the cube texture
  73937. * It must define where the camera used to render the texture was set
  73938. */
  73939. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  73940. if (!url) {
  73941. return _this;
  73942. }
  73943. _this.name = url;
  73944. _this.url = url;
  73945. _this.hasAlpha = false;
  73946. _this.isCube = true;
  73947. _this._textureMatrix = BABYLON.Matrix.Identity();
  73948. _this._onLoad = onLoad;
  73949. _this._onError = onError;
  73950. _this.gammaSpace = false;
  73951. var caps = scene.getEngine().getCaps();
  73952. if (size) {
  73953. _this._isBABYLONPreprocessed = false;
  73954. _this._noMipmap = noMipmap;
  73955. _this._size = size;
  73956. _this._useInGammaSpace = useInGammaSpace;
  73957. _this._usePMREMGenerator = usePMREMGenerator &&
  73958. caps.textureLOD &&
  73959. caps.textureFloat &&
  73960. !_this._useInGammaSpace;
  73961. }
  73962. else {
  73963. _this._isBABYLONPreprocessed = true;
  73964. _this._noMipmap = false;
  73965. _this._useInGammaSpace = false;
  73966. _this._usePMREMGenerator = caps.textureLOD && caps.textureFloat &&
  73967. !_this._useInGammaSpace;
  73968. }
  73969. _this.isPMREM = _this._usePMREMGenerator;
  73970. _this._texture = _this._getFromCache(url, _this._noMipmap);
  73971. if (!_this._texture) {
  73972. if (!scene.useDelayedTextureLoading) {
  73973. _this.loadTexture();
  73974. }
  73975. else {
  73976. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  73977. }
  73978. }
  73979. return _this;
  73980. }
  73981. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  73982. /**
  73983. * Gets wether or not the texture is blocking during loading.
  73984. */
  73985. get: function () {
  73986. return this._isBlocking;
  73987. },
  73988. /**
  73989. * Sets wether or not the texture is blocking during loading.
  73990. */
  73991. set: function (value) {
  73992. this._isBlocking = value;
  73993. },
  73994. enumerable: true,
  73995. configurable: true
  73996. });
  73997. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  73998. get: function () {
  73999. return this._boundingBoxSize;
  74000. },
  74001. /**
  74002. * Gets or sets the size of the bounding box associated with the cube texture
  74003. * When defined, the cubemap will switch to local mode
  74004. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  74005. * @example https://www.babylonjs-playground.com/#RNASML
  74006. */
  74007. set: function (value) {
  74008. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  74009. return;
  74010. }
  74011. this._boundingBoxSize = value;
  74012. var scene = this.getScene();
  74013. if (scene) {
  74014. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  74015. }
  74016. },
  74017. enumerable: true,
  74018. configurable: true
  74019. });
  74020. /**
  74021. * Occurs when the file is a preprocessed .babylon.hdr file.
  74022. */
  74023. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  74024. var _this = this;
  74025. var mipLevels = 0;
  74026. var floatArrayView = null;
  74027. var scene = this.getScene();
  74028. var mipmapGenerator = (!this._useInGammaSpace && scene && scene.getEngine().getCaps().textureFloat) ? function (data) {
  74029. var mips = new Array();
  74030. if (!floatArrayView) {
  74031. return mips;
  74032. }
  74033. var startIndex = 30;
  74034. for (var level = 0; level < mipLevels; level++) {
  74035. mips.push([]);
  74036. // Fill each pixel of the mip level.
  74037. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  74038. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  74039. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  74040. mips[level].push(faceData);
  74041. startIndex += faceSize;
  74042. }
  74043. }
  74044. return mips;
  74045. } : null;
  74046. var callback = function (buffer) {
  74047. var scene = _this.getScene();
  74048. if (!scene) {
  74049. return null;
  74050. }
  74051. // Create Native Array Views
  74052. var intArrayView = new Int32Array(buffer);
  74053. floatArrayView = new Float32Array(buffer);
  74054. // Fill header.
  74055. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  74056. _this._size = intArrayView[1]; // CubeMap max mip face size.
  74057. // Update Texture Information.
  74058. if (!_this._texture) {
  74059. return null;
  74060. }
  74061. _this._texture.updateSize(_this._size, _this._size);
  74062. // Fill polynomial information.
  74063. var sphericalPolynomial = new BABYLON.SphericalPolynomial();
  74064. sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  74065. sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  74066. sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  74067. sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  74068. sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  74069. sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  74070. sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  74071. sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  74072. sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  74073. _this.sphericalPolynomial = sphericalPolynomial;
  74074. // Fill pixel data.
  74075. mipLevels = intArrayView[29]; // Number of mip levels.
  74076. var startIndex = 30;
  74077. var data = [];
  74078. var faceSize = Math.pow(_this._size, 2) * 3;
  74079. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  74080. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  74081. startIndex += faceSize;
  74082. }
  74083. var results = [];
  74084. var byteArray = null;
  74085. // Push each faces.
  74086. for (var k = 0; k < 6; k++) {
  74087. var dataFace = null;
  74088. // To be deprecated.
  74089. if (version === 1) {
  74090. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y...
  74091. dataFace = data[j];
  74092. }
  74093. // If special cases.
  74094. if (!mipmapGenerator && dataFace) {
  74095. if (!scene.getEngine().getCaps().textureFloat) {
  74096. // 3 channels of 1 bytes per pixel in bytes.
  74097. var byteBuffer = new ArrayBuffer(faceSize);
  74098. byteArray = new Uint8Array(byteBuffer);
  74099. }
  74100. for (var i = 0; i < _this._size * _this._size; i++) {
  74101. // Put in gamma space if requested.
  74102. if (_this._useInGammaSpace) {
  74103. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  74104. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  74105. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  74106. }
  74107. // Convert to int texture for fallback.
  74108. if (byteArray) {
  74109. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  74110. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  74111. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  74112. // May use luminance instead if the result is not accurate.
  74113. var max = Math.max(Math.max(r, g), b);
  74114. if (max > 255) {
  74115. var scale = 255 / max;
  74116. r *= scale;
  74117. g *= scale;
  74118. b *= scale;
  74119. }
  74120. byteArray[(i * 3) + 0] = r;
  74121. byteArray[(i * 3) + 1] = g;
  74122. byteArray[(i * 3) + 2] = b;
  74123. }
  74124. }
  74125. }
  74126. // Fill the array accordingly.
  74127. if (byteArray) {
  74128. results.push(byteArray);
  74129. }
  74130. else {
  74131. results.push(dataFace);
  74132. }
  74133. }
  74134. return results;
  74135. };
  74136. if (scene) {
  74137. this._texture = scene.getEngine().createRawCubeTextureFromUrl(this.url, scene, this._size, BABYLON.Engine.TEXTUREFORMAT_RGB, scene.getEngine().getCaps().textureFloat ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, this._noMipmap, callback, mipmapGenerator, this._onLoad, this._onError);
  74138. }
  74139. };
  74140. /**
  74141. * Occurs when the file is raw .hdr file.
  74142. */
  74143. HDRCubeTexture.prototype.loadHDRTexture = function () {
  74144. var _this = this;
  74145. var callback = function (buffer) {
  74146. var scene = _this.getScene();
  74147. if (!scene) {
  74148. return null;
  74149. }
  74150. // Extract the raw linear data.
  74151. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  74152. // Generate harmonics if needed.
  74153. if (_this._generateHarmonics) {
  74154. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  74155. _this.sphericalPolynomial = sphericalPolynomial;
  74156. }
  74157. var results = [];
  74158. var byteArray = null;
  74159. // Push each faces.
  74160. for (var j = 0; j < 6; j++) {
  74161. // Create uintarray fallback.
  74162. if (!scene.getEngine().getCaps().textureFloat) {
  74163. // 3 channels of 1 bytes per pixel in bytes.
  74164. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  74165. byteArray = new Uint8Array(byteBuffer);
  74166. }
  74167. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  74168. // If special cases.
  74169. if (_this._useInGammaSpace || byteArray) {
  74170. for (var i = 0; i < _this._size * _this._size; i++) {
  74171. // Put in gamma space if requested.
  74172. if (_this._useInGammaSpace) {
  74173. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  74174. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  74175. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  74176. }
  74177. // Convert to int texture for fallback.
  74178. if (byteArray) {
  74179. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  74180. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  74181. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  74182. // May use luminance instead if the result is not accurate.
  74183. var max = Math.max(Math.max(r, g), b);
  74184. if (max > 255) {
  74185. var scale = 255 / max;
  74186. r *= scale;
  74187. g *= scale;
  74188. b *= scale;
  74189. }
  74190. byteArray[(i * 3) + 0] = r;
  74191. byteArray[(i * 3) + 1] = g;
  74192. byteArray[(i * 3) + 2] = b;
  74193. }
  74194. }
  74195. }
  74196. if (byteArray) {
  74197. results.push(byteArray);
  74198. }
  74199. else {
  74200. results.push(dataFace);
  74201. }
  74202. }
  74203. return results;
  74204. };
  74205. var mipmapGenerator = null;
  74206. // TODO. Implement In code PMREM Generator following the LYS toolset generation.
  74207. // if (!this._noMipmap &&
  74208. // this._usePMREMGenerator) {
  74209. // mipmapGenerator = (data: ArrayBufferView[]) => {
  74210. // // Custom setup of the generator matching with the PBR shader values.
  74211. // var generator = new BABYLON.PMREMGenerator(data,
  74212. // this._size,
  74213. // this._size,
  74214. // 0,
  74215. // 3,
  74216. // this.getScene().getEngine().getCaps().textureFloat,
  74217. // 2048,
  74218. // 0.25,
  74219. // false,
  74220. // true);
  74221. // return generator.filterCubeMap();
  74222. // };
  74223. // }
  74224. var scene = this.getScene();
  74225. if (scene) {
  74226. this._texture = scene.getEngine().createRawCubeTextureFromUrl(this.url, scene, this._size, BABYLON.Engine.TEXTUREFORMAT_RGB, scene.getEngine().getCaps().textureFloat ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, this._noMipmap, callback, mipmapGenerator, this._onLoad, this._onError);
  74227. }
  74228. };
  74229. /**
  74230. * Starts the loading process of the texture.
  74231. */
  74232. HDRCubeTexture.prototype.loadTexture = function () {
  74233. if (this._isBABYLONPreprocessed) {
  74234. this.loadBabylonTexture();
  74235. }
  74236. else {
  74237. this.loadHDRTexture();
  74238. }
  74239. };
  74240. HDRCubeTexture.prototype.clone = function () {
  74241. var scene = this.getScene();
  74242. if (!scene) {
  74243. return this;
  74244. }
  74245. var size = (this._isBABYLONPreprocessed ? null : this._size);
  74246. var newTexture = new HDRCubeTexture(this.url, scene, size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  74247. // Base texture
  74248. newTexture.level = this.level;
  74249. newTexture.wrapU = this.wrapU;
  74250. newTexture.wrapV = this.wrapV;
  74251. newTexture.coordinatesIndex = this.coordinatesIndex;
  74252. newTexture.coordinatesMode = this.coordinatesMode;
  74253. return newTexture;
  74254. };
  74255. // Methods
  74256. HDRCubeTexture.prototype.delayLoad = function () {
  74257. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  74258. return;
  74259. }
  74260. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  74261. this._texture = this._getFromCache(this.url, this._noMipmap);
  74262. if (!this._texture) {
  74263. this.loadTexture();
  74264. }
  74265. };
  74266. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  74267. return this._textureMatrix;
  74268. };
  74269. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  74270. this._textureMatrix = value;
  74271. };
  74272. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  74273. var texture = null;
  74274. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  74275. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  74276. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  74277. texture.name = parsedTexture.name;
  74278. texture.hasAlpha = parsedTexture.hasAlpha;
  74279. texture.level = parsedTexture.level;
  74280. texture.coordinatesMode = parsedTexture.coordinatesMode;
  74281. texture.isBlocking = parsedTexture.isBlocking;
  74282. }
  74283. if (texture) {
  74284. if (parsedTexture.boundingBoxPosition) {
  74285. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  74286. }
  74287. if (parsedTexture.boundingBoxSize) {
  74288. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  74289. }
  74290. }
  74291. return texture;
  74292. };
  74293. HDRCubeTexture.prototype.serialize = function () {
  74294. if (!this.name) {
  74295. return null;
  74296. }
  74297. var serializationObject = {};
  74298. serializationObject.name = this.name;
  74299. serializationObject.hasAlpha = this.hasAlpha;
  74300. serializationObject.isCube = true;
  74301. serializationObject.level = this.level;
  74302. serializationObject.size = this._size;
  74303. serializationObject.coordinatesMode = this.coordinatesMode;
  74304. serializationObject.useInGammaSpace = this._useInGammaSpace;
  74305. serializationObject.generateHarmonics = this._generateHarmonics;
  74306. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  74307. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  74308. serializationObject.customType = "BABYLON.HDRCubeTexture";
  74309. serializationObject.noMipmap = this._noMipmap;
  74310. serializationObject.isBlocking = this._isBlocking;
  74311. return serializationObject;
  74312. };
  74313. /**
  74314. * Saves as a file the data contained in the texture in a binary format.
  74315. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  74316. * as the spherical used in the lighting.
  74317. * @param url The HDR file url.
  74318. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  74319. * @param onError Method called if any error happens during download.
  74320. * @return The packed binary data.
  74321. */
  74322. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  74323. if (onError === void 0) { onError = null; }
  74324. var callback = function (buffer) {
  74325. var data = new Blob([buffer], { type: 'application/octet-stream' });
  74326. // Returns a URL you can use as a href.
  74327. var objUrl = window.URL.createObjectURL(data);
  74328. // Simulates a link to it and click to dowload.
  74329. var a = document.createElement("a");
  74330. document.body.appendChild(a);
  74331. a.style.display = "none";
  74332. a.href = objUrl;
  74333. a.download = "envmap.babylon.hdr";
  74334. a.click();
  74335. };
  74336. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  74337. };
  74338. /**
  74339. * Serializes the data contained in the texture in a binary format.
  74340. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  74341. * as the spherical used in the lighting.
  74342. * @param url The HDR file url.
  74343. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  74344. * @param onError Method called if any error happens during download.
  74345. * @return The packed binary data.
  74346. */
  74347. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  74348. if (onError === void 0) { onError = null; }
  74349. // Needs the url tho create the texture.
  74350. if (!url) {
  74351. return;
  74352. }
  74353. // Check Power of two size.
  74354. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  74355. return;
  74356. }
  74357. // Coming Back in 3.x.
  74358. BABYLON.Tools.Error("Generation of Babylon HDR is coming back in 3.2.");
  74359. };
  74360. HDRCubeTexture._facesMapping = [
  74361. "right",
  74362. "left",
  74363. "up",
  74364. "down",
  74365. "front",
  74366. "back"
  74367. ];
  74368. return HDRCubeTexture;
  74369. }(BABYLON.BaseTexture));
  74370. BABYLON.HDRCubeTexture = HDRCubeTexture;
  74371. })(BABYLON || (BABYLON = {}));
  74372. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  74373. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  74374. // Huge respect for a such great lib.
  74375. // Earcut license:
  74376. // Copyright (c) 2016, Mapbox
  74377. //
  74378. // Permission to use, copy, modify, and/or distribute this software for any purpose
  74379. // with or without fee is hereby granted, provided that the above copyright notice
  74380. // and this permission notice appear in all copies.
  74381. //
  74382. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  74383. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  74384. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  74385. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  74386. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  74387. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  74388. // THIS SOFTWARE.
  74389. var Earcut;
  74390. (function (Earcut) {
  74391. /**
  74392. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  74393. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  74394. * @param holeIndices is an array of hole indices if any (e.g. [5, 8] for a 12- vertice input would mean one hole with vertices 5–7 and another with 8–11).
  74395. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  74396. */
  74397. function earcut(data, holeIndices, dim) {
  74398. dim = dim || 2;
  74399. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = new Array();
  74400. if (!outerNode)
  74401. return triangles;
  74402. var minX = 0, minY = 0, maxX, maxY, x, y, size = 0;
  74403. if (hasHoles)
  74404. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  74405. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  74406. if (data.length > 80 * dim) {
  74407. minX = maxX = data[0];
  74408. minY = maxY = data[1];
  74409. for (var i = dim; i < outerLen; i += dim) {
  74410. x = data[i];
  74411. y = data[i + 1];
  74412. if (x < minX)
  74413. minX = x;
  74414. if (y < minY)
  74415. minY = y;
  74416. if (x > maxX)
  74417. maxX = x;
  74418. if (y > maxY)
  74419. maxY = y;
  74420. }
  74421. // minX, minY and size are later used to transform coords into integers for z-order calculation
  74422. size = Math.max(maxX - minX, maxY - minY);
  74423. }
  74424. earcutLinked(outerNode, triangles, dim, minX, minY, size, 0);
  74425. return triangles;
  74426. }
  74427. Earcut.earcut = earcut;
  74428. var Node = /** @class */ (function () {
  74429. function Node(i, x, y) {
  74430. this.i = i;
  74431. this.x = x;
  74432. this.y = y;
  74433. this.prev = null;
  74434. this.next = null;
  74435. this.z = null;
  74436. this.prevZ = null;
  74437. this.nextZ = null;
  74438. this.steiner = false;
  74439. }
  74440. return Node;
  74441. }());
  74442. // create a circular doubly linked list from polygon points in the specified winding order
  74443. function linkedList(data, start, end, dim, clockwise) {
  74444. var i, last = null;
  74445. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  74446. for (i = start; i < end; i += dim)
  74447. last = insertNode(i, data[i], data[i + 1], last);
  74448. }
  74449. else {
  74450. for (i = end - dim; i >= start; i -= dim)
  74451. last = insertNode(i, data[i], data[i + 1], last);
  74452. }
  74453. if (last && equals(last, last.next)) {
  74454. removeNode(last);
  74455. last = last.next;
  74456. }
  74457. return last;
  74458. }
  74459. // eliminate colinear or duplicate points
  74460. function filterPoints(start, end) {
  74461. if (!start)
  74462. return start;
  74463. if (!end)
  74464. end = start;
  74465. var p = start, again;
  74466. do {
  74467. again = false;
  74468. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  74469. removeNode(p);
  74470. p = end = p.prev;
  74471. if (p === p.next)
  74472. return undefined;
  74473. again = true;
  74474. }
  74475. else {
  74476. p = p.next;
  74477. }
  74478. } while (again || p !== end);
  74479. return end;
  74480. }
  74481. // main ear slicing loop which triangulates a polygon (given as a linked list)
  74482. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  74483. if (!ear)
  74484. return;
  74485. // interlink polygon nodes in z-order
  74486. if (!pass && size)
  74487. indexCurve(ear, minX, minY, size);
  74488. var stop = ear, prev, next;
  74489. // iterate through ears, slicing them one by one
  74490. while (ear.prev !== ear.next) {
  74491. prev = ear.prev;
  74492. next = ear.next;
  74493. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  74494. // cut off the triangle
  74495. triangles.push(prev.i / dim);
  74496. triangles.push(ear.i / dim);
  74497. triangles.push(next.i / dim);
  74498. removeNode(ear);
  74499. // skipping the next vertice leads to less sliver triangles
  74500. ear = next.next;
  74501. stop = next.next;
  74502. continue;
  74503. }
  74504. ear = next;
  74505. // if we looped through the whole remaining polygon and can't find any more ears
  74506. if (ear === stop) {
  74507. // try filtering points and slicing again
  74508. if (!pass) {
  74509. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  74510. // if this didn't work, try curing all small self-intersections locally
  74511. }
  74512. else if (pass === 1) {
  74513. ear = cureLocalIntersections(ear, triangles, dim);
  74514. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  74515. // as a last resort, try splitting the remaining polygon into two
  74516. }
  74517. else if (pass === 2) {
  74518. splitEarcut(ear, triangles, dim, minX, minY, size);
  74519. }
  74520. break;
  74521. }
  74522. }
  74523. }
  74524. // check whether a polygon node forms a valid ear with adjacent nodes
  74525. function isEar(ear) {
  74526. var a = ear.prev, b = ear, c = ear.next;
  74527. if (area(a, b, c) >= 0)
  74528. return false; // reflex, can't be an ear
  74529. // now make sure we don't have other points inside the potential ear
  74530. var p = ear.next.next;
  74531. while (p !== ear.prev) {
  74532. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  74533. area(p.prev, p, p.next) >= 0)
  74534. return false;
  74535. p = p.next;
  74536. }
  74537. return true;
  74538. }
  74539. function isEarHashed(ear, minX, minY, size) {
  74540. var a = ear.prev, b = ear, c = ear.next;
  74541. if (area(a, b, c) >= 0)
  74542. return false; // reflex, can't be an ear
  74543. // triangle bbox; min & max are calculated like this for speed
  74544. var minTX = a.x < b.x ? (a.x < c.x ? a.x : c.x) : (b.x < c.x ? b.x : c.x), minTY = a.y < b.y ? (a.y < c.y ? a.y : c.y) : (b.y < c.y ? b.y : c.y), maxTX = a.x > b.x ? (a.x > c.x ? a.x : c.x) : (b.x > c.x ? b.x : c.x), maxTY = a.y > b.y ? (a.y > c.y ? a.y : c.y) : (b.y > c.y ? b.y : c.y);
  74545. // z-order range for the current triangle bbox;
  74546. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  74547. // first look for points inside the triangle in increasing z-order
  74548. var p = ear.nextZ;
  74549. while (p && p.z <= maxZ) {
  74550. if (p !== ear.prev &&
  74551. p !== ear.next &&
  74552. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  74553. area(p.prev, p, p.next) >= 0)
  74554. return false;
  74555. p = p.nextZ;
  74556. }
  74557. // then look for points in decreasing z-order
  74558. p = ear.prevZ;
  74559. while (p && p.z >= minZ) {
  74560. if (p !== ear.prev &&
  74561. p !== ear.next &&
  74562. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  74563. area(p.prev, p, p.next) >= 0)
  74564. return false;
  74565. p = p.prevZ;
  74566. }
  74567. return true;
  74568. }
  74569. // go through all polygon nodes and cure small local self-intersections
  74570. function cureLocalIntersections(start, triangles, dim) {
  74571. var p = start;
  74572. do {
  74573. var a = p.prev, b = p.next.next;
  74574. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  74575. triangles.push(a.i / dim);
  74576. triangles.push(p.i / dim);
  74577. triangles.push(b.i / dim);
  74578. // remove two nodes involved
  74579. removeNode(p);
  74580. removeNode(p.next);
  74581. p = start = b;
  74582. }
  74583. p = p.next;
  74584. } while (p !== start);
  74585. return p;
  74586. }
  74587. // try splitting polygon into two and triangulate them independently
  74588. function splitEarcut(start, triangles, dim, minX, minY, size) {
  74589. // look for a valid diagonal that divides the polygon into two
  74590. var a = start;
  74591. do {
  74592. var b = a.next.next;
  74593. while (b !== a.prev) {
  74594. if (a.i !== b.i && isValidDiagonal(a, b)) {
  74595. // split the polygon in two by the diagonal
  74596. var c = splitPolygon(a, b);
  74597. // filter colinear points around the cuts
  74598. a = filterPoints(a, a.next);
  74599. c = filterPoints(c, c.next);
  74600. // run earcut on each half
  74601. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  74602. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  74603. return;
  74604. }
  74605. b = b.next;
  74606. }
  74607. a = a.next;
  74608. } while (a !== start);
  74609. }
  74610. // link every hole into the outer loop, producing a single-ring polygon without holes
  74611. function eliminateHoles(data, holeIndices, outerNode, dim) {
  74612. var queue = [], i, len, start, end, list;
  74613. for (i = 0, len = holeIndices.length; i < len; i++) {
  74614. start = holeIndices[i] * dim;
  74615. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  74616. list = linkedList(data, start, end, dim, false);
  74617. if (list === list.next)
  74618. list.steiner = true;
  74619. queue.push(getLeftmost(list));
  74620. }
  74621. queue.sort(compareX);
  74622. // process holes from left to right
  74623. for (i = 0; i < queue.length; i++) {
  74624. eliminateHole(queue[i], outerNode);
  74625. outerNode = filterPoints(outerNode, outerNode.next);
  74626. }
  74627. return outerNode;
  74628. }
  74629. function compareX(a, b) {
  74630. return a.x - b.x;
  74631. }
  74632. // find a bridge between vertices that connects hole with an outer ring and and link it
  74633. function eliminateHole(hole, outerNode) {
  74634. outerNode = findHoleBridge(hole, outerNode);
  74635. if (outerNode) {
  74636. var b = splitPolygon(outerNode, hole);
  74637. filterPoints(b, b.next);
  74638. }
  74639. }
  74640. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  74641. function findHoleBridge(hole, outerNode) {
  74642. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  74643. // find a segment intersected by a ray from the hole's leftmost point to the left;
  74644. // segment's endpoint with lesser x will be potential connection point
  74645. do {
  74646. if (hy <= p.y && hy >= p.next.y) {
  74647. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  74648. if (x <= hx && x > qx) {
  74649. qx = x;
  74650. if (x === hx) {
  74651. if (hy === p.y)
  74652. return p;
  74653. if (hy === p.next.y)
  74654. return p.next;
  74655. }
  74656. m = p.x < p.next.x ? p : p.next;
  74657. }
  74658. }
  74659. p = p.next;
  74660. } while (p !== outerNode);
  74661. if (!m)
  74662. return null;
  74663. if (hx === qx)
  74664. return m.prev; // hole touches outer segment; pick lower endpoint
  74665. // look for points inside the triangle of hole point, segment intersection and endpoint;
  74666. // if there are no points found, we have a valid connection;
  74667. // otherwise choose the point of the minimum angle with the ray as connection point
  74668. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  74669. p = m.next;
  74670. while (p !== stop) {
  74671. if (hx >= p.x &&
  74672. p.x >= mx &&
  74673. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  74674. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  74675. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  74676. m = p;
  74677. tanMin = tan;
  74678. }
  74679. }
  74680. p = p.next;
  74681. }
  74682. return m;
  74683. }
  74684. // interlink polygon nodes in z-order
  74685. function indexCurve(start, minX, minY, size) {
  74686. var p = start;
  74687. do {
  74688. if (p.z === null)
  74689. p.z = zOrder(p.x, p.y, minX, minY, size);
  74690. p.prevZ = p.prev;
  74691. p.nextZ = p.next;
  74692. p = p.next;
  74693. } while (p !== start);
  74694. p.prevZ.nextZ = null;
  74695. p.prevZ = null;
  74696. sortLinked(p);
  74697. }
  74698. // Simon Tatham's linked list merge sort algorithm
  74699. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  74700. function sortLinked(list) {
  74701. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  74702. do {
  74703. p = list;
  74704. list = null;
  74705. tail = null;
  74706. numMerges = 0;
  74707. while (p) {
  74708. numMerges++;
  74709. q = p;
  74710. pSize = 0;
  74711. for (i = 0; i < inSize; i++) {
  74712. pSize++;
  74713. q = q.nextZ;
  74714. if (!q)
  74715. break;
  74716. }
  74717. qSize = inSize;
  74718. while (pSize > 0 || (qSize > 0 && q)) {
  74719. if (pSize === 0) {
  74720. e = q;
  74721. q = q.nextZ;
  74722. qSize--;
  74723. }
  74724. else if (qSize === 0 || !q) {
  74725. e = p;
  74726. p = p.nextZ;
  74727. pSize--;
  74728. }
  74729. else if (p.z <= q.z) {
  74730. e = p;
  74731. p = p.nextZ;
  74732. pSize--;
  74733. }
  74734. else {
  74735. e = q;
  74736. q = q.nextZ;
  74737. qSize--;
  74738. }
  74739. if (tail)
  74740. tail.nextZ = e;
  74741. else
  74742. list = e;
  74743. e.prevZ = tail;
  74744. tail = e;
  74745. }
  74746. p = q;
  74747. }
  74748. tail.nextZ = null;
  74749. inSize *= 2;
  74750. } while (numMerges > 1);
  74751. return list;
  74752. }
  74753. // z-order of a point given coords and size of the data bounding box
  74754. function zOrder(x, y, minX, minY, size) {
  74755. // coords are transformed into non-negative 15-bit integer range
  74756. x = 32767 * (x - minX) / size;
  74757. y = 32767 * (y - minY) / size;
  74758. x = (x | (x << 8)) & 0x00FF00FF;
  74759. x = (x | (x << 4)) & 0x0F0F0F0F;
  74760. x = (x | (x << 2)) & 0x33333333;
  74761. x = (x | (x << 1)) & 0x55555555;
  74762. y = (y | (y << 8)) & 0x00FF00FF;
  74763. y = (y | (y << 4)) & 0x0F0F0F0F;
  74764. y = (y | (y << 2)) & 0x33333333;
  74765. y = (y | (y << 1)) & 0x55555555;
  74766. return x | (y << 1);
  74767. }
  74768. // find the leftmost node of a polygon ring
  74769. function getLeftmost(start) {
  74770. var p = start, leftmost = start;
  74771. do {
  74772. if (p.x < leftmost.x)
  74773. leftmost = p;
  74774. p = p.next;
  74775. } while (p !== start);
  74776. return leftmost;
  74777. }
  74778. // check if a point lies within a convex triangle
  74779. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  74780. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  74781. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  74782. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  74783. }
  74784. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  74785. function isValidDiagonal(a, b) {
  74786. return a.next.i !== b.i &&
  74787. a.prev.i !== b.i &&
  74788. !intersectsPolygon(a, b) &&
  74789. locallyInside(a, b) &&
  74790. locallyInside(b, a) &&
  74791. middleInside(a, b);
  74792. }
  74793. // signed area of a triangle
  74794. function area(p, q, r) {
  74795. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  74796. }
  74797. // check if two points are equal
  74798. function equals(p1, p2) {
  74799. return p1.x === p2.x && p1.y === p2.y;
  74800. }
  74801. // check if two segments intersect
  74802. function intersects(p1, q1, p2, q2) {
  74803. if ((equals(p1, q1) && equals(p2, q2)) ||
  74804. (equals(p1, q2) && equals(p2, q1)))
  74805. return true;
  74806. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  74807. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  74808. }
  74809. // check if a polygon diagonal intersects any polygon segments
  74810. function intersectsPolygon(a, b) {
  74811. var p = a;
  74812. do {
  74813. if (p.i !== a.i &&
  74814. p.next.i !== a.i &&
  74815. p.i !== b.i &&
  74816. p.next.i !== b.i &&
  74817. intersects(p, p.next, a, b))
  74818. return true;
  74819. p = p.next;
  74820. } while (p !== a);
  74821. return false;
  74822. }
  74823. // check if a polygon diagonal is locally inside the polygon
  74824. function locallyInside(a, b) {
  74825. return area(a.prev, a, a.next) < 0
  74826. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  74827. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  74828. }
  74829. // check if the middle point of a polygon diagonal is inside the polygon
  74830. function middleInside(a, b) {
  74831. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  74832. do {
  74833. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  74834. inside = !inside;
  74835. p = p.next;
  74836. } while (p !== a);
  74837. return inside;
  74838. }
  74839. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  74840. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  74841. function splitPolygon(a, b) {
  74842. var a2 = new Node(a.i, a.x, a.y), b2 = new Node(b.i, b.x, b.y), an = a.next, bp = b.prev;
  74843. a.next = b;
  74844. b.prev = a;
  74845. a2.next = an;
  74846. an.prev = a2;
  74847. b2.next = a2;
  74848. a2.prev = b2;
  74849. bp.next = b2;
  74850. b2.prev = bp;
  74851. return b2;
  74852. }
  74853. // create a node and optionally link it with previous one (in a circular doubly linked list)
  74854. function insertNode(i, x, y, last) {
  74855. var p = new Node(i, x, y);
  74856. if (!last) {
  74857. p.prev = p;
  74858. p.next = p;
  74859. }
  74860. else {
  74861. p.next = last.next;
  74862. p.prev = last;
  74863. last.next.prev = p;
  74864. last.next = p;
  74865. }
  74866. return p;
  74867. }
  74868. function removeNode(p) {
  74869. p.next.prev = p.prev;
  74870. p.prev.next = p.next;
  74871. if (p.prevZ)
  74872. p.prevZ.nextZ = p.nextZ;
  74873. if (p.nextZ)
  74874. p.nextZ.prevZ = p.prevZ;
  74875. }
  74876. /**
  74877. * return a percentage difference between the polygon area and its triangulation area;
  74878. * used to verify correctness of triangulation
  74879. */
  74880. function deviation(data, holeIndices, dim, triangles) {
  74881. var hasHoles = holeIndices && holeIndices.length;
  74882. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  74883. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  74884. if (hasHoles) {
  74885. for (var i = 0, len = holeIndices.length; i < len; i++) {
  74886. var start = holeIndices[i] * dim;
  74887. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  74888. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  74889. }
  74890. }
  74891. var trianglesArea = 0;
  74892. for (i = 0; i < triangles.length; i += 3) {
  74893. var a = triangles[i] * dim;
  74894. var b = triangles[i + 1] * dim;
  74895. var c = triangles[i + 2] * dim;
  74896. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  74897. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  74898. }
  74899. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  74900. }
  74901. Earcut.deviation = deviation;
  74902. ;
  74903. function signedArea(data, start, end, dim) {
  74904. var sum = 0;
  74905. for (var i = start, j = end - dim; i < end; i += dim) {
  74906. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  74907. j = i;
  74908. }
  74909. return sum;
  74910. }
  74911. /**
  74912. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  74913. */
  74914. function flatten(data) {
  74915. var dim = data[0][0].length, result = { vertices: new Array(), holes: new Array(), dimensions: dim }, holeIndex = 0;
  74916. for (var i = 0; i < data.length; i++) {
  74917. for (var j = 0; j < data[i].length; j++) {
  74918. for (var d = 0; d < dim; d++)
  74919. result.vertices.push(data[i][j][d]);
  74920. }
  74921. if (i > 0) {
  74922. holeIndex += data[i - 1].length;
  74923. result.holes.push(holeIndex);
  74924. }
  74925. }
  74926. return result;
  74927. }
  74928. Earcut.flatten = flatten;
  74929. ;
  74930. })(Earcut || (Earcut = {}));
  74931. //# sourceMappingURL=babylon.earcut.js.map
  74932. var BABYLON;
  74933. (function (BABYLON) {
  74934. var IndexedVector2 = /** @class */ (function (_super) {
  74935. __extends(IndexedVector2, _super);
  74936. function IndexedVector2(original, index) {
  74937. var _this = _super.call(this, original.x, original.y) || this;
  74938. _this.index = index;
  74939. return _this;
  74940. }
  74941. return IndexedVector2;
  74942. }(BABYLON.Vector2));
  74943. var PolygonPoints = /** @class */ (function () {
  74944. function PolygonPoints() {
  74945. this.elements = new Array();
  74946. }
  74947. PolygonPoints.prototype.add = function (originalPoints) {
  74948. var _this = this;
  74949. var result = new Array();
  74950. originalPoints.forEach(function (point) {
  74951. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  74952. var newPoint = new IndexedVector2(point, _this.elements.length);
  74953. result.push(newPoint);
  74954. _this.elements.push(newPoint);
  74955. }
  74956. });
  74957. return result;
  74958. };
  74959. PolygonPoints.prototype.computeBounds = function () {
  74960. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  74961. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  74962. this.elements.forEach(function (point) {
  74963. // x
  74964. if (point.x < lmin.x) {
  74965. lmin.x = point.x;
  74966. }
  74967. else if (point.x > lmax.x) {
  74968. lmax.x = point.x;
  74969. }
  74970. // y
  74971. if (point.y < lmin.y) {
  74972. lmin.y = point.y;
  74973. }
  74974. else if (point.y > lmax.y) {
  74975. lmax.y = point.y;
  74976. }
  74977. });
  74978. return {
  74979. min: lmin,
  74980. max: lmax,
  74981. width: lmax.x - lmin.x,
  74982. height: lmax.y - lmin.y
  74983. };
  74984. };
  74985. return PolygonPoints;
  74986. }());
  74987. var Polygon = /** @class */ (function () {
  74988. function Polygon() {
  74989. }
  74990. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  74991. return [
  74992. new BABYLON.Vector2(xmin, ymin),
  74993. new BABYLON.Vector2(xmax, ymin),
  74994. new BABYLON.Vector2(xmax, ymax),
  74995. new BABYLON.Vector2(xmin, ymax)
  74996. ];
  74997. };
  74998. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  74999. if (cx === void 0) { cx = 0; }
  75000. if (cy === void 0) { cy = 0; }
  75001. if (numberOfSides === void 0) { numberOfSides = 32; }
  75002. var result = new Array();
  75003. var angle = 0;
  75004. var increment = (Math.PI * 2) / numberOfSides;
  75005. for (var i = 0; i < numberOfSides; i++) {
  75006. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  75007. angle -= increment;
  75008. }
  75009. return result;
  75010. };
  75011. Polygon.Parse = function (input) {
  75012. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  75013. var i, result = [];
  75014. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  75015. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  75016. }
  75017. return result;
  75018. };
  75019. Polygon.StartingAt = function (x, y) {
  75020. return BABYLON.Path2.StartingAt(x, y);
  75021. };
  75022. return Polygon;
  75023. }());
  75024. BABYLON.Polygon = Polygon;
  75025. var PolygonMeshBuilder = /** @class */ (function () {
  75026. function PolygonMeshBuilder(name, contours, scene) {
  75027. this._points = new PolygonPoints();
  75028. this._outlinepoints = new PolygonPoints();
  75029. this._holes = new Array();
  75030. this._epoints = new Array();
  75031. this._eholes = new Array();
  75032. this._name = name;
  75033. this._scene = scene;
  75034. var points;
  75035. if (contours instanceof BABYLON.Path2) {
  75036. points = contours.getPoints();
  75037. }
  75038. else {
  75039. points = contours;
  75040. }
  75041. this._addToepoint(points);
  75042. this._points.add(points);
  75043. this._outlinepoints.add(points);
  75044. }
  75045. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  75046. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  75047. var p = points_1[_i];
  75048. this._epoints.push(p.x, p.y);
  75049. }
  75050. };
  75051. PolygonMeshBuilder.prototype.addHole = function (hole) {
  75052. this._points.add(hole);
  75053. var holepoints = new PolygonPoints();
  75054. holepoints.add(hole);
  75055. this._holes.push(holepoints);
  75056. this._eholes.push(this._epoints.length / 2);
  75057. this._addToepoint(hole);
  75058. return this;
  75059. };
  75060. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  75061. var _this = this;
  75062. if (updatable === void 0) { updatable = false; }
  75063. if (depth === void 0) { depth = 0; }
  75064. var result = new BABYLON.Mesh(this._name, this._scene);
  75065. var normals = new Array();
  75066. var positions = new Array();
  75067. var uvs = new Array();
  75068. var bounds = this._points.computeBounds();
  75069. this._points.elements.forEach(function (p) {
  75070. normals.push(0, 1.0, 0);
  75071. positions.push(p.x, 0, p.y);
  75072. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  75073. });
  75074. var indices = new Array();
  75075. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  75076. for (var i = 0; i < res.length; i++) {
  75077. indices.push(res[i]);
  75078. }
  75079. if (depth > 0) {
  75080. var positionscount = (positions.length / 3); //get the current pointcount
  75081. this._points.elements.forEach(function (p) {
  75082. normals.push(0, -1.0, 0);
  75083. positions.push(p.x, -depth, p.y);
  75084. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  75085. });
  75086. var totalCount = indices.length;
  75087. for (var i = 0; i < totalCount; i += 3) {
  75088. var i0 = indices[i + 0];
  75089. var i1 = indices[i + 1];
  75090. var i2 = indices[i + 2];
  75091. indices.push(i2 + positionscount);
  75092. indices.push(i1 + positionscount);
  75093. indices.push(i0 + positionscount);
  75094. }
  75095. //Add the sides
  75096. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  75097. this._holes.forEach(function (hole) {
  75098. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  75099. });
  75100. }
  75101. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  75102. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  75103. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  75104. result.setIndices(indices);
  75105. return result;
  75106. };
  75107. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  75108. var StartIndex = positions.length / 3;
  75109. var ulength = 0;
  75110. for (var i = 0; i < points.elements.length; i++) {
  75111. var p = points.elements[i];
  75112. var p1;
  75113. if ((i + 1) > points.elements.length - 1) {
  75114. p1 = points.elements[0];
  75115. }
  75116. else {
  75117. p1 = points.elements[i + 1];
  75118. }
  75119. positions.push(p.x, 0, p.y);
  75120. positions.push(p.x, -depth, p.y);
  75121. positions.push(p1.x, 0, p1.y);
  75122. positions.push(p1.x, -depth, p1.y);
  75123. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  75124. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  75125. var v3 = v2.subtract(v1);
  75126. var v4 = new BABYLON.Vector3(0, 1, 0);
  75127. var vn = BABYLON.Vector3.Cross(v3, v4);
  75128. vn = vn.normalize();
  75129. uvs.push(ulength / bounds.width, 0);
  75130. uvs.push(ulength / bounds.width, 1);
  75131. ulength += v3.length();
  75132. uvs.push((ulength / bounds.width), 0);
  75133. uvs.push((ulength / bounds.width), 1);
  75134. if (!flip) {
  75135. normals.push(-vn.x, -vn.y, -vn.z);
  75136. normals.push(-vn.x, -vn.y, -vn.z);
  75137. normals.push(-vn.x, -vn.y, -vn.z);
  75138. normals.push(-vn.x, -vn.y, -vn.z);
  75139. indices.push(StartIndex);
  75140. indices.push(StartIndex + 1);
  75141. indices.push(StartIndex + 2);
  75142. indices.push(StartIndex + 1);
  75143. indices.push(StartIndex + 3);
  75144. indices.push(StartIndex + 2);
  75145. }
  75146. else {
  75147. normals.push(vn.x, vn.y, vn.z);
  75148. normals.push(vn.x, vn.y, vn.z);
  75149. normals.push(vn.x, vn.y, vn.z);
  75150. normals.push(vn.x, vn.y, vn.z);
  75151. indices.push(StartIndex);
  75152. indices.push(StartIndex + 2);
  75153. indices.push(StartIndex + 1);
  75154. indices.push(StartIndex + 1);
  75155. indices.push(StartIndex + 2);
  75156. indices.push(StartIndex + 3);
  75157. }
  75158. StartIndex += 4;
  75159. }
  75160. ;
  75161. };
  75162. return PolygonMeshBuilder;
  75163. }());
  75164. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  75165. })(BABYLON || (BABYLON = {}));
  75166. //# sourceMappingURL=babylon.polygonMesh.js.map
  75167. var BABYLON;
  75168. (function (BABYLON) {
  75169. // Unique ID when we import meshes from Babylon to CSG
  75170. var currentCSGMeshId = 0;
  75171. // # class Vertex
  75172. // Represents a vertex of a polygon. Use your own vertex class instead of this
  75173. // one to provide additional features like texture coordinates and vertex
  75174. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  75175. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  75176. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  75177. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  75178. // is not used anywhere else.
  75179. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  75180. var Vertex = /** @class */ (function () {
  75181. function Vertex(pos, normal, uv) {
  75182. this.pos = pos;
  75183. this.normal = normal;
  75184. this.uv = uv;
  75185. }
  75186. Vertex.prototype.clone = function () {
  75187. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  75188. };
  75189. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  75190. // orientation of a polygon is flipped.
  75191. Vertex.prototype.flip = function () {
  75192. this.normal = this.normal.scale(-1);
  75193. };
  75194. // Create a new vertex between this vertex and `other` by linearly
  75195. // interpolating all properties using a parameter of `t`. Subclasses should
  75196. // override this to interpolate additional properties.
  75197. Vertex.prototype.interpolate = function (other, t) {
  75198. return new Vertex(BABYLON.Vector3.Lerp(this.pos, other.pos, t), BABYLON.Vector3.Lerp(this.normal, other.normal, t), BABYLON.Vector2.Lerp(this.uv, other.uv, t));
  75199. };
  75200. return Vertex;
  75201. }());
  75202. // # class Plane
  75203. // Represents a plane in 3D space.
  75204. var Plane = /** @class */ (function () {
  75205. function Plane(normal, w) {
  75206. this.normal = normal;
  75207. this.w = w;
  75208. }
  75209. Plane.FromPoints = function (a, b, c) {
  75210. var v0 = c.subtract(a);
  75211. var v1 = b.subtract(a);
  75212. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  75213. return null;
  75214. }
  75215. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  75216. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  75217. };
  75218. Plane.prototype.clone = function () {
  75219. return new Plane(this.normal.clone(), this.w);
  75220. };
  75221. Plane.prototype.flip = function () {
  75222. this.normal.scaleInPlace(-1);
  75223. this.w = -this.w;
  75224. };
  75225. // Split `polygon` by this plane if needed, then put the polygon or polygon
  75226. // fragments in the appropriate lists. Coplanar polygons go into either
  75227. // `coplanarFront` or `coplanarBack` depending on their orientation with
  75228. // respect to this plane. Polygons in front or in back of this plane go into
  75229. // either `front` or `back`.
  75230. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  75231. var COPLANAR = 0;
  75232. var FRONT = 1;
  75233. var BACK = 2;
  75234. var SPANNING = 3;
  75235. // Classify each point as well as the entire polygon into one of the above
  75236. // four classes.
  75237. var polygonType = 0;
  75238. var types = [];
  75239. var i;
  75240. var t;
  75241. for (i = 0; i < polygon.vertices.length; i++) {
  75242. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  75243. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  75244. polygonType |= type;
  75245. types.push(type);
  75246. }
  75247. // Put the polygon in the correct list, splitting it when necessary.
  75248. switch (polygonType) {
  75249. case COPLANAR:
  75250. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  75251. break;
  75252. case FRONT:
  75253. front.push(polygon);
  75254. break;
  75255. case BACK:
  75256. back.push(polygon);
  75257. break;
  75258. case SPANNING:
  75259. var f = [], b = [];
  75260. for (i = 0; i < polygon.vertices.length; i++) {
  75261. var j = (i + 1) % polygon.vertices.length;
  75262. var ti = types[i], tj = types[j];
  75263. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  75264. if (ti !== BACK)
  75265. f.push(vi);
  75266. if (ti !== FRONT)
  75267. b.push(ti !== BACK ? vi.clone() : vi);
  75268. if ((ti | tj) === SPANNING) {
  75269. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  75270. var v = vi.interpolate(vj, t);
  75271. f.push(v);
  75272. b.push(v.clone());
  75273. }
  75274. }
  75275. var poly;
  75276. if (f.length >= 3) {
  75277. poly = new Polygon(f, polygon.shared);
  75278. if (poly.plane)
  75279. front.push(poly);
  75280. }
  75281. if (b.length >= 3) {
  75282. poly = new Polygon(b, polygon.shared);
  75283. if (poly.plane)
  75284. back.push(poly);
  75285. }
  75286. break;
  75287. }
  75288. };
  75289. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  75290. // point is on the plane.
  75291. Plane.EPSILON = 1e-5;
  75292. return Plane;
  75293. }());
  75294. // # class Polygon
  75295. // Represents a convex polygon. The vertices used to initialize a polygon must
  75296. // be coplanar and form a convex loop.
  75297. //
  75298. // Each convex polygon has a `shared` property, which is shared between all
  75299. // polygons that are clones of each other or were split from the same polygon.
  75300. // This can be used to define per-polygon properties (such as surface color).
  75301. var Polygon = /** @class */ (function () {
  75302. function Polygon(vertices, shared) {
  75303. this.vertices = vertices;
  75304. this.shared = shared;
  75305. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  75306. }
  75307. Polygon.prototype.clone = function () {
  75308. var vertices = this.vertices.map(function (v) { return v.clone(); });
  75309. return new Polygon(vertices, this.shared);
  75310. };
  75311. Polygon.prototype.flip = function () {
  75312. this.vertices.reverse().map(function (v) { v.flip(); });
  75313. this.plane.flip();
  75314. };
  75315. return Polygon;
  75316. }());
  75317. // # class Node
  75318. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  75319. // by picking a polygon to split along. That polygon (and all other coplanar
  75320. // polygons) are added directly to that node and the other polygons are added to
  75321. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  75322. // no distinction between internal and leaf nodes.
  75323. var Node = /** @class */ (function () {
  75324. function Node(polygons) {
  75325. this.plane = null;
  75326. this.front = null;
  75327. this.back = null;
  75328. this.polygons = new Array();
  75329. if (polygons) {
  75330. this.build(polygons);
  75331. }
  75332. }
  75333. Node.prototype.clone = function () {
  75334. var node = new Node();
  75335. node.plane = this.plane && this.plane.clone();
  75336. node.front = this.front && this.front.clone();
  75337. node.back = this.back && this.back.clone();
  75338. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  75339. return node;
  75340. };
  75341. // Convert solid space to empty space and empty space to solid space.
  75342. Node.prototype.invert = function () {
  75343. for (var i = 0; i < this.polygons.length; i++) {
  75344. this.polygons[i].flip();
  75345. }
  75346. if (this.plane) {
  75347. this.plane.flip();
  75348. }
  75349. if (this.front) {
  75350. this.front.invert();
  75351. }
  75352. if (this.back) {
  75353. this.back.invert();
  75354. }
  75355. var temp = this.front;
  75356. this.front = this.back;
  75357. this.back = temp;
  75358. };
  75359. // Recursively remove all polygons in `polygons` that are inside this BSP
  75360. // tree.
  75361. Node.prototype.clipPolygons = function (polygons) {
  75362. if (!this.plane)
  75363. return polygons.slice();
  75364. var front = new Array(), back = new Array();
  75365. for (var i = 0; i < polygons.length; i++) {
  75366. this.plane.splitPolygon(polygons[i], front, back, front, back);
  75367. }
  75368. if (this.front) {
  75369. front = this.front.clipPolygons(front);
  75370. }
  75371. if (this.back) {
  75372. back = this.back.clipPolygons(back);
  75373. }
  75374. else {
  75375. back = [];
  75376. }
  75377. return front.concat(back);
  75378. };
  75379. // Remove all polygons in this BSP tree that are inside the other BSP tree
  75380. // `bsp`.
  75381. Node.prototype.clipTo = function (bsp) {
  75382. this.polygons = bsp.clipPolygons(this.polygons);
  75383. if (this.front)
  75384. this.front.clipTo(bsp);
  75385. if (this.back)
  75386. this.back.clipTo(bsp);
  75387. };
  75388. // Return a list of all polygons in this BSP tree.
  75389. Node.prototype.allPolygons = function () {
  75390. var polygons = this.polygons.slice();
  75391. if (this.front)
  75392. polygons = polygons.concat(this.front.allPolygons());
  75393. if (this.back)
  75394. polygons = polygons.concat(this.back.allPolygons());
  75395. return polygons;
  75396. };
  75397. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  75398. // new polygons are filtered down to the bottom of the tree and become new
  75399. // nodes there. Each set of polygons is partitioned using the first polygon
  75400. // (no heuristic is used to pick a good split).
  75401. Node.prototype.build = function (polygons) {
  75402. if (!polygons.length)
  75403. return;
  75404. if (!this.plane)
  75405. this.plane = polygons[0].plane.clone();
  75406. var front = new Array(), back = new Array();
  75407. for (var i = 0; i < polygons.length; i++) {
  75408. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  75409. }
  75410. if (front.length) {
  75411. if (!this.front)
  75412. this.front = new Node();
  75413. this.front.build(front);
  75414. }
  75415. if (back.length) {
  75416. if (!this.back)
  75417. this.back = new Node();
  75418. this.back.build(back);
  75419. }
  75420. };
  75421. return Node;
  75422. }());
  75423. var CSG = /** @class */ (function () {
  75424. function CSG() {
  75425. this.polygons = new Array();
  75426. }
  75427. // Convert BABYLON.Mesh to BABYLON.CSG
  75428. CSG.FromMesh = function (mesh) {
  75429. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  75430. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  75431. if (mesh instanceof BABYLON.Mesh) {
  75432. mesh.computeWorldMatrix(true);
  75433. matrix = mesh.getWorldMatrix();
  75434. meshPosition = mesh.position.clone();
  75435. meshRotation = mesh.rotation.clone();
  75436. if (mesh.rotationQuaternion) {
  75437. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  75438. }
  75439. meshScaling = mesh.scaling.clone();
  75440. }
  75441. else {
  75442. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  75443. }
  75444. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  75445. var subMeshes = mesh.subMeshes;
  75446. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  75447. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  75448. vertices = [];
  75449. for (var j = 0; j < 3; j++) {
  75450. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  75451. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  75452. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  75453. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  75454. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  75455. vertex = new Vertex(position, normal, uv);
  75456. vertices.push(vertex);
  75457. }
  75458. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  75459. // To handle the case of degenerated triangle
  75460. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  75461. if (polygon.plane)
  75462. polygons.push(polygon);
  75463. }
  75464. }
  75465. var csg = CSG.FromPolygons(polygons);
  75466. csg.matrix = matrix;
  75467. csg.position = meshPosition;
  75468. csg.rotation = meshRotation;
  75469. csg.scaling = meshScaling;
  75470. csg.rotationQuaternion = meshRotationQuaternion;
  75471. currentCSGMeshId++;
  75472. return csg;
  75473. };
  75474. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  75475. CSG.FromPolygons = function (polygons) {
  75476. var csg = new CSG();
  75477. csg.polygons = polygons;
  75478. return csg;
  75479. };
  75480. CSG.prototype.clone = function () {
  75481. var csg = new CSG();
  75482. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  75483. csg.copyTransformAttributes(this);
  75484. return csg;
  75485. };
  75486. CSG.prototype.union = function (csg) {
  75487. var a = new Node(this.clone().polygons);
  75488. var b = new Node(csg.clone().polygons);
  75489. a.clipTo(b);
  75490. b.clipTo(a);
  75491. b.invert();
  75492. b.clipTo(a);
  75493. b.invert();
  75494. a.build(b.allPolygons());
  75495. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  75496. };
  75497. CSG.prototype.unionInPlace = function (csg) {
  75498. var a = new Node(this.polygons);
  75499. var b = new Node(csg.polygons);
  75500. a.clipTo(b);
  75501. b.clipTo(a);
  75502. b.invert();
  75503. b.clipTo(a);
  75504. b.invert();
  75505. a.build(b.allPolygons());
  75506. this.polygons = a.allPolygons();
  75507. };
  75508. CSG.prototype.subtract = function (csg) {
  75509. var a = new Node(this.clone().polygons);
  75510. var b = new Node(csg.clone().polygons);
  75511. a.invert();
  75512. a.clipTo(b);
  75513. b.clipTo(a);
  75514. b.invert();
  75515. b.clipTo(a);
  75516. b.invert();
  75517. a.build(b.allPolygons());
  75518. a.invert();
  75519. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  75520. };
  75521. CSG.prototype.subtractInPlace = function (csg) {
  75522. var a = new Node(this.polygons);
  75523. var b = new Node(csg.polygons);
  75524. a.invert();
  75525. a.clipTo(b);
  75526. b.clipTo(a);
  75527. b.invert();
  75528. b.clipTo(a);
  75529. b.invert();
  75530. a.build(b.allPolygons());
  75531. a.invert();
  75532. this.polygons = a.allPolygons();
  75533. };
  75534. CSG.prototype.intersect = function (csg) {
  75535. var a = new Node(this.clone().polygons);
  75536. var b = new Node(csg.clone().polygons);
  75537. a.invert();
  75538. b.clipTo(a);
  75539. b.invert();
  75540. a.clipTo(b);
  75541. b.clipTo(a);
  75542. a.build(b.allPolygons());
  75543. a.invert();
  75544. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  75545. };
  75546. CSG.prototype.intersectInPlace = function (csg) {
  75547. var a = new Node(this.polygons);
  75548. var b = new Node(csg.polygons);
  75549. a.invert();
  75550. b.clipTo(a);
  75551. b.invert();
  75552. a.clipTo(b);
  75553. b.clipTo(a);
  75554. a.build(b.allPolygons());
  75555. a.invert();
  75556. this.polygons = a.allPolygons();
  75557. };
  75558. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  75559. // not modified.
  75560. CSG.prototype.inverse = function () {
  75561. var csg = this.clone();
  75562. csg.inverseInPlace();
  75563. return csg;
  75564. };
  75565. CSG.prototype.inverseInPlace = function () {
  75566. this.polygons.map(function (p) { p.flip(); });
  75567. };
  75568. // This is used to keep meshes transformations so they can be restored
  75569. // when we build back a Babylon Mesh
  75570. // NB : All CSG operations are performed in world coordinates
  75571. CSG.prototype.copyTransformAttributes = function (csg) {
  75572. this.matrix = csg.matrix;
  75573. this.position = csg.position;
  75574. this.rotation = csg.rotation;
  75575. this.scaling = csg.scaling;
  75576. this.rotationQuaternion = csg.rotationQuaternion;
  75577. return this;
  75578. };
  75579. // Build Raw mesh from CSG
  75580. // Coordinates here are in world space
  75581. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  75582. var matrix = this.matrix.clone();
  75583. matrix.invert();
  75584. var mesh = new BABYLON.Mesh(name, scene), vertices = [], indices = [], normals = [], uvs = [], vertex = BABYLON.Vector3.Zero(), normal = BABYLON.Vector3.Zero(), uv = BABYLON.Vector2.Zero(), polygons = this.polygons, polygonIndices = [0, 0, 0], polygon, vertice_dict = {}, vertex_idx, currentIndex = 0, subMesh_dict = {}, subMesh_obj;
  75585. if (keepSubMeshes) {
  75586. // Sort Polygons, since subMeshes are indices range
  75587. polygons.sort(function (a, b) {
  75588. if (a.shared.meshId === b.shared.meshId) {
  75589. return a.shared.subMeshId - b.shared.subMeshId;
  75590. }
  75591. else {
  75592. return a.shared.meshId - b.shared.meshId;
  75593. }
  75594. });
  75595. }
  75596. for (var i = 0, il = polygons.length; i < il; i++) {
  75597. polygon = polygons[i];
  75598. // Building SubMeshes
  75599. if (!subMesh_dict[polygon.shared.meshId]) {
  75600. subMesh_dict[polygon.shared.meshId] = {};
  75601. }
  75602. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  75603. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  75604. indexStart: +Infinity,
  75605. indexEnd: -Infinity,
  75606. materialIndex: polygon.shared.materialIndex
  75607. };
  75608. }
  75609. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  75610. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  75611. polygonIndices[0] = 0;
  75612. polygonIndices[1] = j - 1;
  75613. polygonIndices[2] = j;
  75614. for (var k = 0; k < 3; k++) {
  75615. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  75616. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  75617. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  75618. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  75619. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  75620. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  75621. // Check if 2 points can be merged
  75622. if (!(typeof vertex_idx !== 'undefined' &&
  75623. normals[vertex_idx * 3] === localNormal.x &&
  75624. normals[vertex_idx * 3 + 1] === localNormal.y &&
  75625. normals[vertex_idx * 3 + 2] === localNormal.z &&
  75626. uvs[vertex_idx * 2] === uv.x &&
  75627. uvs[vertex_idx * 2 + 1] === uv.y)) {
  75628. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  75629. uvs.push(uv.x, uv.y);
  75630. normals.push(normal.x, normal.y, normal.z);
  75631. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  75632. }
  75633. indices.push(vertex_idx);
  75634. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  75635. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  75636. currentIndex++;
  75637. }
  75638. }
  75639. }
  75640. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  75641. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  75642. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  75643. mesh.setIndices(indices, null);
  75644. if (keepSubMeshes) {
  75645. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  75646. var materialIndexOffset = 0, materialMaxIndex;
  75647. mesh.subMeshes = new Array();
  75648. for (var m in subMesh_dict) {
  75649. materialMaxIndex = -1;
  75650. for (var sm in subMesh_dict[m]) {
  75651. subMesh_obj = subMesh_dict[m][sm];
  75652. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  75653. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  75654. }
  75655. materialIndexOffset += ++materialMaxIndex;
  75656. }
  75657. }
  75658. return mesh;
  75659. };
  75660. // Build Mesh from CSG taking material and transforms into account
  75661. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  75662. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  75663. mesh.material = material;
  75664. mesh.position.copyFrom(this.position);
  75665. mesh.rotation.copyFrom(this.rotation);
  75666. if (this.rotationQuaternion) {
  75667. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  75668. }
  75669. mesh.scaling.copyFrom(this.scaling);
  75670. mesh.computeWorldMatrix(true);
  75671. return mesh;
  75672. };
  75673. return CSG;
  75674. }());
  75675. BABYLON.CSG = CSG;
  75676. })(BABYLON || (BABYLON = {}));
  75677. //# sourceMappingURL=babylon.csg.js.map
  75678. var BABYLON;
  75679. (function (BABYLON) {
  75680. var LensFlare = /** @class */ (function () {
  75681. function LensFlare(size, position, color, imgUrl, system) {
  75682. this.size = size;
  75683. this.position = position;
  75684. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  75685. this.color = color || new BABYLON.Color3(1, 1, 1);
  75686. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  75687. this._system = system;
  75688. system.lensFlares.push(this);
  75689. }
  75690. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  75691. return new LensFlare(size, position, color, imgUrl, system);
  75692. };
  75693. LensFlare.prototype.dispose = function () {
  75694. if (this.texture) {
  75695. this.texture.dispose();
  75696. }
  75697. // Remove from scene
  75698. var index = this._system.lensFlares.indexOf(this);
  75699. this._system.lensFlares.splice(index, 1);
  75700. };
  75701. ;
  75702. return LensFlare;
  75703. }());
  75704. BABYLON.LensFlare = LensFlare;
  75705. })(BABYLON || (BABYLON = {}));
  75706. //# sourceMappingURL=babylon.lensFlare.js.map
  75707. var BABYLON;
  75708. (function (BABYLON) {
  75709. var LensFlareSystem = /** @class */ (function () {
  75710. function LensFlareSystem(name, emitter, scene) {
  75711. this.name = name;
  75712. this.lensFlares = new Array();
  75713. this.borderLimit = 300;
  75714. this.viewportBorder = 0;
  75715. this.layerMask = 0x0FFFFFFF;
  75716. this._vertexBuffers = {};
  75717. this._isEnabled = true;
  75718. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  75719. this._emitter = emitter;
  75720. this.id = name;
  75721. scene.lensFlareSystems.push(this);
  75722. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  75723. var engine = scene.getEngine();
  75724. // VBO
  75725. var vertices = [];
  75726. vertices.push(1, 1);
  75727. vertices.push(-1, 1);
  75728. vertices.push(-1, -1);
  75729. vertices.push(1, -1);
  75730. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  75731. // Indices
  75732. var indices = [];
  75733. indices.push(0);
  75734. indices.push(1);
  75735. indices.push(2);
  75736. indices.push(0);
  75737. indices.push(2);
  75738. indices.push(3);
  75739. this._indexBuffer = engine.createIndexBuffer(indices);
  75740. // Effects
  75741. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  75742. }
  75743. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  75744. get: function () {
  75745. return this._isEnabled;
  75746. },
  75747. set: function (value) {
  75748. this._isEnabled = value;
  75749. },
  75750. enumerable: true,
  75751. configurable: true
  75752. });
  75753. LensFlareSystem.prototype.getScene = function () {
  75754. return this._scene;
  75755. };
  75756. LensFlareSystem.prototype.getEmitter = function () {
  75757. return this._emitter;
  75758. };
  75759. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  75760. this._emitter = newEmitter;
  75761. };
  75762. LensFlareSystem.prototype.getEmitterPosition = function () {
  75763. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  75764. };
  75765. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  75766. var position = this.getEmitterPosition();
  75767. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  75768. this._positionX = position.x;
  75769. this._positionY = position.y;
  75770. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  75771. if (this.viewportBorder > 0) {
  75772. globalViewport.x -= this.viewportBorder;
  75773. globalViewport.y -= this.viewportBorder;
  75774. globalViewport.width += this.viewportBorder * 2;
  75775. globalViewport.height += this.viewportBorder * 2;
  75776. position.x += this.viewportBorder;
  75777. position.y += this.viewportBorder;
  75778. this._positionX += this.viewportBorder;
  75779. this._positionY += this.viewportBorder;
  75780. }
  75781. if (position.z > 0) {
  75782. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  75783. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  75784. return true;
  75785. }
  75786. return true;
  75787. }
  75788. return false;
  75789. };
  75790. LensFlareSystem.prototype._isVisible = function () {
  75791. if (!this._isEnabled || !this._scene.activeCamera) {
  75792. return false;
  75793. }
  75794. var emitterPosition = this.getEmitterPosition();
  75795. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  75796. var distance = direction.length();
  75797. direction.normalize();
  75798. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  75799. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  75800. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  75801. };
  75802. LensFlareSystem.prototype.render = function () {
  75803. if (!this._effect.isReady() || !this._scene.activeCamera)
  75804. return false;
  75805. var engine = this._scene.getEngine();
  75806. var viewport = this._scene.activeCamera.viewport;
  75807. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  75808. // Position
  75809. if (!this.computeEffectivePosition(globalViewport)) {
  75810. return false;
  75811. }
  75812. // Visibility
  75813. if (!this._isVisible()) {
  75814. return false;
  75815. }
  75816. // Intensity
  75817. var awayX;
  75818. var awayY;
  75819. if (this._positionX < this.borderLimit + globalViewport.x) {
  75820. awayX = this.borderLimit + globalViewport.x - this._positionX;
  75821. }
  75822. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  75823. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  75824. }
  75825. else {
  75826. awayX = 0;
  75827. }
  75828. if (this._positionY < this.borderLimit + globalViewport.y) {
  75829. awayY = this.borderLimit + globalViewport.y - this._positionY;
  75830. }
  75831. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  75832. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  75833. }
  75834. else {
  75835. awayY = 0;
  75836. }
  75837. var away = (awayX > awayY) ? awayX : awayY;
  75838. away -= this.viewportBorder;
  75839. if (away > this.borderLimit) {
  75840. away = this.borderLimit;
  75841. }
  75842. var intensity = 1.0 - (away / this.borderLimit);
  75843. if (intensity < 0) {
  75844. return false;
  75845. }
  75846. if (intensity > 1.0) {
  75847. intensity = 1.0;
  75848. }
  75849. if (this.viewportBorder > 0) {
  75850. globalViewport.x += this.viewportBorder;
  75851. globalViewport.y += this.viewportBorder;
  75852. globalViewport.width -= this.viewportBorder * 2;
  75853. globalViewport.height -= this.viewportBorder * 2;
  75854. this._positionX -= this.viewportBorder;
  75855. this._positionY -= this.viewportBorder;
  75856. }
  75857. // Position
  75858. var centerX = globalViewport.x + globalViewport.width / 2;
  75859. var centerY = globalViewport.y + globalViewport.height / 2;
  75860. var distX = centerX - this._positionX;
  75861. var distY = centerY - this._positionY;
  75862. // Effects
  75863. engine.enableEffect(this._effect);
  75864. engine.setState(false);
  75865. engine.setDepthBuffer(false);
  75866. // VBOs
  75867. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  75868. // Flares
  75869. for (var index = 0; index < this.lensFlares.length; index++) {
  75870. var flare = this.lensFlares[index];
  75871. engine.setAlphaMode(flare.alphaMode);
  75872. var x = centerX - (distX * flare.position);
  75873. var y = centerY - (distY * flare.position);
  75874. var cw = flare.size;
  75875. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  75876. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  75877. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  75878. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  75879. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  75880. // Texture
  75881. this._effect.setTexture("textureSampler", flare.texture);
  75882. // Color
  75883. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  75884. // Draw order
  75885. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  75886. }
  75887. engine.setDepthBuffer(true);
  75888. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  75889. return true;
  75890. };
  75891. LensFlareSystem.prototype.dispose = function () {
  75892. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  75893. if (vertexBuffer) {
  75894. vertexBuffer.dispose();
  75895. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  75896. }
  75897. if (this._indexBuffer) {
  75898. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  75899. this._indexBuffer = null;
  75900. }
  75901. while (this.lensFlares.length) {
  75902. this.lensFlares[0].dispose();
  75903. }
  75904. // Remove from scene
  75905. var index = this._scene.lensFlareSystems.indexOf(this);
  75906. this._scene.lensFlareSystems.splice(index, 1);
  75907. };
  75908. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  75909. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  75910. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  75911. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  75912. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  75913. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  75914. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  75915. var parsedFlare = parsedLensFlareSystem.flares[index];
  75916. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  75917. }
  75918. return lensFlareSystem;
  75919. };
  75920. LensFlareSystem.prototype.serialize = function () {
  75921. var serializationObject = {};
  75922. serializationObject.id = this.id;
  75923. serializationObject.name = this.name;
  75924. serializationObject.emitterId = this.getEmitter().id;
  75925. serializationObject.borderLimit = this.borderLimit;
  75926. serializationObject.flares = [];
  75927. for (var index = 0; index < this.lensFlares.length; index++) {
  75928. var flare = this.lensFlares[index];
  75929. serializationObject.flares.push({
  75930. size: flare.size,
  75931. position: flare.position,
  75932. color: flare.color.asArray(),
  75933. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  75934. });
  75935. }
  75936. return serializationObject;
  75937. };
  75938. return LensFlareSystem;
  75939. }());
  75940. BABYLON.LensFlareSystem = LensFlareSystem;
  75941. })(BABYLON || (BABYLON = {}));
  75942. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  75943. var BABYLON;
  75944. (function (BABYLON) {
  75945. /**
  75946. * This is a holder class for the physics joint created by the physics plugin.
  75947. * It holds a set of functions to control the underlying joint.
  75948. */
  75949. var PhysicsJoint = /** @class */ (function () {
  75950. function PhysicsJoint(type, jointData) {
  75951. this.type = type;
  75952. this.jointData = jointData;
  75953. jointData.nativeParams = jointData.nativeParams || {};
  75954. }
  75955. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  75956. get: function () {
  75957. return this._physicsJoint;
  75958. },
  75959. set: function (newJoint) {
  75960. if (this._physicsJoint) {
  75961. //remove from the wolrd
  75962. }
  75963. this._physicsJoint = newJoint;
  75964. },
  75965. enumerable: true,
  75966. configurable: true
  75967. });
  75968. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  75969. set: function (physicsPlugin) {
  75970. this._physicsPlugin = physicsPlugin;
  75971. },
  75972. enumerable: true,
  75973. configurable: true
  75974. });
  75975. /**
  75976. * Execute a function that is physics-plugin specific.
  75977. * @param {Function} func the function that will be executed.
  75978. * It accepts two parameters: the physics world and the physics joint.
  75979. */
  75980. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  75981. func(this._physicsPlugin.world, this._physicsJoint);
  75982. };
  75983. //TODO check if the native joints are the same
  75984. //Joint Types
  75985. PhysicsJoint.DistanceJoint = 0;
  75986. PhysicsJoint.HingeJoint = 1;
  75987. PhysicsJoint.BallAndSocketJoint = 2;
  75988. PhysicsJoint.WheelJoint = 3;
  75989. PhysicsJoint.SliderJoint = 4;
  75990. //OIMO
  75991. PhysicsJoint.PrismaticJoint = 5;
  75992. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  75993. PhysicsJoint.UniversalJoint = 6;
  75994. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  75995. //Cannon
  75996. //Similar to a Ball-Joint. Different in params
  75997. PhysicsJoint.PointToPointJoint = 8;
  75998. //Cannon only at the moment
  75999. PhysicsJoint.SpringJoint = 9;
  76000. PhysicsJoint.LockJoint = 10;
  76001. return PhysicsJoint;
  76002. }());
  76003. BABYLON.PhysicsJoint = PhysicsJoint;
  76004. /**
  76005. * A class representing a physics distance joint.
  76006. */
  76007. var DistanceJoint = /** @class */ (function (_super) {
  76008. __extends(DistanceJoint, _super);
  76009. function DistanceJoint(jointData) {
  76010. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  76011. }
  76012. /**
  76013. * Update the predefined distance.
  76014. */
  76015. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  76016. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  76017. };
  76018. return DistanceJoint;
  76019. }(PhysicsJoint));
  76020. BABYLON.DistanceJoint = DistanceJoint;
  76021. var MotorEnabledJoint = /** @class */ (function (_super) {
  76022. __extends(MotorEnabledJoint, _super);
  76023. function MotorEnabledJoint(type, jointData) {
  76024. return _super.call(this, type, jointData) || this;
  76025. }
  76026. /**
  76027. * Set the motor values.
  76028. * Attention, this function is plugin specific. Engines won't react 100% the same.
  76029. * @param {number} force the force to apply
  76030. * @param {number} maxForce max force for this motor.
  76031. */
  76032. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  76033. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  76034. };
  76035. /**
  76036. * Set the motor's limits.
  76037. * Attention, this function is plugin specific. Engines won't react 100% the same.
  76038. */
  76039. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  76040. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  76041. };
  76042. return MotorEnabledJoint;
  76043. }(PhysicsJoint));
  76044. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  76045. /**
  76046. * This class represents a single hinge physics joint
  76047. */
  76048. var HingeJoint = /** @class */ (function (_super) {
  76049. __extends(HingeJoint, _super);
  76050. function HingeJoint(jointData) {
  76051. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  76052. }
  76053. /**
  76054. * Set the motor values.
  76055. * Attention, this function is plugin specific. Engines won't react 100% the same.
  76056. * @param {number} force the force to apply
  76057. * @param {number} maxForce max force for this motor.
  76058. */
  76059. HingeJoint.prototype.setMotor = function (force, maxForce) {
  76060. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  76061. };
  76062. /**
  76063. * Set the motor's limits.
  76064. * Attention, this function is plugin specific. Engines won't react 100% the same.
  76065. */
  76066. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  76067. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  76068. };
  76069. return HingeJoint;
  76070. }(MotorEnabledJoint));
  76071. BABYLON.HingeJoint = HingeJoint;
  76072. /**
  76073. * This class represents a dual hinge physics joint (same as wheel joint)
  76074. */
  76075. var Hinge2Joint = /** @class */ (function (_super) {
  76076. __extends(Hinge2Joint, _super);
  76077. function Hinge2Joint(jointData) {
  76078. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  76079. }
  76080. /**
  76081. * Set the motor values.
  76082. * Attention, this function is plugin specific. Engines won't react 100% the same.
  76083. * @param {number} force the force to apply
  76084. * @param {number} maxForce max force for this motor.
  76085. * @param {motorIndex} the motor's index, 0 or 1.
  76086. */
  76087. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  76088. if (motorIndex === void 0) { motorIndex = 0; }
  76089. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  76090. };
  76091. /**
  76092. * Set the motor limits.
  76093. * Attention, this function is plugin specific. Engines won't react 100% the same.
  76094. * @param {number} upperLimit the upper limit
  76095. * @param {number} lowerLimit lower limit
  76096. * @param {motorIndex} the motor's index, 0 or 1.
  76097. */
  76098. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  76099. if (motorIndex === void 0) { motorIndex = 0; }
  76100. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  76101. };
  76102. return Hinge2Joint;
  76103. }(MotorEnabledJoint));
  76104. BABYLON.Hinge2Joint = Hinge2Joint;
  76105. })(BABYLON || (BABYLON = {}));
  76106. //# sourceMappingURL=babylon.physicsJoint.js.map
  76107. var BABYLON;
  76108. (function (BABYLON) {
  76109. var PhysicsImpostor = /** @class */ (function () {
  76110. function PhysicsImpostor(object, type, _options, _scene) {
  76111. if (_options === void 0) { _options = { mass: 0 }; }
  76112. var _this = this;
  76113. this.object = object;
  76114. this.type = type;
  76115. this._options = _options;
  76116. this._scene = _scene;
  76117. this._bodyUpdateRequired = false;
  76118. this._onBeforePhysicsStepCallbacks = new Array();
  76119. this._onAfterPhysicsStepCallbacks = new Array();
  76120. this._onPhysicsCollideCallbacks = [];
  76121. this._deltaPosition = BABYLON.Vector3.Zero();
  76122. this._isDisposed = false;
  76123. //temp variables for parent rotation calculations
  76124. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  76125. this._tmpQuat = new BABYLON.Quaternion();
  76126. this._tmpQuat2 = new BABYLON.Quaternion();
  76127. /**
  76128. * this function is executed by the physics engine.
  76129. */
  76130. this.beforeStep = function () {
  76131. if (!_this._physicsEngine) {
  76132. return;
  76133. }
  76134. _this.object.translate(_this._deltaPosition, -1);
  76135. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  76136. _this.object.computeWorldMatrix(false);
  76137. if (_this.object.parent && _this.object.rotationQuaternion) {
  76138. _this.getParentsRotation();
  76139. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  76140. }
  76141. else {
  76142. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  76143. }
  76144. if (!_this._options.disableBidirectionalTransformation) {
  76145. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  76146. }
  76147. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  76148. func(_this);
  76149. });
  76150. };
  76151. /**
  76152. * this function is executed by the physics engine.
  76153. */
  76154. this.afterStep = function () {
  76155. if (!_this._physicsEngine) {
  76156. return;
  76157. }
  76158. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  76159. func(_this);
  76160. });
  76161. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  76162. // object has now its world rotation. needs to be converted to local.
  76163. if (_this.object.parent && _this.object.rotationQuaternion) {
  76164. _this.getParentsRotation();
  76165. _this._tmpQuat.conjugateInPlace();
  76166. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  76167. }
  76168. // take the position set and make it the absolute position of this object.
  76169. _this.object.setAbsolutePosition(_this.object.position);
  76170. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  76171. _this.object.translate(_this._deltaPosition, 1);
  76172. };
  76173. /**
  76174. * Legacy collision detection event support
  76175. */
  76176. this.onCollideEvent = null;
  76177. //event and body object due to cannon's event-based architecture.
  76178. this.onCollide = function (e) {
  76179. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  76180. return;
  76181. }
  76182. if (!_this._physicsEngine) {
  76183. return;
  76184. }
  76185. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  76186. if (otherImpostor) {
  76187. // Legacy collision detection event support
  76188. if (_this.onCollideEvent) {
  76189. _this.onCollideEvent(_this, otherImpostor);
  76190. }
  76191. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  76192. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  76193. }).forEach(function (obj) {
  76194. obj.callback(_this, otherImpostor);
  76195. });
  76196. }
  76197. };
  76198. //sanity check!
  76199. if (!this.object) {
  76200. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  76201. return;
  76202. }
  76203. //legacy support for old syntax.
  76204. if (!this._scene && object.getScene) {
  76205. this._scene = object.getScene();
  76206. }
  76207. if (!this._scene) {
  76208. return;
  76209. }
  76210. this._physicsEngine = this._scene.getPhysicsEngine();
  76211. if (!this._physicsEngine) {
  76212. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  76213. }
  76214. else {
  76215. //set the object's quaternion, if not set
  76216. if (!this.object.rotationQuaternion) {
  76217. if (this.object.rotation) {
  76218. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  76219. }
  76220. else {
  76221. this.object.rotationQuaternion = new BABYLON.Quaternion();
  76222. }
  76223. }
  76224. //default options params
  76225. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  76226. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  76227. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  76228. this._joints = [];
  76229. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  76230. if (!this.object.parent || this._options.ignoreParent) {
  76231. this._init();
  76232. }
  76233. else if (this.object.parent.physicsImpostor) {
  76234. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  76235. }
  76236. }
  76237. }
  76238. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  76239. get: function () {
  76240. return this._isDisposed;
  76241. },
  76242. enumerable: true,
  76243. configurable: true
  76244. });
  76245. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  76246. get: function () {
  76247. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  76248. },
  76249. set: function (value) {
  76250. this.setMass(value);
  76251. },
  76252. enumerable: true,
  76253. configurable: true
  76254. });
  76255. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  76256. get: function () {
  76257. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  76258. },
  76259. set: function (value) {
  76260. if (!this._physicsEngine) {
  76261. return;
  76262. }
  76263. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  76264. },
  76265. enumerable: true,
  76266. configurable: true
  76267. });
  76268. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  76269. get: function () {
  76270. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  76271. },
  76272. set: function (value) {
  76273. if (!this._physicsEngine) {
  76274. return;
  76275. }
  76276. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  76277. },
  76278. enumerable: true,
  76279. configurable: true
  76280. });
  76281. /**
  76282. * This function will completly initialize this impostor.
  76283. * It will create a new body - but only if this mesh has no parent.
  76284. * If it has, this impostor will not be used other than to define the impostor
  76285. * of the child mesh.
  76286. */
  76287. PhysicsImpostor.prototype._init = function () {
  76288. if (!this._physicsEngine) {
  76289. return;
  76290. }
  76291. this._physicsEngine.removeImpostor(this);
  76292. this.physicsBody = null;
  76293. this._parent = this._parent || this._getPhysicsParent();
  76294. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  76295. this._physicsEngine.addImpostor(this);
  76296. }
  76297. };
  76298. PhysicsImpostor.prototype._getPhysicsParent = function () {
  76299. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  76300. var parentMesh = this.object.parent;
  76301. return parentMesh.physicsImpostor;
  76302. }
  76303. return null;
  76304. };
  76305. /**
  76306. * Should a new body be generated.
  76307. */
  76308. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  76309. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  76310. };
  76311. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  76312. this.forceUpdate();
  76313. };
  76314. /**
  76315. * Force a regeneration of this or the parent's impostor's body.
  76316. * Use under cautious - This will remove all joints already implemented.
  76317. */
  76318. PhysicsImpostor.prototype.forceUpdate = function () {
  76319. this._init();
  76320. if (this.parent && !this._options.ignoreParent) {
  76321. this.parent.forceUpdate();
  76322. }
  76323. };
  76324. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  76325. /*public get mesh(): AbstractMesh {
  76326. return this._mesh;
  76327. }*/
  76328. /**
  76329. * Gets the body that holds this impostor. Either its own, or its parent.
  76330. */
  76331. get: function () {
  76332. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  76333. },
  76334. /**
  76335. * Set the physics body. Used mainly by the physics engine/plugin
  76336. */
  76337. set: function (physicsBody) {
  76338. if (this._physicsBody && this._physicsEngine) {
  76339. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  76340. }
  76341. this._physicsBody = physicsBody;
  76342. this.resetUpdateFlags();
  76343. },
  76344. enumerable: true,
  76345. configurable: true
  76346. });
  76347. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  76348. get: function () {
  76349. return !this._options.ignoreParent && this._parent ? this._parent : null;
  76350. },
  76351. set: function (value) {
  76352. this._parent = value;
  76353. },
  76354. enumerable: true,
  76355. configurable: true
  76356. });
  76357. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  76358. this._bodyUpdateRequired = false;
  76359. };
  76360. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  76361. if (this.object.getBoundingInfo) {
  76362. var q = this.object.rotationQuaternion;
  76363. //reset rotation
  76364. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  76365. //calculate the world matrix with no rotation
  76366. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  76367. var boundingInfo = this.object.getBoundingInfo();
  76368. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  76369. //bring back the rotation
  76370. this.object.rotationQuaternion = q;
  76371. //calculate the world matrix with the new rotation
  76372. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  76373. return size;
  76374. }
  76375. else {
  76376. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  76377. }
  76378. };
  76379. PhysicsImpostor.prototype.getObjectCenter = function () {
  76380. if (this.object.getBoundingInfo) {
  76381. var boundingInfo = this.object.getBoundingInfo();
  76382. return boundingInfo.boundingBox.centerWorld;
  76383. }
  76384. else {
  76385. return this.object.position;
  76386. }
  76387. };
  76388. /**
  76389. * Get a specific parametes from the options parameter.
  76390. */
  76391. PhysicsImpostor.prototype.getParam = function (paramName) {
  76392. return this._options[paramName];
  76393. };
  76394. /**
  76395. * Sets a specific parameter in the options given to the physics plugin
  76396. */
  76397. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  76398. this._options[paramName] = value;
  76399. this._bodyUpdateRequired = true;
  76400. };
  76401. /**
  76402. * Specifically change the body's mass option. Won't recreate the physics body object
  76403. */
  76404. PhysicsImpostor.prototype.setMass = function (mass) {
  76405. if (this.getParam("mass") !== mass) {
  76406. this.setParam("mass", mass);
  76407. }
  76408. if (this._physicsEngine) {
  76409. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  76410. }
  76411. };
  76412. PhysicsImpostor.prototype.getLinearVelocity = function () {
  76413. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  76414. };
  76415. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  76416. if (this._physicsEngine) {
  76417. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  76418. }
  76419. };
  76420. PhysicsImpostor.prototype.getAngularVelocity = function () {
  76421. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  76422. };
  76423. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  76424. if (this._physicsEngine) {
  76425. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  76426. }
  76427. };
  76428. /**
  76429. * Execute a function with the physics plugin native code.
  76430. * Provide a function the will have two variables - the world object and the physics body object.
  76431. */
  76432. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  76433. if (this._physicsEngine) {
  76434. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  76435. }
  76436. };
  76437. /**
  76438. * Register a function that will be executed before the physics world is stepping forward.
  76439. */
  76440. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  76441. this._onBeforePhysicsStepCallbacks.push(func);
  76442. };
  76443. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  76444. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  76445. if (index > -1) {
  76446. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  76447. }
  76448. else {
  76449. BABYLON.Tools.Warn("Function to remove was not found");
  76450. }
  76451. };
  76452. /**
  76453. * Register a function that will be executed after the physics step
  76454. */
  76455. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  76456. this._onAfterPhysicsStepCallbacks.push(func);
  76457. };
  76458. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  76459. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  76460. if (index > -1) {
  76461. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  76462. }
  76463. else {
  76464. BABYLON.Tools.Warn("Function to remove was not found");
  76465. }
  76466. };
  76467. /**
  76468. * register a function that will be executed when this impostor collides against a different body.
  76469. */
  76470. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  76471. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  76472. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  76473. };
  76474. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  76475. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  76476. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  76477. if (index > -1) {
  76478. this._onPhysicsCollideCallbacks.splice(index, 1);
  76479. }
  76480. else {
  76481. BABYLON.Tools.Warn("Function to remove was not found");
  76482. }
  76483. };
  76484. PhysicsImpostor.prototype.getParentsRotation = function () {
  76485. var parent = this.object.parent;
  76486. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  76487. while (parent) {
  76488. if (parent.rotationQuaternion) {
  76489. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  76490. }
  76491. else {
  76492. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  76493. }
  76494. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  76495. parent = parent.parent;
  76496. }
  76497. return this._tmpQuat;
  76498. };
  76499. /**
  76500. * Apply a force
  76501. */
  76502. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  76503. if (this._physicsEngine) {
  76504. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  76505. }
  76506. return this;
  76507. };
  76508. /**
  76509. * Apply an impulse
  76510. */
  76511. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  76512. if (this._physicsEngine) {
  76513. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  76514. }
  76515. return this;
  76516. };
  76517. /**
  76518. * A help function to create a joint.
  76519. */
  76520. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  76521. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  76522. this.addJoint(otherImpostor, joint);
  76523. return this;
  76524. };
  76525. /**
  76526. * Add a joint to this impostor with a different impostor.
  76527. */
  76528. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  76529. this._joints.push({
  76530. otherImpostor: otherImpostor,
  76531. joint: joint
  76532. });
  76533. if (this._physicsEngine) {
  76534. this._physicsEngine.addJoint(this, otherImpostor, joint);
  76535. }
  76536. return this;
  76537. };
  76538. /**
  76539. * Will keep this body still, in a sleep mode.
  76540. */
  76541. PhysicsImpostor.prototype.sleep = function () {
  76542. if (this._physicsEngine) {
  76543. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  76544. }
  76545. return this;
  76546. };
  76547. /**
  76548. * Wake the body up.
  76549. */
  76550. PhysicsImpostor.prototype.wakeUp = function () {
  76551. if (this._physicsEngine) {
  76552. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  76553. }
  76554. return this;
  76555. };
  76556. PhysicsImpostor.prototype.clone = function (newObject) {
  76557. if (!newObject)
  76558. return null;
  76559. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  76560. };
  76561. PhysicsImpostor.prototype.dispose = function () {
  76562. var _this = this;
  76563. //no dispose if no physics engine is available.
  76564. if (!this._physicsEngine) {
  76565. return;
  76566. }
  76567. this._joints.forEach(function (j) {
  76568. if (_this._physicsEngine) {
  76569. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  76570. }
  76571. });
  76572. //dispose the physics body
  76573. this._physicsEngine.removeImpostor(this);
  76574. if (this.parent) {
  76575. this.parent.forceUpdate();
  76576. }
  76577. else {
  76578. /*this._object.getChildMeshes().forEach(function(mesh) {
  76579. if (mesh.physicsImpostor) {
  76580. if (disposeChildren) {
  76581. mesh.physicsImpostor.dispose();
  76582. mesh.physicsImpostor = null;
  76583. }
  76584. }
  76585. })*/
  76586. }
  76587. this._isDisposed = true;
  76588. };
  76589. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  76590. this._deltaPosition.copyFrom(position);
  76591. };
  76592. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  76593. if (!this._deltaRotation) {
  76594. this._deltaRotation = new BABYLON.Quaternion();
  76595. }
  76596. this._deltaRotation.copyFrom(rotation);
  76597. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  76598. };
  76599. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  76600. if (this._physicsEngine) {
  76601. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  76602. }
  76603. return this;
  76604. };
  76605. PhysicsImpostor.prototype.getRadius = function () {
  76606. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  76607. };
  76608. /**
  76609. * Sync a bone with this impostor
  76610. * @param bone The bone to sync to the impostor.
  76611. * @param boneMesh The mesh that the bone is influencing.
  76612. * @param jointPivot The pivot of the joint / bone in local space.
  76613. * @param distToJoint Optional distance from the impostor to the joint.
  76614. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  76615. */
  76616. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  76617. var tempVec = PhysicsImpostor._tmpVecs[0];
  76618. var mesh = this.object;
  76619. if (mesh.rotationQuaternion) {
  76620. if (adjustRotation) {
  76621. var tempQuat = PhysicsImpostor._tmpQuat;
  76622. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  76623. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  76624. }
  76625. else {
  76626. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  76627. }
  76628. }
  76629. tempVec.x = 0;
  76630. tempVec.y = 0;
  76631. tempVec.z = 0;
  76632. if (jointPivot) {
  76633. tempVec.x = jointPivot.x;
  76634. tempVec.y = jointPivot.y;
  76635. tempVec.z = jointPivot.z;
  76636. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  76637. if (distToJoint === undefined || distToJoint === null) {
  76638. distToJoint = jointPivot.length();
  76639. }
  76640. tempVec.x *= distToJoint;
  76641. tempVec.y *= distToJoint;
  76642. tempVec.z *= distToJoint;
  76643. }
  76644. if (bone.getParent()) {
  76645. tempVec.addInPlace(mesh.getAbsolutePosition());
  76646. bone.setAbsolutePosition(tempVec, boneMesh);
  76647. }
  76648. else {
  76649. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  76650. boneMesh.position.x -= tempVec.x;
  76651. boneMesh.position.y -= tempVec.y;
  76652. boneMesh.position.z -= tempVec.z;
  76653. }
  76654. };
  76655. /**
  76656. * Sync impostor to a bone
  76657. * @param bone The bone that the impostor will be synced to.
  76658. * @param boneMesh The mesh that the bone is influencing.
  76659. * @param jointPivot The pivot of the joint / bone in local space.
  76660. * @param distToJoint Optional distance from the impostor to the joint.
  76661. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  76662. * @param boneAxis Optional vector3 axis the bone is aligned with
  76663. */
  76664. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  76665. var mesh = this.object;
  76666. if (mesh.rotationQuaternion) {
  76667. if (adjustRotation) {
  76668. var tempQuat = PhysicsImpostor._tmpQuat;
  76669. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  76670. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  76671. }
  76672. else {
  76673. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  76674. }
  76675. }
  76676. var pos = PhysicsImpostor._tmpVecs[0];
  76677. var boneDir = PhysicsImpostor._tmpVecs[1];
  76678. if (!boneAxis) {
  76679. boneAxis = PhysicsImpostor._tmpVecs[2];
  76680. boneAxis.x = 0;
  76681. boneAxis.y = 1;
  76682. boneAxis.z = 0;
  76683. }
  76684. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  76685. bone.getAbsolutePositionToRef(boneMesh, pos);
  76686. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  76687. distToJoint = jointPivot.length();
  76688. }
  76689. if (distToJoint !== undefined && distToJoint !== null) {
  76690. pos.x += boneDir.x * distToJoint;
  76691. pos.y += boneDir.y * distToJoint;
  76692. pos.z += boneDir.z * distToJoint;
  76693. }
  76694. mesh.setAbsolutePosition(pos);
  76695. };
  76696. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  76697. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  76698. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  76699. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  76700. //Impostor types
  76701. PhysicsImpostor.NoImpostor = 0;
  76702. PhysicsImpostor.SphereImpostor = 1;
  76703. PhysicsImpostor.BoxImpostor = 2;
  76704. PhysicsImpostor.PlaneImpostor = 3;
  76705. PhysicsImpostor.MeshImpostor = 4;
  76706. PhysicsImpostor.CylinderImpostor = 7;
  76707. PhysicsImpostor.ParticleImpostor = 8;
  76708. PhysicsImpostor.HeightmapImpostor = 9;
  76709. return PhysicsImpostor;
  76710. }());
  76711. BABYLON.PhysicsImpostor = PhysicsImpostor;
  76712. })(BABYLON || (BABYLON = {}));
  76713. //# sourceMappingURL=babylon.physicsImpostor.js.map
  76714. var BABYLON;
  76715. (function (BABYLON) {
  76716. var PhysicsEngine = /** @class */ (function () {
  76717. function PhysicsEngine(gravity, _physicsPlugin) {
  76718. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  76719. this._physicsPlugin = _physicsPlugin;
  76720. //new methods and parameters
  76721. this._impostors = [];
  76722. this._joints = [];
  76723. if (!this._physicsPlugin.isSupported()) {
  76724. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  76725. + "Please make sure it is included.");
  76726. }
  76727. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  76728. this.setGravity(gravity);
  76729. this.setTimeStep();
  76730. }
  76731. PhysicsEngine.prototype.setGravity = function (gravity) {
  76732. this.gravity = gravity;
  76733. this._physicsPlugin.setGravity(this.gravity);
  76734. };
  76735. /**
  76736. * Set the time step of the physics engine.
  76737. * default is 1/60.
  76738. * To slow it down, enter 1/600 for example.
  76739. * To speed it up, 1/30
  76740. * @param {number} newTimeStep the new timestep to apply to this world.
  76741. */
  76742. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  76743. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  76744. this._physicsPlugin.setTimeStep(newTimeStep);
  76745. };
  76746. /**
  76747. * Get the time step of the physics engine.
  76748. */
  76749. PhysicsEngine.prototype.getTimeStep = function () {
  76750. return this._physicsPlugin.getTimeStep();
  76751. };
  76752. PhysicsEngine.prototype.dispose = function () {
  76753. this._impostors.forEach(function (impostor) {
  76754. impostor.dispose();
  76755. });
  76756. this._physicsPlugin.dispose();
  76757. };
  76758. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  76759. return this._physicsPlugin.name;
  76760. };
  76761. /**
  76762. * Adding a new impostor for the impostor tracking.
  76763. * This will be done by the impostor itself.
  76764. * @param {PhysicsImpostor} impostor the impostor to add
  76765. */
  76766. PhysicsEngine.prototype.addImpostor = function (impostor) {
  76767. impostor.uniqueId = this._impostors.push(impostor);
  76768. //if no parent, generate the body
  76769. if (!impostor.parent) {
  76770. this._physicsPlugin.generatePhysicsBody(impostor);
  76771. }
  76772. };
  76773. /**
  76774. * Remove an impostor from the engine.
  76775. * This impostor and its mesh will not longer be updated by the physics engine.
  76776. * @param {PhysicsImpostor} impostor the impostor to remove
  76777. */
  76778. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  76779. var index = this._impostors.indexOf(impostor);
  76780. if (index > -1) {
  76781. var removed = this._impostors.splice(index, 1);
  76782. //Is it needed?
  76783. if (removed.length) {
  76784. //this will also remove it from the world.
  76785. removed[0].physicsBody = null;
  76786. }
  76787. }
  76788. };
  76789. /**
  76790. * Add a joint to the physics engine
  76791. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  76792. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  76793. * @param {PhysicsJoint} the joint that will connect both impostors.
  76794. */
  76795. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  76796. var impostorJoint = {
  76797. mainImpostor: mainImpostor,
  76798. connectedImpostor: connectedImpostor,
  76799. joint: joint
  76800. };
  76801. joint.physicsPlugin = this._physicsPlugin;
  76802. this._joints.push(impostorJoint);
  76803. this._physicsPlugin.generateJoint(impostorJoint);
  76804. };
  76805. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  76806. var matchingJoints = this._joints.filter(function (impostorJoint) {
  76807. return (impostorJoint.connectedImpostor === connectedImpostor
  76808. && impostorJoint.joint === joint
  76809. && impostorJoint.mainImpostor === mainImpostor);
  76810. });
  76811. if (matchingJoints.length) {
  76812. this._physicsPlugin.removeJoint(matchingJoints[0]);
  76813. //TODO remove it from the list as well
  76814. }
  76815. };
  76816. /**
  76817. * Called by the scene. no need to call it.
  76818. */
  76819. PhysicsEngine.prototype._step = function (delta) {
  76820. var _this = this;
  76821. //check if any mesh has no body / requires an update
  76822. this._impostors.forEach(function (impostor) {
  76823. if (impostor.isBodyInitRequired()) {
  76824. _this._physicsPlugin.generatePhysicsBody(impostor);
  76825. }
  76826. });
  76827. if (delta > 0.1) {
  76828. delta = 0.1;
  76829. }
  76830. else if (delta <= 0) {
  76831. delta = 1.0 / 60.0;
  76832. }
  76833. this._physicsPlugin.executeStep(delta, this._impostors);
  76834. };
  76835. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  76836. return this._physicsPlugin;
  76837. };
  76838. PhysicsEngine.prototype.getImpostors = function () {
  76839. return this._impostors;
  76840. };
  76841. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  76842. for (var i = 0; i < this._impostors.length; ++i) {
  76843. if (this._impostors[i].object === object) {
  76844. return this._impostors[i];
  76845. }
  76846. }
  76847. return null;
  76848. };
  76849. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  76850. for (var i = 0; i < this._impostors.length; ++i) {
  76851. if (this._impostors[i].physicsBody === body) {
  76852. return this._impostors[i];
  76853. }
  76854. }
  76855. return null;
  76856. };
  76857. // Statics
  76858. PhysicsEngine.Epsilon = 0.001;
  76859. return PhysicsEngine;
  76860. }());
  76861. BABYLON.PhysicsEngine = PhysicsEngine;
  76862. })(BABYLON || (BABYLON = {}));
  76863. //# sourceMappingURL=babylon.physicsEngine.js.map
  76864. var BABYLON;
  76865. (function (BABYLON) {
  76866. var PhysicsHelper = /** @class */ (function () {
  76867. function PhysicsHelper(scene) {
  76868. this._scene = scene;
  76869. this._physicsEngine = this._scene.getPhysicsEngine();
  76870. if (!this._physicsEngine) {
  76871. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  76872. }
  76873. }
  76874. /**
  76875. * @param {Vector3} origin the origin of the explosion
  76876. * @param {number} radius the explosion radius
  76877. * @param {number} strength the explosion strength
  76878. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  76879. */
  76880. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  76881. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  76882. if (!this._physicsEngine) {
  76883. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  76884. return null;
  76885. }
  76886. var impostors = this._physicsEngine.getImpostors();
  76887. if (impostors.length === 0) {
  76888. return null;
  76889. }
  76890. var event = new PhysicsRadialExplosionEvent(this._scene);
  76891. impostors.forEach(function (impostor) {
  76892. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  76893. if (!impostorForceAndContactPoint) {
  76894. return;
  76895. }
  76896. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  76897. });
  76898. event.dispose(false);
  76899. return event;
  76900. };
  76901. /**
  76902. * @param {Vector3} origin the origin of the explosion
  76903. * @param {number} radius the explosion radius
  76904. * @param {number} strength the explosion strength
  76905. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  76906. */
  76907. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  76908. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  76909. if (!this._physicsEngine) {
  76910. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  76911. return null;
  76912. }
  76913. var impostors = this._physicsEngine.getImpostors();
  76914. if (impostors.length === 0) {
  76915. return null;
  76916. }
  76917. var event = new PhysicsRadialExplosionEvent(this._scene);
  76918. impostors.forEach(function (impostor) {
  76919. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  76920. if (!impostorForceAndContactPoint) {
  76921. return;
  76922. }
  76923. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  76924. });
  76925. event.dispose(false);
  76926. return event;
  76927. };
  76928. /**
  76929. * @param {Vector3} origin the origin of the explosion
  76930. * @param {number} radius the explosion radius
  76931. * @param {number} strength the explosion strength
  76932. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  76933. */
  76934. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  76935. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  76936. if (!this._physicsEngine) {
  76937. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  76938. return null;
  76939. }
  76940. var impostors = this._physicsEngine.getImpostors();
  76941. if (impostors.length === 0) {
  76942. return null;
  76943. }
  76944. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  76945. event.dispose(false);
  76946. return event;
  76947. };
  76948. /**
  76949. * @param {Vector3} origin the origin of the updraft
  76950. * @param {number} radius the radius of the updraft
  76951. * @param {number} strength the strength of the updraft
  76952. * @param {number} height the height of the updraft
  76953. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  76954. */
  76955. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  76956. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  76957. if (!this._physicsEngine) {
  76958. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  76959. return null;
  76960. }
  76961. if (this._physicsEngine.getImpostors().length === 0) {
  76962. return null;
  76963. }
  76964. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  76965. event.dispose(false);
  76966. return event;
  76967. };
  76968. /**
  76969. * @param {Vector3} origin the of the vortex
  76970. * @param {number} radius the radius of the vortex
  76971. * @param {number} strength the strength of the vortex
  76972. * @param {number} height the height of the vortex
  76973. */
  76974. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  76975. if (!this._physicsEngine) {
  76976. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  76977. return null;
  76978. }
  76979. if (this._physicsEngine.getImpostors().length === 0) {
  76980. return null;
  76981. }
  76982. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  76983. event.dispose(false);
  76984. return event;
  76985. };
  76986. return PhysicsHelper;
  76987. }());
  76988. BABYLON.PhysicsHelper = PhysicsHelper;
  76989. /***** Radial explosion *****/
  76990. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  76991. function PhysicsRadialExplosionEvent(scene) {
  76992. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  76993. this._rays = [];
  76994. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  76995. this._scene = scene;
  76996. }
  76997. /**
  76998. * Returns the data related to the radial explosion event (sphere & rays).
  76999. * @returns {PhysicsRadialExplosionEventData}
  77000. */
  77001. PhysicsRadialExplosionEvent.prototype.getData = function () {
  77002. this._dataFetched = true;
  77003. return {
  77004. sphere: this._sphere,
  77005. rays: this._rays,
  77006. };
  77007. };
  77008. /**
  77009. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  77010. * @param impostor
  77011. * @param {Vector3} origin the origin of the explosion
  77012. * @param {number} radius the explosion radius
  77013. * @param {number} strength the explosion strength
  77014. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  77015. * @returns {Nullable<PhysicsForceAndContactPoint>}
  77016. */
  77017. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  77018. if (impostor.mass === 0) {
  77019. return null;
  77020. }
  77021. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  77022. return null;
  77023. }
  77024. if (impostor.object.getClassName() !== 'Mesh') {
  77025. return null;
  77026. }
  77027. var impostorObject = impostor.object;
  77028. var impostorObjectCenter = impostor.getObjectCenter();
  77029. var direction = impostorObjectCenter.subtract(origin);
  77030. var ray = new BABYLON.Ray(origin, direction, radius);
  77031. this._rays.push(ray);
  77032. var hit = ray.intersectsMesh(impostorObject);
  77033. var contactPoint = hit.pickedPoint;
  77034. if (!contactPoint) {
  77035. return null;
  77036. }
  77037. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  77038. if (distanceFromOrigin > radius) {
  77039. return null;
  77040. }
  77041. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  77042. ? strength
  77043. : strength * (1 - (distanceFromOrigin / radius));
  77044. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  77045. return { force: force, contactPoint: contactPoint };
  77046. };
  77047. /**
  77048. * Disposes the sphere.
  77049. * @param {bolean} force
  77050. */
  77051. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  77052. var _this = this;
  77053. if (force === void 0) { force = true; }
  77054. if (force) {
  77055. this._sphere.dispose();
  77056. }
  77057. else {
  77058. setTimeout(function () {
  77059. if (!_this._dataFetched) {
  77060. _this._sphere.dispose();
  77061. }
  77062. }, 0);
  77063. }
  77064. };
  77065. /*** Helpers ***/
  77066. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  77067. if (!this._sphere) {
  77068. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  77069. this._sphere.isVisible = false;
  77070. }
  77071. };
  77072. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  77073. var impostorObject = impostor.object;
  77074. this._prepareSphere();
  77075. this._sphere.position = origin;
  77076. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  77077. this._sphere._updateBoundingInfo();
  77078. this._sphere.computeWorldMatrix(true);
  77079. return this._sphere.intersectsMesh(impostorObject, true);
  77080. };
  77081. return PhysicsRadialExplosionEvent;
  77082. }());
  77083. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  77084. /***** Gravitational Field *****/
  77085. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  77086. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  77087. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  77088. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  77089. this._physicsHelper = physicsHelper;
  77090. this._scene = scene;
  77091. this._origin = origin;
  77092. this._radius = radius;
  77093. this._strength = strength;
  77094. this._falloff = falloff;
  77095. this._tickCallback = this._tick.bind(this);
  77096. }
  77097. /**
  77098. * Returns the data related to the gravitational field event (sphere).
  77099. * @returns {PhysicsGravitationalFieldEventData}
  77100. */
  77101. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  77102. this._dataFetched = true;
  77103. return {
  77104. sphere: this._sphere,
  77105. };
  77106. };
  77107. /**
  77108. * Enables the gravitational field.
  77109. */
  77110. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  77111. this._tickCallback.call(this);
  77112. this._scene.registerBeforeRender(this._tickCallback);
  77113. };
  77114. /**
  77115. * Disables the gravitational field.
  77116. */
  77117. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  77118. this._scene.unregisterBeforeRender(this._tickCallback);
  77119. };
  77120. /**
  77121. * Disposes the sphere.
  77122. * @param {bolean} force
  77123. */
  77124. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  77125. var _this = this;
  77126. if (force === void 0) { force = true; }
  77127. if (force) {
  77128. this._sphere.dispose();
  77129. }
  77130. else {
  77131. setTimeout(function () {
  77132. if (!_this._dataFetched) {
  77133. _this._sphere.dispose();
  77134. }
  77135. }, 0);
  77136. }
  77137. };
  77138. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  77139. // Since the params won't change, we fetch the event only once
  77140. if (this._sphere) {
  77141. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  77142. }
  77143. else {
  77144. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  77145. if (radialExplosionEvent) {
  77146. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  77147. }
  77148. }
  77149. };
  77150. return PhysicsGravitationalFieldEvent;
  77151. }());
  77152. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  77153. /***** Updraft *****/
  77154. var PhysicsUpdraftEvent = /** @class */ (function () {
  77155. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  77156. this._scene = _scene;
  77157. this._origin = _origin;
  77158. this._radius = _radius;
  77159. this._strength = _strength;
  77160. this._height = _height;
  77161. this._updraftMode = _updraftMode;
  77162. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  77163. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  77164. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  77165. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  77166. this._physicsEngine = this._scene.getPhysicsEngine();
  77167. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  77168. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  77169. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  77170. this._originDirection = this._origin.subtract(this._originTop).normalize();
  77171. }
  77172. this._tickCallback = this._tick.bind(this);
  77173. }
  77174. /**
  77175. * Returns the data related to the updraft event (cylinder).
  77176. * @returns {PhysicsUpdraftEventData}
  77177. */
  77178. PhysicsUpdraftEvent.prototype.getData = function () {
  77179. this._dataFetched = true;
  77180. return {
  77181. cylinder: this._cylinder,
  77182. };
  77183. };
  77184. /**
  77185. * Enables the updraft.
  77186. */
  77187. PhysicsUpdraftEvent.prototype.enable = function () {
  77188. this._tickCallback.call(this);
  77189. this._scene.registerBeforeRender(this._tickCallback);
  77190. };
  77191. /**
  77192. * Disables the cortex.
  77193. */
  77194. PhysicsUpdraftEvent.prototype.disable = function () {
  77195. this._scene.unregisterBeforeRender(this._tickCallback);
  77196. };
  77197. /**
  77198. * Disposes the sphere.
  77199. * @param {bolean} force
  77200. */
  77201. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  77202. var _this = this;
  77203. if (force === void 0) { force = true; }
  77204. if (force) {
  77205. this._cylinder.dispose();
  77206. }
  77207. else {
  77208. setTimeout(function () {
  77209. if (!_this._dataFetched) {
  77210. _this._cylinder.dispose();
  77211. }
  77212. }, 0);
  77213. }
  77214. };
  77215. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  77216. if (impostor.mass === 0) {
  77217. return null;
  77218. }
  77219. if (!this._intersectsWithCylinder(impostor)) {
  77220. return null;
  77221. }
  77222. var impostorObjectCenter = impostor.getObjectCenter();
  77223. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  77224. var direction = this._originDirection;
  77225. }
  77226. else {
  77227. var direction = impostorObjectCenter.subtract(this._originTop);
  77228. }
  77229. var multiplier = this._strength * -1;
  77230. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  77231. return { force: force, contactPoint: impostorObjectCenter };
  77232. };
  77233. PhysicsUpdraftEvent.prototype._tick = function () {
  77234. var _this = this;
  77235. this._physicsEngine.getImpostors().forEach(function (impostor) {
  77236. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  77237. if (!impostorForceAndContactPoint) {
  77238. return;
  77239. }
  77240. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  77241. });
  77242. };
  77243. /*** Helpers ***/
  77244. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  77245. if (!this._cylinder) {
  77246. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  77247. height: this._height,
  77248. diameter: this._radius * 2,
  77249. }, this._scene);
  77250. this._cylinder.isVisible = false;
  77251. }
  77252. };
  77253. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  77254. var impostorObject = impostor.object;
  77255. this._prepareCylinder();
  77256. this._cylinder.position = this._cylinderPosition;
  77257. return this._cylinder.intersectsMesh(impostorObject, true);
  77258. };
  77259. return PhysicsUpdraftEvent;
  77260. }());
  77261. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  77262. /***** Vortex *****/
  77263. var PhysicsVortexEvent = /** @class */ (function () {
  77264. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  77265. this._scene = _scene;
  77266. this._origin = _origin;
  77267. this._radius = _radius;
  77268. this._strength = _strength;
  77269. this._height = _height;
  77270. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  77271. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  77272. this._updraftMultiplier = 0.02;
  77273. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  77274. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  77275. this._physicsEngine = this._scene.getPhysicsEngine();
  77276. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  77277. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  77278. this._tickCallback = this._tick.bind(this);
  77279. }
  77280. /**
  77281. * Returns the data related to the vortex event (cylinder).
  77282. * @returns {PhysicsVortexEventData}
  77283. */
  77284. PhysicsVortexEvent.prototype.getData = function () {
  77285. this._dataFetched = true;
  77286. return {
  77287. cylinder: this._cylinder,
  77288. };
  77289. };
  77290. /**
  77291. * Enables the vortex.
  77292. */
  77293. PhysicsVortexEvent.prototype.enable = function () {
  77294. this._tickCallback.call(this);
  77295. this._scene.registerBeforeRender(this._tickCallback);
  77296. };
  77297. /**
  77298. * Disables the cortex.
  77299. */
  77300. PhysicsVortexEvent.prototype.disable = function () {
  77301. this._scene.unregisterBeforeRender(this._tickCallback);
  77302. };
  77303. /**
  77304. * Disposes the sphere.
  77305. * @param {bolean} force
  77306. */
  77307. PhysicsVortexEvent.prototype.dispose = function (force) {
  77308. var _this = this;
  77309. if (force === void 0) { force = true; }
  77310. if (force) {
  77311. this._cylinder.dispose();
  77312. }
  77313. else {
  77314. setTimeout(function () {
  77315. if (!_this._dataFetched) {
  77316. _this._cylinder.dispose();
  77317. }
  77318. }, 0);
  77319. }
  77320. };
  77321. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  77322. if (impostor.mass === 0) {
  77323. return null;
  77324. }
  77325. if (!this._intersectsWithCylinder(impostor)) {
  77326. return null;
  77327. }
  77328. if (impostor.object.getClassName() !== 'Mesh') {
  77329. return null;
  77330. }
  77331. var impostorObject = impostor.object;
  77332. var impostorObjectCenter = impostor.getObjectCenter();
  77333. var originOnPlane = new BABYLON.Vector3(this._origin.x, impostorObjectCenter.y, this._origin.z); // the distance to the origin as if both objects were on a plane (Y-axis)
  77334. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  77335. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  77336. var hit = ray.intersectsMesh(impostorObject);
  77337. var contactPoint = hit.pickedPoint;
  77338. if (!contactPoint) {
  77339. return null;
  77340. }
  77341. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  77342. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  77343. var directionToOrigin = contactPoint.normalize();
  77344. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  77345. directionToOrigin = directionToOrigin.negate();
  77346. }
  77347. // TODO: find a more physically based solution
  77348. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  77349. var forceX = directionToOrigin.x * this._strength / 8;
  77350. var forceY = directionToOrigin.y * this._updraftMultiplier;
  77351. var forceZ = directionToOrigin.z * this._strength / 8;
  77352. }
  77353. else {
  77354. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  77355. var forceY = this._originTop.y * this._updraftMultiplier;
  77356. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  77357. }
  77358. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  77359. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  77360. return { force: force, contactPoint: impostorObjectCenter };
  77361. };
  77362. PhysicsVortexEvent.prototype._tick = function () {
  77363. var _this = this;
  77364. this._physicsEngine.getImpostors().forEach(function (impostor) {
  77365. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  77366. if (!impostorForceAndContactPoint) {
  77367. return;
  77368. }
  77369. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  77370. });
  77371. };
  77372. /*** Helpers ***/
  77373. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  77374. if (!this._cylinder) {
  77375. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  77376. height: this._height,
  77377. diameter: this._radius * 2,
  77378. }, this._scene);
  77379. this._cylinder.isVisible = false;
  77380. }
  77381. };
  77382. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  77383. var impostorObject = impostor.object;
  77384. this._prepareCylinder();
  77385. this._cylinder.position = this._cylinderPosition;
  77386. return this._cylinder.intersectsMesh(impostorObject, true);
  77387. };
  77388. return PhysicsVortexEvent;
  77389. }());
  77390. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  77391. /***** Enums *****/
  77392. /**
  77393. * The strenght of the force in correspondence to the distance of the affected object
  77394. */
  77395. var PhysicsRadialImpulseFalloff;
  77396. (function (PhysicsRadialImpulseFalloff) {
  77397. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  77398. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear"; // impulse gets weaker if it's further from the origin
  77399. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  77400. /**
  77401. * The strenght of the force in correspondence to the distance of the affected object
  77402. */
  77403. var PhysicsUpdraftMode;
  77404. (function (PhysicsUpdraftMode) {
  77405. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  77406. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular"; // once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder
  77407. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  77408. })(BABYLON || (BABYLON = {}));
  77409. //# sourceMappingURL=babylon.physicsHelper.js.map
  77410. var BABYLON;
  77411. (function (BABYLON) {
  77412. var CannonJSPlugin = /** @class */ (function () {
  77413. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  77414. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  77415. if (iterations === void 0) { iterations = 10; }
  77416. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  77417. this.name = "CannonJSPlugin";
  77418. this._physicsMaterials = new Array();
  77419. this._fixedTimeStep = 1 / 60;
  77420. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  77421. this.BJSCANNON = typeof CANNON !== 'undefined' ? CANNON : ( true ? __webpack_require__(17) : undefined);
  77422. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  77423. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  77424. this._tmpPosition = BABYLON.Vector3.Zero();
  77425. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  77426. this._tmpUnityRotation = new BABYLON.Quaternion();
  77427. if (!this.isSupported()) {
  77428. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  77429. return;
  77430. }
  77431. this._extendNamespace();
  77432. this.world = new this.BJSCANNON.World();
  77433. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  77434. this.world.solver.iterations = iterations;
  77435. }
  77436. CannonJSPlugin.prototype.setGravity = function (gravity) {
  77437. this.world.gravity.copy(gravity);
  77438. };
  77439. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  77440. this._fixedTimeStep = timeStep;
  77441. };
  77442. CannonJSPlugin.prototype.getTimeStep = function () {
  77443. return this._fixedTimeStep;
  77444. };
  77445. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  77446. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  77447. };
  77448. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  77449. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  77450. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  77451. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  77452. };
  77453. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  77454. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  77455. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  77456. impostor.physicsBody.applyForce(impulse, worldPoint);
  77457. };
  77458. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  77459. //parent-child relationship. Does this impostor has a parent impostor?
  77460. if (impostor.parent) {
  77461. if (impostor.physicsBody) {
  77462. this.removePhysicsBody(impostor);
  77463. //TODO is that needed?
  77464. impostor.forceUpdate();
  77465. }
  77466. return;
  77467. }
  77468. //should a new body be created for this impostor?
  77469. if (impostor.isBodyInitRequired()) {
  77470. var shape = this._createShape(impostor);
  77471. //unregister events, if body is being changed
  77472. var oldBody = impostor.physicsBody;
  77473. if (oldBody) {
  77474. this.removePhysicsBody(impostor);
  77475. }
  77476. //create the body and material
  77477. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  77478. var bodyCreationObject = {
  77479. mass: impostor.getParam("mass"),
  77480. material: material
  77481. };
  77482. // A simple extend, in case native options were used.
  77483. var nativeOptions = impostor.getParam("nativeOptions");
  77484. for (var key in nativeOptions) {
  77485. if (nativeOptions.hasOwnProperty(key)) {
  77486. bodyCreationObject[key] = nativeOptions[key];
  77487. }
  77488. }
  77489. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  77490. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  77491. this.world.addEventListener("preStep", impostor.beforeStep);
  77492. this.world.addEventListener("postStep", impostor.afterStep);
  77493. impostor.physicsBody.addShape(shape);
  77494. this.world.add(impostor.physicsBody);
  77495. //try to keep the body moving in the right direction by taking old properties.
  77496. //Should be tested!
  77497. if (oldBody) {
  77498. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  77499. impostor.physicsBody[param].copy(oldBody[param]);
  77500. });
  77501. }
  77502. this._processChildMeshes(impostor);
  77503. }
  77504. //now update the body's transformation
  77505. this._updatePhysicsBodyTransformation(impostor);
  77506. };
  77507. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  77508. var _this = this;
  77509. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  77510. var currentRotation = mainImpostor.object.rotationQuaternion;
  77511. if (meshChildren.length) {
  77512. var processMesh = function (localPosition, mesh) {
  77513. if (!currentRotation || !mesh.rotationQuaternion) {
  77514. return;
  77515. }
  77516. var childImpostor = mesh.getPhysicsImpostor();
  77517. if (childImpostor) {
  77518. var parent = childImpostor.parent;
  77519. if (parent !== mainImpostor) {
  77520. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  77521. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  77522. if (childImpostor.physicsBody) {
  77523. _this.removePhysicsBody(childImpostor);
  77524. childImpostor.physicsBody = null;
  77525. }
  77526. childImpostor.parent = mainImpostor;
  77527. childImpostor.resetUpdateFlags();
  77528. mainImpostor.physicsBody.addShape(_this._createShape(childImpostor), new _this.BJSCANNON.Vec3(pPosition.x, pPosition.y, pPosition.z), new _this.BJSCANNON.Quaternion(localRotation.x, localRotation.y, localRotation.z, localRotation.w));
  77529. //Add the mass of the children.
  77530. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  77531. }
  77532. }
  77533. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  77534. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  77535. };
  77536. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  77537. }
  77538. };
  77539. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  77540. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  77541. this.world.removeEventListener("preStep", impostor.beforeStep);
  77542. this.world.removeEventListener("postStep", impostor.afterStep);
  77543. this.world.remove(impostor.physicsBody);
  77544. };
  77545. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  77546. var mainBody = impostorJoint.mainImpostor.physicsBody;
  77547. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  77548. if (!mainBody || !connectedBody) {
  77549. return;
  77550. }
  77551. var constraint;
  77552. var jointData = impostorJoint.joint.jointData;
  77553. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  77554. var constraintData = {
  77555. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  77556. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  77557. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  77558. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  77559. maxForce: jointData.nativeParams.maxForce,
  77560. collideConnected: !!jointData.collision
  77561. };
  77562. switch (impostorJoint.joint.type) {
  77563. case BABYLON.PhysicsJoint.HingeJoint:
  77564. case BABYLON.PhysicsJoint.Hinge2Joint:
  77565. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  77566. break;
  77567. case BABYLON.PhysicsJoint.DistanceJoint:
  77568. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  77569. break;
  77570. case BABYLON.PhysicsJoint.SpringJoint:
  77571. var springData = jointData;
  77572. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  77573. restLength: springData.length,
  77574. stiffness: springData.stiffness,
  77575. damping: springData.damping,
  77576. localAnchorA: constraintData.pivotA,
  77577. localAnchorB: constraintData.pivotB
  77578. });
  77579. break;
  77580. case BABYLON.PhysicsJoint.LockJoint:
  77581. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  77582. break;
  77583. case BABYLON.PhysicsJoint.PointToPointJoint:
  77584. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  77585. default:
  77586. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  77587. break;
  77588. }
  77589. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  77590. constraint.collideConnected = !!jointData.collision;
  77591. impostorJoint.joint.physicsJoint = constraint;
  77592. //don't add spring as constraint, as it is not one.
  77593. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  77594. this.world.addConstraint(constraint);
  77595. }
  77596. else {
  77597. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  77598. constraint.applyForce();
  77599. });
  77600. }
  77601. };
  77602. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  77603. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  77604. };
  77605. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  77606. var index;
  77607. var mat;
  77608. for (index = 0; index < this._physicsMaterials.length; index++) {
  77609. mat = this._physicsMaterials[index];
  77610. if (mat.friction === friction && mat.restitution === restitution) {
  77611. return mat;
  77612. }
  77613. }
  77614. var currentMat = new this.BJSCANNON.Material(name);
  77615. currentMat.friction = friction;
  77616. currentMat.restitution = restitution;
  77617. this._physicsMaterials.push(currentMat);
  77618. return currentMat;
  77619. };
  77620. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  77621. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  77622. };
  77623. CannonJSPlugin.prototype._createShape = function (impostor) {
  77624. var object = impostor.object;
  77625. var returnValue;
  77626. var extendSize = impostor.getObjectExtendSize();
  77627. switch (impostor.type) {
  77628. case BABYLON.PhysicsImpostor.SphereImpostor:
  77629. var radiusX = extendSize.x;
  77630. var radiusY = extendSize.y;
  77631. var radiusZ = extendSize.z;
  77632. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  77633. break;
  77634. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  77635. case BABYLON.PhysicsImpostor.CylinderImpostor:
  77636. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  77637. break;
  77638. case BABYLON.PhysicsImpostor.BoxImpostor:
  77639. var box = extendSize.scale(0.5);
  77640. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  77641. break;
  77642. case BABYLON.PhysicsImpostor.PlaneImpostor:
  77643. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  77644. returnValue = new this.BJSCANNON.Plane();
  77645. break;
  77646. case BABYLON.PhysicsImpostor.MeshImpostor:
  77647. // should transform the vertex data to world coordinates!!
  77648. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  77649. var rawFaces = object.getIndices ? object.getIndices() : [];
  77650. if (!rawVerts)
  77651. return;
  77652. // get only scale! so the object could transform correctly.
  77653. var oldPosition = object.position.clone();
  77654. var oldRotation = object.rotation && object.rotation.clone();
  77655. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  77656. object.position.copyFromFloats(0, 0, 0);
  77657. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  77658. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  77659. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  77660. var transform = object.computeWorldMatrix(true);
  77661. // convert rawVerts to object space
  77662. var temp = new Array();
  77663. var index;
  77664. for (index = 0; index < rawVerts.length; index += 3) {
  77665. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  77666. }
  77667. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  77668. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  77669. //now set back the transformation!
  77670. object.position.copyFrom(oldPosition);
  77671. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  77672. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  77673. break;
  77674. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  77675. var oldPosition2 = object.position.clone();
  77676. var oldRotation2 = object.rotation && object.rotation.clone();
  77677. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  77678. object.position.copyFromFloats(0, 0, 0);
  77679. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  77680. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  77681. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  77682. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  77683. returnValue = this._createHeightmap(object);
  77684. object.position.copyFrom(oldPosition2);
  77685. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  77686. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  77687. object.computeWorldMatrix(true);
  77688. break;
  77689. case BABYLON.PhysicsImpostor.ParticleImpostor:
  77690. returnValue = new this.BJSCANNON.Particle();
  77691. break;
  77692. }
  77693. return returnValue;
  77694. };
  77695. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  77696. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  77697. var transform = object.computeWorldMatrix(true);
  77698. // convert rawVerts to object space
  77699. var temp = new Array();
  77700. var index;
  77701. for (index = 0; index < pos.length; index += 3) {
  77702. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  77703. }
  77704. pos = temp;
  77705. var matrix = new Array();
  77706. //For now pointDepth will not be used and will be automatically calculated.
  77707. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  77708. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  77709. var boundingInfo = object.getBoundingInfo();
  77710. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  77711. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  77712. var elementSize = dim * 2 / arraySize;
  77713. for (var i = 0; i < pos.length; i = i + 3) {
  77714. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  77715. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  77716. var y = -pos[i + 2] + minY;
  77717. if (!matrix[x]) {
  77718. matrix[x] = [];
  77719. }
  77720. if (!matrix[x][z]) {
  77721. matrix[x][z] = y;
  77722. }
  77723. matrix[x][z] = Math.max(y, matrix[x][z]);
  77724. }
  77725. for (var x = 0; x <= arraySize; ++x) {
  77726. if (!matrix[x]) {
  77727. var loc = 1;
  77728. while (!matrix[(x + loc) % arraySize]) {
  77729. loc++;
  77730. }
  77731. matrix[x] = matrix[(x + loc) % arraySize].slice();
  77732. //console.log("missing x", x);
  77733. }
  77734. for (var z = 0; z <= arraySize; ++z) {
  77735. if (!matrix[x][z]) {
  77736. var loc = 1;
  77737. var newValue;
  77738. while (newValue === undefined) {
  77739. newValue = matrix[x][(z + loc++) % arraySize];
  77740. }
  77741. matrix[x][z] = newValue;
  77742. }
  77743. }
  77744. }
  77745. var shape = new this.BJSCANNON.Heightfield(matrix, {
  77746. elementSize: elementSize
  77747. });
  77748. //For future reference, needed for body transformation
  77749. shape.minY = minY;
  77750. return shape;
  77751. };
  77752. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  77753. var object = impostor.object;
  77754. //make sure it is updated...
  77755. object.computeWorldMatrix && object.computeWorldMatrix(true);
  77756. // The delta between the mesh position and the mesh bounding box center
  77757. var bInfo = object.getBoundingInfo();
  77758. if (!bInfo)
  77759. return;
  77760. var center = impostor.getObjectCenter();
  77761. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  77762. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  77763. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  77764. this._tmpPosition.copyFrom(center);
  77765. var quaternion = object.rotationQuaternion;
  77766. if (!quaternion) {
  77767. return;
  77768. }
  77769. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  77770. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  77771. //-90 DEG in X, precalculated
  77772. quaternion = quaternion.multiply(this._minus90X);
  77773. //Invert! (Precalculated, 90 deg in X)
  77774. //No need to clone. this will never change.
  77775. impostor.setDeltaRotation(this._plus90X);
  77776. }
  77777. //If it is a heightfield, if should be centered.
  77778. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  77779. var mesh = object;
  77780. var boundingInfo = mesh.getBoundingInfo();
  77781. //calculate the correct body position:
  77782. var rotationQuaternion = mesh.rotationQuaternion;
  77783. mesh.rotationQuaternion = this._tmpUnityRotation;
  77784. mesh.computeWorldMatrix(true);
  77785. //get original center with no rotation
  77786. var c = center.clone();
  77787. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  77788. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  77789. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  77790. mesh.setPreTransformMatrix(p);
  77791. mesh.computeWorldMatrix(true);
  77792. //calculate the translation
  77793. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  77794. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  77795. //add it inverted to the delta
  77796. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  77797. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  77798. //rotation is back
  77799. mesh.rotationQuaternion = rotationQuaternion;
  77800. mesh.setPreTransformMatrix(oldPivot);
  77801. mesh.computeWorldMatrix(true);
  77802. }
  77803. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  77804. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  77805. //this._tmpPosition.copyFrom(object.position);
  77806. }
  77807. impostor.setDeltaPosition(this._tmpDeltaPosition);
  77808. //Now update the impostor object
  77809. impostor.physicsBody.position.copy(this._tmpPosition);
  77810. impostor.physicsBody.quaternion.copy(quaternion);
  77811. };
  77812. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  77813. impostor.object.position.copyFrom(impostor.physicsBody.position);
  77814. if (impostor.object.rotationQuaternion) {
  77815. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  77816. }
  77817. };
  77818. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  77819. impostor.physicsBody.position.copy(newPosition);
  77820. impostor.physicsBody.quaternion.copy(newRotation);
  77821. };
  77822. CannonJSPlugin.prototype.isSupported = function () {
  77823. return this.BJSCANNON !== undefined;
  77824. };
  77825. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  77826. impostor.physicsBody.velocity.copy(velocity);
  77827. };
  77828. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  77829. impostor.physicsBody.angularVelocity.copy(velocity);
  77830. };
  77831. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  77832. var v = impostor.physicsBody.velocity;
  77833. if (!v) {
  77834. return null;
  77835. }
  77836. return new BABYLON.Vector3(v.x, v.y, v.z);
  77837. };
  77838. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  77839. var v = impostor.physicsBody.angularVelocity;
  77840. if (!v) {
  77841. return null;
  77842. }
  77843. return new BABYLON.Vector3(v.x, v.y, v.z);
  77844. };
  77845. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  77846. impostor.physicsBody.mass = mass;
  77847. impostor.physicsBody.updateMassProperties();
  77848. };
  77849. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  77850. return impostor.physicsBody.mass;
  77851. };
  77852. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  77853. return impostor.physicsBody.material.friction;
  77854. };
  77855. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  77856. impostor.physicsBody.material.friction = friction;
  77857. };
  77858. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  77859. return impostor.physicsBody.material.restitution;
  77860. };
  77861. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  77862. impostor.physicsBody.material.restitution = restitution;
  77863. };
  77864. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  77865. impostor.physicsBody.sleep();
  77866. };
  77867. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  77868. impostor.physicsBody.wakeUp();
  77869. };
  77870. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  77871. joint.physicsJoint.distance = maxDistance;
  77872. };
  77873. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  77874. // if (!motorIndex) {
  77875. // joint.physicsJoint.enableMotor();
  77876. // }
  77877. // }
  77878. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  77879. // if (!motorIndex) {
  77880. // joint.physicsJoint.disableMotor();
  77881. // }
  77882. // }
  77883. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  77884. if (!motorIndex) {
  77885. joint.physicsJoint.enableMotor();
  77886. joint.physicsJoint.setMotorSpeed(speed);
  77887. if (maxForce) {
  77888. this.setLimit(joint, maxForce);
  77889. }
  77890. }
  77891. };
  77892. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  77893. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  77894. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  77895. };
  77896. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  77897. var body = impostor.physicsBody;
  77898. mesh.position.x = body.position.x;
  77899. mesh.position.y = body.position.y;
  77900. mesh.position.z = body.position.z;
  77901. if (mesh.rotationQuaternion) {
  77902. mesh.rotationQuaternion.x = body.quaternion.x;
  77903. mesh.rotationQuaternion.y = body.quaternion.y;
  77904. mesh.rotationQuaternion.z = body.quaternion.z;
  77905. mesh.rotationQuaternion.w = body.quaternion.w;
  77906. }
  77907. };
  77908. CannonJSPlugin.prototype.getRadius = function (impostor) {
  77909. var shape = impostor.physicsBody.shapes[0];
  77910. return shape.boundingSphereRadius;
  77911. };
  77912. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  77913. var shape = impostor.physicsBody.shapes[0];
  77914. result.x = shape.halfExtents.x * 2;
  77915. result.y = shape.halfExtents.y * 2;
  77916. result.z = shape.halfExtents.z * 2;
  77917. };
  77918. CannonJSPlugin.prototype.dispose = function () {
  77919. };
  77920. CannonJSPlugin.prototype._extendNamespace = function () {
  77921. //this will force cannon to execute at least one step when using interpolation
  77922. var step_tmp1 = new this.BJSCANNON.Vec3();
  77923. var Engine = this.BJSCANNON;
  77924. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  77925. maxSubSteps = maxSubSteps || 10;
  77926. timeSinceLastCalled = timeSinceLastCalled || 0;
  77927. if (timeSinceLastCalled === 0) {
  77928. this.internalStep(dt);
  77929. this.time += dt;
  77930. }
  77931. else {
  77932. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  77933. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  77934. var t0 = performance.now();
  77935. for (var i = 0; i !== internalSteps; i++) {
  77936. this.internalStep(dt);
  77937. if (performance.now() - t0 > dt * 1000) {
  77938. break;
  77939. }
  77940. }
  77941. this.time += timeSinceLastCalled;
  77942. var h = this.time % dt;
  77943. var h_div_dt = h / dt;
  77944. var interpvelo = step_tmp1;
  77945. var bodies = this.bodies;
  77946. for (var j = 0; j !== bodies.length; j++) {
  77947. var b = bodies[j];
  77948. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  77949. b.position.vsub(b.previousPosition, interpvelo);
  77950. interpvelo.scale(h_div_dt, interpvelo);
  77951. b.position.vadd(interpvelo, b.interpolatedPosition);
  77952. }
  77953. else {
  77954. b.interpolatedPosition.copy(b.position);
  77955. b.interpolatedQuaternion.copy(b.quaternion);
  77956. }
  77957. }
  77958. }
  77959. };
  77960. };
  77961. return CannonJSPlugin;
  77962. }());
  77963. BABYLON.CannonJSPlugin = CannonJSPlugin;
  77964. })(BABYLON || (BABYLON = {}));
  77965. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  77966. var BABYLON;
  77967. (function (BABYLON) {
  77968. var OimoJSPlugin = /** @class */ (function () {
  77969. function OimoJSPlugin(iterations) {
  77970. this.name = "OimoJSPlugin";
  77971. this._tmpImpostorsArray = [];
  77972. this._tmpPositionVector = BABYLON.Vector3.Zero();
  77973. this.BJSOIMO = typeof OIMO !== 'undefined' ? OIMO : ( true ? __webpack_require__(18) : undefined);
  77974. this.world = new this.BJSOIMO.World(1 / 60, 2, iterations, true);
  77975. this.world.worldscale(1);
  77976. this.world.clear();
  77977. //making sure no stats are calculated
  77978. this.world.isNoStat = true;
  77979. }
  77980. OimoJSPlugin.prototype.setGravity = function (gravity) {
  77981. this.world.gravity.copy(gravity);
  77982. };
  77983. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  77984. this.world.timeStep = timeStep;
  77985. };
  77986. OimoJSPlugin.prototype.getTimeStep = function () {
  77987. return this.world.timeStep;
  77988. };
  77989. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  77990. var _this = this;
  77991. impostors.forEach(function (impostor) {
  77992. impostor.beforeStep();
  77993. });
  77994. this.world.step();
  77995. impostors.forEach(function (impostor) {
  77996. impostor.afterStep();
  77997. //update the ordered impostors array
  77998. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  77999. });
  78000. //check for collisions
  78001. var contact = this.world.contacts;
  78002. while (contact !== null) {
  78003. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  78004. contact = contact.next;
  78005. continue;
  78006. }
  78007. //is this body colliding with any other? get the impostor
  78008. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  78009. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  78010. if (!mainImpostor || !collidingImpostor) {
  78011. contact = contact.next;
  78012. continue;
  78013. }
  78014. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  78015. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  78016. contact = contact.next;
  78017. }
  78018. };
  78019. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  78020. var mass = impostor.physicsBody.massInfo.mass;
  78021. impostor.physicsBody.applyImpulse(contactPoint.scale(this.BJSOIMO.INV_SCALE), force.scale(this.BJSOIMO.INV_SCALE * mass));
  78022. };
  78023. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  78024. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  78025. this.applyImpulse(impostor, force, contactPoint);
  78026. };
  78027. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  78028. var _this = this;
  78029. //parent-child relationship. Does this impostor has a parent impostor?
  78030. if (impostor.parent) {
  78031. if (impostor.physicsBody) {
  78032. this.removePhysicsBody(impostor);
  78033. //TODO is that needed?
  78034. impostor.forceUpdate();
  78035. }
  78036. return;
  78037. }
  78038. if (impostor.isBodyInitRequired()) {
  78039. var bodyConfig = {
  78040. name: impostor.uniqueId,
  78041. //Oimo must have mass, also for static objects.
  78042. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  78043. size: [],
  78044. type: [],
  78045. pos: [],
  78046. rot: [],
  78047. move: impostor.getParam("mass") !== 0,
  78048. //Supporting older versions of Oimo
  78049. world: this.world
  78050. };
  78051. var impostors = [impostor];
  78052. var addToArray = function (parent) {
  78053. if (!parent.getChildMeshes)
  78054. return;
  78055. parent.getChildMeshes().forEach(function (m) {
  78056. if (m.physicsImpostor) {
  78057. impostors.push(m.physicsImpostor);
  78058. //m.physicsImpostor._init();
  78059. }
  78060. });
  78061. };
  78062. addToArray(impostor.object);
  78063. var checkWithEpsilon_1 = function (value) {
  78064. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  78065. };
  78066. impostors.forEach(function (i) {
  78067. if (!impostor.object.rotationQuaternion) {
  78068. return;
  78069. }
  78070. //get the correct bounding box
  78071. var oldQuaternion = i.object.rotationQuaternion;
  78072. var rot = new _this.BJSOIMO.Euler().setFromQuaternion({
  78073. x: impostor.object.rotationQuaternion.x,
  78074. y: impostor.object.rotationQuaternion.y,
  78075. z: impostor.object.rotationQuaternion.z,
  78076. s: impostor.object.rotationQuaternion.w
  78077. });
  78078. var extendSize = i.getObjectExtendSize();
  78079. if (i === impostor) {
  78080. var center = impostor.getObjectCenter();
  78081. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  78082. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  78083. //Can also use Array.prototype.push.apply
  78084. bodyConfig.pos.push(center.x);
  78085. bodyConfig.pos.push(center.y);
  78086. bodyConfig.pos.push(center.z);
  78087. //tmp solution
  78088. bodyConfig.rot.push(rot.x / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  78089. bodyConfig.rot.push(rot.y / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  78090. bodyConfig.rot.push(rot.z / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  78091. }
  78092. else {
  78093. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  78094. bodyConfig.pos.push(localPosition.x);
  78095. bodyConfig.pos.push(localPosition.y);
  78096. bodyConfig.pos.push(localPosition.z);
  78097. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  78098. bodyConfig.rot.push(0);
  78099. bodyConfig.rot.push(0);
  78100. bodyConfig.rot.push(0);
  78101. }
  78102. // register mesh
  78103. switch (i.type) {
  78104. case BABYLON.PhysicsImpostor.ParticleImpostor:
  78105. BABYLON.Tools.Warn("No Particle support in this.BJSOIMO.js. using SphereImpostor instead");
  78106. case BABYLON.PhysicsImpostor.SphereImpostor:
  78107. var radiusX = extendSize.x;
  78108. var radiusY = extendSize.y;
  78109. var radiusZ = extendSize.z;
  78110. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  78111. bodyConfig.type.push('sphere');
  78112. //due to the way oimo works with compounds, add 3 times
  78113. bodyConfig.size.push(size);
  78114. bodyConfig.size.push(size);
  78115. bodyConfig.size.push(size);
  78116. break;
  78117. case BABYLON.PhysicsImpostor.CylinderImpostor:
  78118. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  78119. var sizeY = checkWithEpsilon_1(extendSize.y);
  78120. bodyConfig.type.push('cylinder');
  78121. bodyConfig.size.push(sizeX);
  78122. bodyConfig.size.push(sizeY);
  78123. //due to the way oimo works with compounds, add one more value.
  78124. bodyConfig.size.push(sizeY);
  78125. break;
  78126. case BABYLON.PhysicsImpostor.PlaneImpostor:
  78127. case BABYLON.PhysicsImpostor.BoxImpostor:
  78128. default:
  78129. var sizeX = checkWithEpsilon_1(extendSize.x);
  78130. var sizeY = checkWithEpsilon_1(extendSize.y);
  78131. var sizeZ = checkWithEpsilon_1(extendSize.z);
  78132. bodyConfig.type.push('box');
  78133. bodyConfig.size.push(sizeX);
  78134. bodyConfig.size.push(sizeY);
  78135. bodyConfig.size.push(sizeZ);
  78136. break;
  78137. }
  78138. //actually not needed, but hey...
  78139. i.object.rotationQuaternion = oldQuaternion;
  78140. });
  78141. impostor.physicsBody = new this.BJSOIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  78142. }
  78143. else {
  78144. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  78145. }
  78146. impostor.setDeltaPosition(this._tmpPositionVector);
  78147. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  78148. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  78149. };
  78150. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  78151. //impostor.physicsBody.dispose();
  78152. //Same as : (older oimo versions)
  78153. this.world.removeRigidBody(impostor.physicsBody);
  78154. };
  78155. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  78156. var mainBody = impostorJoint.mainImpostor.physicsBody;
  78157. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  78158. if (!mainBody || !connectedBody) {
  78159. return;
  78160. }
  78161. var jointData = impostorJoint.joint.jointData;
  78162. var options = jointData.nativeParams || {};
  78163. var type;
  78164. var nativeJointData = {
  78165. body1: mainBody,
  78166. body2: connectedBody,
  78167. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  78168. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  78169. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  78170. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  78171. min: options.min,
  78172. max: options.max,
  78173. collision: options.collision || jointData.collision,
  78174. spring: options.spring,
  78175. //supporting older version of Oimo
  78176. world: this.world
  78177. };
  78178. switch (impostorJoint.joint.type) {
  78179. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  78180. type = "jointBall";
  78181. break;
  78182. case BABYLON.PhysicsJoint.SpringJoint:
  78183. BABYLON.Tools.Warn("this.BJSOIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  78184. var springData = jointData;
  78185. nativeJointData.min = springData.length || nativeJointData.min;
  78186. //Max should also be set, just make sure it is at least min
  78187. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  78188. case BABYLON.PhysicsJoint.DistanceJoint:
  78189. type = "jointDistance";
  78190. nativeJointData.max = jointData.maxDistance;
  78191. break;
  78192. case BABYLON.PhysicsJoint.PrismaticJoint:
  78193. type = "jointPrisme";
  78194. break;
  78195. case BABYLON.PhysicsJoint.SliderJoint:
  78196. type = "jointSlide";
  78197. break;
  78198. case BABYLON.PhysicsJoint.WheelJoint:
  78199. type = "jointWheel";
  78200. break;
  78201. case BABYLON.PhysicsJoint.HingeJoint:
  78202. default:
  78203. type = "jointHinge";
  78204. break;
  78205. }
  78206. nativeJointData.type = type;
  78207. impostorJoint.joint.physicsJoint = new this.BJSOIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  78208. };
  78209. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  78210. //Bug in Oimo prevents us from disposing a joint in the playground
  78211. //joint.joint.physicsJoint.dispose();
  78212. //So we will bruteforce it!
  78213. try {
  78214. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  78215. }
  78216. catch (e) {
  78217. BABYLON.Tools.Warn(e);
  78218. }
  78219. };
  78220. OimoJSPlugin.prototype.isSupported = function () {
  78221. return this.BJSOIMO !== undefined;
  78222. };
  78223. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  78224. if (!impostor.physicsBody.sleeping) {
  78225. //TODO check that
  78226. if (impostor.physicsBody.shapes.next) {
  78227. var parentShape = this._getLastShape(impostor.physicsBody);
  78228. impostor.object.position.x = parentShape.position.x * this.BJSOIMO.WORLD_SCALE;
  78229. impostor.object.position.y = parentShape.position.y * this.BJSOIMO.WORLD_SCALE;
  78230. impostor.object.position.z = parentShape.position.z * this.BJSOIMO.WORLD_SCALE;
  78231. }
  78232. else {
  78233. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  78234. }
  78235. if (impostor.object.rotationQuaternion) {
  78236. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  78237. impostor.object.rotationQuaternion.normalize();
  78238. }
  78239. }
  78240. };
  78241. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  78242. var body = impostor.physicsBody;
  78243. body.position.init(newPosition.x * this.BJSOIMO.INV_SCALE, newPosition.y * this.BJSOIMO.INV_SCALE, newPosition.z * this.BJSOIMO.INV_SCALE);
  78244. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  78245. body.syncShapes();
  78246. body.awake();
  78247. };
  78248. OimoJSPlugin.prototype._getLastShape = function (body) {
  78249. var lastShape = body.shapes;
  78250. while (lastShape.next) {
  78251. lastShape = lastShape.next;
  78252. }
  78253. return lastShape;
  78254. };
  78255. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  78256. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  78257. };
  78258. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  78259. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  78260. };
  78261. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  78262. var v = impostor.physicsBody.linearVelocity;
  78263. if (!v) {
  78264. return null;
  78265. }
  78266. return new BABYLON.Vector3(v.x, v.y, v.z);
  78267. };
  78268. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  78269. var v = impostor.physicsBody.angularVelocity;
  78270. if (!v) {
  78271. return null;
  78272. }
  78273. return new BABYLON.Vector3(v.x, v.y, v.z);
  78274. };
  78275. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  78276. var staticBody = mass === 0;
  78277. //this will actually set the body's density and not its mass.
  78278. //But this is how oimo treats the mass variable.
  78279. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  78280. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  78281. };
  78282. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  78283. return impostor.physicsBody.shapes.density;
  78284. };
  78285. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  78286. return impostor.physicsBody.shapes.friction;
  78287. };
  78288. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  78289. impostor.physicsBody.shapes.friction = friction;
  78290. };
  78291. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  78292. return impostor.physicsBody.shapes.restitution;
  78293. };
  78294. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  78295. impostor.physicsBody.shapes.restitution = restitution;
  78296. };
  78297. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  78298. impostor.physicsBody.sleep();
  78299. };
  78300. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  78301. impostor.physicsBody.awake();
  78302. };
  78303. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  78304. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  78305. if (minDistance !== void 0) {
  78306. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  78307. }
  78308. };
  78309. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  78310. //TODO separate rotational and transational motors.
  78311. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  78312. if (motor) {
  78313. motor.setMotor(speed, maxForce);
  78314. }
  78315. };
  78316. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  78317. //TODO separate rotational and transational motors.
  78318. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  78319. if (motor) {
  78320. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  78321. }
  78322. };
  78323. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  78324. var body = impostor.physicsBody;
  78325. mesh.position.x = body.position.x;
  78326. mesh.position.y = body.position.y;
  78327. mesh.position.z = body.position.z;
  78328. if (mesh.rotationQuaternion) {
  78329. mesh.rotationQuaternion.x = body.orientation.x;
  78330. mesh.rotationQuaternion.y = body.orientation.y;
  78331. mesh.rotationQuaternion.z = body.orientation.z;
  78332. mesh.rotationQuaternion.w = body.orientation.s;
  78333. }
  78334. };
  78335. OimoJSPlugin.prototype.getRadius = function (impostor) {
  78336. return impostor.physicsBody.shapes.radius;
  78337. };
  78338. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  78339. var shape = impostor.physicsBody.shapes;
  78340. result.x = shape.halfWidth * 2;
  78341. result.y = shape.halfHeight * 2;
  78342. result.z = shape.halfDepth * 2;
  78343. };
  78344. OimoJSPlugin.prototype.dispose = function () {
  78345. this.world.clear();
  78346. };
  78347. return OimoJSPlugin;
  78348. }());
  78349. BABYLON.OimoJSPlugin = OimoJSPlugin;
  78350. })(BABYLON || (BABYLON = {}));
  78351. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  78352. var BABYLON;
  78353. (function (BABYLON) {
  78354. /*
  78355. * Based on jsTGALoader - Javascript loader for TGA file
  78356. * By Vincent Thibault
  78357. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  78358. */
  78359. var TGATools = /** @class */ (function () {
  78360. function TGATools() {
  78361. }
  78362. TGATools.GetTGAHeader = function (data) {
  78363. var offset = 0;
  78364. var header = {
  78365. id_length: data[offset++],
  78366. colormap_type: data[offset++],
  78367. image_type: data[offset++],
  78368. colormap_index: data[offset++] | data[offset++] << 8,
  78369. colormap_length: data[offset++] | data[offset++] << 8,
  78370. colormap_size: data[offset++],
  78371. origin: [
  78372. data[offset++] | data[offset++] << 8,
  78373. data[offset++] | data[offset++] << 8
  78374. ],
  78375. width: data[offset++] | data[offset++] << 8,
  78376. height: data[offset++] | data[offset++] << 8,
  78377. pixel_size: data[offset++],
  78378. flags: data[offset++]
  78379. };
  78380. return header;
  78381. };
  78382. TGATools.UploadContent = function (gl, data) {
  78383. // Not enough data to contain header ?
  78384. if (data.length < 19) {
  78385. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  78386. return;
  78387. }
  78388. // Read Header
  78389. var offset = 18;
  78390. var header = TGATools.GetTGAHeader(data);
  78391. // Assume it's a valid Targa file.
  78392. if (header.id_length + offset > data.length) {
  78393. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  78394. return;
  78395. }
  78396. // Skip not needed data
  78397. offset += header.id_length;
  78398. var use_rle = false;
  78399. var use_pal = false;
  78400. var use_grey = false;
  78401. // Get some informations.
  78402. switch (header.image_type) {
  78403. case TGATools._TYPE_RLE_INDEXED:
  78404. use_rle = true;
  78405. case TGATools._TYPE_INDEXED:
  78406. use_pal = true;
  78407. break;
  78408. case TGATools._TYPE_RLE_RGB:
  78409. use_rle = true;
  78410. case TGATools._TYPE_RGB:
  78411. // use_rgb = true;
  78412. break;
  78413. case TGATools._TYPE_RLE_GREY:
  78414. use_rle = true;
  78415. case TGATools._TYPE_GREY:
  78416. use_grey = true;
  78417. break;
  78418. }
  78419. var pixel_data;
  78420. // var numAlphaBits = header.flags & 0xf;
  78421. var pixel_size = header.pixel_size >> 3;
  78422. var pixel_total = header.width * header.height * pixel_size;
  78423. // Read palettes
  78424. var palettes;
  78425. if (use_pal) {
  78426. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  78427. }
  78428. // Read LRE
  78429. if (use_rle) {
  78430. pixel_data = new Uint8Array(pixel_total);
  78431. var c, count, i;
  78432. var localOffset = 0;
  78433. var pixels = new Uint8Array(pixel_size);
  78434. while (offset < pixel_total && localOffset < pixel_total) {
  78435. c = data[offset++];
  78436. count = (c & 0x7f) + 1;
  78437. // RLE pixels
  78438. if (c & 0x80) {
  78439. // Bind pixel tmp array
  78440. for (i = 0; i < pixel_size; ++i) {
  78441. pixels[i] = data[offset++];
  78442. }
  78443. // Copy pixel array
  78444. for (i = 0; i < count; ++i) {
  78445. pixel_data.set(pixels, localOffset + i * pixel_size);
  78446. }
  78447. localOffset += pixel_size * count;
  78448. }
  78449. else {
  78450. count *= pixel_size;
  78451. for (i = 0; i < count; ++i) {
  78452. pixel_data[localOffset + i] = data[offset++];
  78453. }
  78454. localOffset += count;
  78455. }
  78456. }
  78457. }
  78458. else {
  78459. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  78460. }
  78461. // Load to texture
  78462. var x_start, y_start, x_step, y_step, y_end, x_end;
  78463. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  78464. default:
  78465. case TGATools._ORIGIN_UL:
  78466. x_start = 0;
  78467. x_step = 1;
  78468. x_end = header.width;
  78469. y_start = 0;
  78470. y_step = 1;
  78471. y_end = header.height;
  78472. break;
  78473. case TGATools._ORIGIN_BL:
  78474. x_start = 0;
  78475. x_step = 1;
  78476. x_end = header.width;
  78477. y_start = header.height - 1;
  78478. y_step = -1;
  78479. y_end = -1;
  78480. break;
  78481. case TGATools._ORIGIN_UR:
  78482. x_start = header.width - 1;
  78483. x_step = -1;
  78484. x_end = -1;
  78485. y_start = 0;
  78486. y_step = 1;
  78487. y_end = header.height;
  78488. break;
  78489. case TGATools._ORIGIN_BR:
  78490. x_start = header.width - 1;
  78491. x_step = -1;
  78492. x_end = -1;
  78493. y_start = header.height - 1;
  78494. y_step = -1;
  78495. y_end = -1;
  78496. break;
  78497. }
  78498. // Load the specify method
  78499. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  78500. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  78501. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  78502. };
  78503. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  78504. var image = pixel_data, colormap = palettes;
  78505. var width = header.width, height = header.height;
  78506. var color, i = 0, x, y;
  78507. var imageData = new Uint8Array(width * height * 4);
  78508. for (y = y_start; y !== y_end; y += y_step) {
  78509. for (x = x_start; x !== x_end; x += x_step, i++) {
  78510. color = image[i];
  78511. imageData[(x + width * y) * 4 + 3] = 255;
  78512. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  78513. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  78514. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  78515. }
  78516. }
  78517. return imageData;
  78518. };
  78519. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  78520. var image = pixel_data;
  78521. var width = header.width, height = header.height;
  78522. var color, i = 0, x, y;
  78523. var imageData = new Uint8Array(width * height * 4);
  78524. for (y = y_start; y !== y_end; y += y_step) {
  78525. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  78526. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  78527. var r = (((color & 0x7C00) >> 10) * 255) / 0x1F | 0;
  78528. var g = (((color & 0x03E0) >> 5) * 255) / 0x1F | 0;
  78529. var b = ((color & 0x001F) * 255) / 0x1F | 0;
  78530. imageData[(x + width * y) * 4 + 0] = r;
  78531. imageData[(x + width * y) * 4 + 1] = g;
  78532. imageData[(x + width * y) * 4 + 2] = b;
  78533. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  78534. }
  78535. }
  78536. return imageData;
  78537. };
  78538. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  78539. var image = pixel_data;
  78540. var width = header.width, height = header.height;
  78541. var i = 0, x, y;
  78542. var imageData = new Uint8Array(width * height * 4);
  78543. for (y = y_start; y !== y_end; y += y_step) {
  78544. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  78545. imageData[(x + width * y) * 4 + 3] = 255;
  78546. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  78547. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  78548. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  78549. }
  78550. }
  78551. return imageData;
  78552. };
  78553. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  78554. var image = pixel_data;
  78555. var width = header.width, height = header.height;
  78556. var i = 0, x, y;
  78557. var imageData = new Uint8Array(width * height * 4);
  78558. for (y = y_start; y !== y_end; y += y_step) {
  78559. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  78560. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  78561. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  78562. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  78563. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  78564. }
  78565. }
  78566. return imageData;
  78567. };
  78568. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  78569. var image = pixel_data;
  78570. var width = header.width, height = header.height;
  78571. var color, i = 0, x, y;
  78572. var imageData = new Uint8Array(width * height * 4);
  78573. for (y = y_start; y !== y_end; y += y_step) {
  78574. for (x = x_start; x !== x_end; x += x_step, i++) {
  78575. color = image[i];
  78576. imageData[(x + width * y) * 4 + 0] = color;
  78577. imageData[(x + width * y) * 4 + 1] = color;
  78578. imageData[(x + width * y) * 4 + 2] = color;
  78579. imageData[(x + width * y) * 4 + 3] = 255;
  78580. }
  78581. }
  78582. return imageData;
  78583. };
  78584. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  78585. var image = pixel_data;
  78586. var width = header.width, height = header.height;
  78587. var i = 0, x, y;
  78588. var imageData = new Uint8Array(width * height * 4);
  78589. for (y = y_start; y !== y_end; y += y_step) {
  78590. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  78591. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  78592. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  78593. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  78594. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  78595. }
  78596. }
  78597. return imageData;
  78598. };
  78599. //private static _TYPE_NO_DATA = 0;
  78600. TGATools._TYPE_INDEXED = 1;
  78601. TGATools._TYPE_RGB = 2;
  78602. TGATools._TYPE_GREY = 3;
  78603. TGATools._TYPE_RLE_INDEXED = 9;
  78604. TGATools._TYPE_RLE_RGB = 10;
  78605. TGATools._TYPE_RLE_GREY = 11;
  78606. TGATools._ORIGIN_MASK = 0x30;
  78607. TGATools._ORIGIN_SHIFT = 0x04;
  78608. TGATools._ORIGIN_BL = 0x00;
  78609. TGATools._ORIGIN_BR = 0x01;
  78610. TGATools._ORIGIN_UL = 0x02;
  78611. TGATools._ORIGIN_UR = 0x03;
  78612. return TGATools;
  78613. }());
  78614. BABYLON.TGATools = TGATools;
  78615. })(BABYLON || (BABYLON = {}));
  78616. //# sourceMappingURL=babylon.tga.js.map
  78617. var BABYLON;
  78618. (function (BABYLON) {
  78619. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  78620. // All values and structures referenced from:
  78621. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  78622. var DDS_MAGIC = 0x20534444;
  78623. var
  78624. //DDSD_CAPS = 0x1,
  78625. //DDSD_HEIGHT = 0x2,
  78626. //DDSD_WIDTH = 0x4,
  78627. //DDSD_PITCH = 0x8,
  78628. //DDSD_PIXELFORMAT = 0x1000,
  78629. DDSD_MIPMAPCOUNT = 0x20000;
  78630. //DDSD_LINEARSIZE = 0x80000,
  78631. //DDSD_DEPTH = 0x800000;
  78632. // var DDSCAPS_COMPLEX = 0x8,
  78633. // DDSCAPS_MIPMAP = 0x400000,
  78634. // DDSCAPS_TEXTURE = 0x1000;
  78635. var DDSCAPS2_CUBEMAP = 0x200;
  78636. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  78637. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  78638. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  78639. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  78640. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  78641. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  78642. // DDSCAPS2_VOLUME = 0x200000;
  78643. var
  78644. //DDPF_ALPHAPIXELS = 0x1,
  78645. //DDPF_ALPHA = 0x2,
  78646. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  78647. //DDPF_YUV = 0x200,
  78648. DDPF_LUMINANCE = 0x20000;
  78649. function FourCCToInt32(value) {
  78650. return value.charCodeAt(0) +
  78651. (value.charCodeAt(1) << 8) +
  78652. (value.charCodeAt(2) << 16) +
  78653. (value.charCodeAt(3) << 24);
  78654. }
  78655. function Int32ToFourCC(value) {
  78656. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  78657. }
  78658. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  78659. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  78660. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  78661. var FOURCC_DX10 = FourCCToInt32("DX10");
  78662. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  78663. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  78664. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  78665. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  78666. var headerLengthInt = 31; // The header length in 32 bit ints
  78667. // Offsets into the header array
  78668. var off_magic = 0;
  78669. var off_size = 1;
  78670. var off_flags = 2;
  78671. var off_height = 3;
  78672. var off_width = 4;
  78673. var off_mipmapCount = 7;
  78674. var off_pfFlags = 20;
  78675. var off_pfFourCC = 21;
  78676. var off_RGBbpp = 22;
  78677. var off_RMask = 23;
  78678. var off_GMask = 24;
  78679. var off_BMask = 25;
  78680. var off_AMask = 26;
  78681. // var off_caps1 = 27;
  78682. var off_caps2 = 28;
  78683. // var off_caps3 = 29;
  78684. // var off_caps4 = 30;
  78685. var off_dxgiFormat = 32;
  78686. ;
  78687. var DDSTools = /** @class */ (function () {
  78688. function DDSTools() {
  78689. }
  78690. DDSTools.GetDDSInfo = function (arrayBuffer) {
  78691. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  78692. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  78693. var mipmapCount = 1;
  78694. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  78695. mipmapCount = Math.max(1, header[off_mipmapCount]);
  78696. }
  78697. var fourCC = header[off_pfFourCC];
  78698. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  78699. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  78700. switch (fourCC) {
  78701. case FOURCC_D3DFMT_R16G16B16A16F:
  78702. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  78703. break;
  78704. case FOURCC_D3DFMT_R32G32B32A32F:
  78705. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  78706. break;
  78707. case FOURCC_DX10:
  78708. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  78709. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  78710. break;
  78711. }
  78712. }
  78713. return {
  78714. width: header[off_width],
  78715. height: header[off_height],
  78716. mipmapCount: mipmapCount,
  78717. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  78718. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  78719. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  78720. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  78721. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  78722. dxgiFormat: dxgiFormat,
  78723. textureType: textureType
  78724. };
  78725. };
  78726. DDSTools._ToHalfFloat = function (value) {
  78727. if (!DDSTools._FloatView) {
  78728. DDSTools._FloatView = new Float32Array(1);
  78729. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  78730. }
  78731. DDSTools._FloatView[0] = value;
  78732. var x = DDSTools._Int32View[0];
  78733. var bits = (x >> 16) & 0x8000; /* Get the sign */
  78734. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  78735. var e = (x >> 23) & 0xff; /* Using int is faster here */
  78736. /* If zero, or denormal, or exponent underflows too much for a denormal
  78737. * half, return signed zero. */
  78738. if (e < 103) {
  78739. return bits;
  78740. }
  78741. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  78742. if (e > 142) {
  78743. bits |= 0x7c00;
  78744. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  78745. * not Inf, so make sure we set one mantissa bit too. */
  78746. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  78747. return bits;
  78748. }
  78749. /* If exponent underflows but not too much, return a denormal */
  78750. if (e < 113) {
  78751. m |= 0x0800;
  78752. /* Extra rounding may overflow and set mantissa to 0 and exponent
  78753. * to 1, which is OK. */
  78754. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  78755. return bits;
  78756. }
  78757. bits |= ((e - 112) << 10) | (m >> 1);
  78758. bits += m & 1;
  78759. return bits;
  78760. };
  78761. DDSTools._FromHalfFloat = function (value) {
  78762. var s = (value & 0x8000) >> 15;
  78763. var e = (value & 0x7C00) >> 10;
  78764. var f = value & 0x03FF;
  78765. if (e === 0) {
  78766. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  78767. }
  78768. else if (e == 0x1F) {
  78769. return f ? NaN : ((s ? -1 : 1) * Infinity);
  78770. }
  78771. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  78772. };
  78773. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  78774. var destArray = new Float32Array(dataLength);
  78775. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  78776. var index = 0;
  78777. for (var y = 0; y < height; y++) {
  78778. for (var x = 0; x < width; x++) {
  78779. var srcPos = (x + y * width) * 4;
  78780. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  78781. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  78782. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  78783. if (DDSTools.StoreLODInAlphaChannel) {
  78784. destArray[index + 3] = lod;
  78785. }
  78786. else {
  78787. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  78788. }
  78789. index += 4;
  78790. }
  78791. }
  78792. return destArray;
  78793. };
  78794. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  78795. if (DDSTools.StoreLODInAlphaChannel) {
  78796. var destArray = new Uint16Array(dataLength);
  78797. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  78798. var index = 0;
  78799. for (var y = 0; y < height; y++) {
  78800. for (var x = 0; x < width; x++) {
  78801. var srcPos = (x + y * width) * 4;
  78802. destArray[index] = srcData[srcPos];
  78803. destArray[index + 1] = srcData[srcPos + 1];
  78804. destArray[index + 2] = srcData[srcPos + 2];
  78805. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  78806. index += 4;
  78807. }
  78808. }
  78809. return destArray;
  78810. }
  78811. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  78812. };
  78813. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  78814. if (DDSTools.StoreLODInAlphaChannel) {
  78815. var destArray = new Float32Array(dataLength);
  78816. var srcData = new Float32Array(arrayBuffer, dataOffset);
  78817. var index = 0;
  78818. for (var y = 0; y < height; y++) {
  78819. for (var x = 0; x < width; x++) {
  78820. var srcPos = (x + y * width) * 4;
  78821. destArray[index] = srcData[srcPos];
  78822. destArray[index + 1] = srcData[srcPos + 1];
  78823. destArray[index + 2] = srcData[srcPos + 2];
  78824. destArray[index + 3] = lod;
  78825. index += 4;
  78826. }
  78827. }
  78828. return destArray;
  78829. }
  78830. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  78831. };
  78832. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  78833. var destArray = new Uint8Array(dataLength);
  78834. var srcData = new Float32Array(arrayBuffer, dataOffset);
  78835. var index = 0;
  78836. for (var y = 0; y < height; y++) {
  78837. for (var x = 0; x < width; x++) {
  78838. var srcPos = (x + y * width) * 4;
  78839. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  78840. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  78841. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  78842. if (DDSTools.StoreLODInAlphaChannel) {
  78843. destArray[index + 3] = lod;
  78844. }
  78845. else {
  78846. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  78847. }
  78848. index += 4;
  78849. }
  78850. }
  78851. return destArray;
  78852. };
  78853. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  78854. var destArray = new Uint8Array(dataLength);
  78855. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  78856. var index = 0;
  78857. for (var y = 0; y < height; y++) {
  78858. for (var x = 0; x < width; x++) {
  78859. var srcPos = (x + y * width) * 4;
  78860. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  78861. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  78862. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  78863. if (DDSTools.StoreLODInAlphaChannel) {
  78864. destArray[index + 3] = lod;
  78865. }
  78866. else {
  78867. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  78868. }
  78869. index += 4;
  78870. }
  78871. }
  78872. return destArray;
  78873. };
  78874. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  78875. var byteArray = new Uint8Array(dataLength);
  78876. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  78877. var index = 0;
  78878. for (var y = 0; y < height; y++) {
  78879. for (var x = 0; x < width; x++) {
  78880. var srcPos = (x + y * width) * 4;
  78881. byteArray[index] = srcData[srcPos + rOffset];
  78882. byteArray[index + 1] = srcData[srcPos + gOffset];
  78883. byteArray[index + 2] = srcData[srcPos + bOffset];
  78884. byteArray[index + 3] = srcData[srcPos + aOffset];
  78885. index += 4;
  78886. }
  78887. }
  78888. return byteArray;
  78889. };
  78890. DDSTools._ExtractLongWordOrder = function (value) {
  78891. if (value === 0 || value === 255 || value === -16777216) {
  78892. return 0;
  78893. }
  78894. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  78895. };
  78896. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  78897. var byteArray = new Uint8Array(dataLength);
  78898. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  78899. var index = 0;
  78900. for (var y = 0; y < height; y++) {
  78901. for (var x = 0; x < width; x++) {
  78902. var srcPos = (x + y * width) * 3;
  78903. byteArray[index] = srcData[srcPos + rOffset];
  78904. byteArray[index + 1] = srcData[srcPos + gOffset];
  78905. byteArray[index + 2] = srcData[srcPos + bOffset];
  78906. index += 3;
  78907. }
  78908. }
  78909. return byteArray;
  78910. };
  78911. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  78912. var byteArray = new Uint8Array(dataLength);
  78913. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  78914. var index = 0;
  78915. for (var y = 0; y < height; y++) {
  78916. for (var x = 0; x < width; x++) {
  78917. var srcPos = (x + y * width);
  78918. byteArray[index] = srcData[srcPos];
  78919. index++;
  78920. }
  78921. }
  78922. return byteArray;
  78923. };
  78924. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  78925. if (lodIndex === void 0) { lodIndex = -1; }
  78926. var ext = engine.getCaps().s3tc;
  78927. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  78928. var fourCC, width, height, dataLength = 0, dataOffset;
  78929. var byteArray, mipmapCount, mip;
  78930. var internalFormat = 0;
  78931. var format = 0;
  78932. var blockBytes = 1;
  78933. if (header[off_magic] !== DDS_MAGIC) {
  78934. BABYLON.Tools.Error("Invalid magic number in DDS header");
  78935. return;
  78936. }
  78937. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  78938. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  78939. return;
  78940. }
  78941. if (info.isCompressed && !ext) {
  78942. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  78943. return;
  78944. }
  78945. var bpp = header[off_RGBbpp];
  78946. dataOffset = header[off_size] + 4;
  78947. var computeFormats = false;
  78948. if (info.isFourCC) {
  78949. fourCC = header[off_pfFourCC];
  78950. switch (fourCC) {
  78951. case FOURCC_DXT1:
  78952. blockBytes = 8;
  78953. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  78954. break;
  78955. case FOURCC_DXT3:
  78956. blockBytes = 16;
  78957. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  78958. break;
  78959. case FOURCC_DXT5:
  78960. blockBytes = 16;
  78961. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  78962. break;
  78963. case FOURCC_D3DFMT_R16G16B16A16F:
  78964. computeFormats = true;
  78965. break;
  78966. case FOURCC_D3DFMT_R32G32B32A32F:
  78967. computeFormats = true;
  78968. break;
  78969. case FOURCC_DX10:
  78970. // There is an additionnal header so dataOffset need to be changed
  78971. dataOffset += 5 * 4; // 5 uints
  78972. var supported = false;
  78973. switch (info.dxgiFormat) {
  78974. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  78975. computeFormats = true;
  78976. supported = true;
  78977. break;
  78978. case DXGI_FORMAT_B8G8R8X8_UNORM:
  78979. info.isRGB = true;
  78980. info.isFourCC = false;
  78981. bpp = 32;
  78982. supported = true;
  78983. break;
  78984. }
  78985. if (supported) {
  78986. break;
  78987. }
  78988. default:
  78989. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  78990. return;
  78991. }
  78992. }
  78993. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  78994. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  78995. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  78996. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  78997. if (computeFormats) {
  78998. format = engine._getWebGLTextureType(info.textureType);
  78999. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  79000. }
  79001. mipmapCount = 1;
  79002. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  79003. mipmapCount = Math.max(1, header[off_mipmapCount]);
  79004. }
  79005. for (var face = 0; face < faces; face++) {
  79006. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face + (currentFace ? currentFace : 0));
  79007. width = header[off_width];
  79008. height = header[off_height];
  79009. for (mip = 0; mip < mipmapCount; ++mip) {
  79010. if (lodIndex === -1 || lodIndex === mip) {
  79011. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  79012. var i = (lodIndex === -1) ? mip : 0;
  79013. if (!info.isCompressed && info.isFourCC) {
  79014. dataLength = width * height * 4;
  79015. var floatArray = null;
  79016. if (engine.badOS || engine.badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) {
  79017. if (bpp === 128) {
  79018. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  79019. }
  79020. else if (bpp === 64) {
  79021. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  79022. }
  79023. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  79024. format = engine._getWebGLTextureType(info.textureType);
  79025. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  79026. }
  79027. else {
  79028. if (bpp === 128) {
  79029. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  79030. }
  79031. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  79032. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  79033. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  79034. format = engine._getWebGLTextureType(info.textureType);
  79035. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  79036. }
  79037. else {
  79038. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  79039. }
  79040. }
  79041. if (floatArray) {
  79042. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  79043. }
  79044. }
  79045. else if (info.isRGB) {
  79046. if (bpp === 24) {
  79047. dataLength = width * height * 3;
  79048. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  79049. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  79050. }
  79051. else {
  79052. dataLength = width * height * 4;
  79053. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  79054. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  79055. }
  79056. }
  79057. else if (info.isLuminance) {
  79058. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  79059. var unpaddedRowSize = width;
  79060. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  79061. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  79062. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  79063. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  79064. }
  79065. else {
  79066. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  79067. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  79068. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  79069. }
  79070. }
  79071. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  79072. width *= 0.5;
  79073. height *= 0.5;
  79074. width = Math.max(1.0, width);
  79075. height = Math.max(1.0, height);
  79076. }
  79077. if (currentFace !== undefined) {
  79078. // Loading a single face
  79079. break;
  79080. }
  79081. }
  79082. };
  79083. DDSTools.StoreLODInAlphaChannel = false;
  79084. return DDSTools;
  79085. }());
  79086. BABYLON.DDSTools = DDSTools;
  79087. })(BABYLON || (BABYLON = {}));
  79088. //# sourceMappingURL=babylon.dds.js.map
  79089. var BABYLON;
  79090. (function (BABYLON) {
  79091. /**
  79092. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  79093. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  79094. */
  79095. var KhronosTextureContainer = /** @class */ (function () {
  79096. /**
  79097. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  79098. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  79099. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  79100. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  79101. */
  79102. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  79103. this.arrayBuffer = arrayBuffer;
  79104. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  79105. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  79106. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  79107. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  79108. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  79109. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  79110. BABYLON.Tools.Error("texture missing KTX identifier");
  79111. return;
  79112. }
  79113. // load the reset of the header in native 32 bit int
  79114. var header = new Int32Array(this.arrayBuffer, 12, 13);
  79115. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  79116. var oppositeEndianess = header[0] === 0x01020304;
  79117. // read all the header elements in order they exist in the file, without modification (sans endainness)
  79118. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  79119. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  79120. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  79121. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  79122. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  79123. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  79124. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  79125. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  79126. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  79127. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  79128. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  79129. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  79130. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  79131. if (this.glType !== 0) {
  79132. BABYLON.Tools.Error("only compressed formats currently supported");
  79133. return;
  79134. }
  79135. else {
  79136. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  79137. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  79138. }
  79139. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  79140. BABYLON.Tools.Error("only 2D textures currently supported");
  79141. return;
  79142. }
  79143. if (this.numberOfArrayElements !== 0) {
  79144. BABYLON.Tools.Error("texture arrays not currently supported");
  79145. return;
  79146. }
  79147. if (this.numberOfFaces !== facesExpected) {
  79148. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  79149. return;
  79150. }
  79151. // we now have a completely validated file, so could use existence of loadType as success
  79152. // would need to make this more elaborate & adjust checks above to support more than one load type
  79153. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  79154. }
  79155. // not as fast hardware based, but will probably never need to use
  79156. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  79157. return ((val & 0xFF) << 24)
  79158. | ((val & 0xFF00) << 8)
  79159. | ((val >> 8) & 0xFF00)
  79160. | ((val >> 24) & 0xFF);
  79161. };
  79162. /**
  79163. * It is assumed that the texture has already been created & is currently bound
  79164. */
  79165. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  79166. switch (this.loadType) {
  79167. case KhronosTextureContainer.COMPRESSED_2D:
  79168. this._upload2DCompressedLevels(gl, loadMipmaps);
  79169. break;
  79170. case KhronosTextureContainer.TEX_2D:
  79171. case KhronosTextureContainer.COMPRESSED_3D:
  79172. case KhronosTextureContainer.TEX_3D:
  79173. }
  79174. };
  79175. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  79176. // initialize width & height for level 1
  79177. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  79178. var width = this.pixelWidth;
  79179. var height = this.pixelHeight;
  79180. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  79181. for (var level = 0; level < mipmapCount; level++) {
  79182. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  79183. for (var face = 0; face < this.numberOfFaces; face++) {
  79184. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  79185. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  79186. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  79187. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  79188. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  79189. }
  79190. width = Math.max(1.0, width * 0.5);
  79191. height = Math.max(1.0, height * 0.5);
  79192. }
  79193. };
  79194. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  79195. // load types
  79196. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  79197. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  79198. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  79199. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  79200. return KhronosTextureContainer;
  79201. }());
  79202. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  79203. })(BABYLON || (BABYLON = {}));
  79204. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  79205. var BABYLON;
  79206. (function (BABYLON) {
  79207. var Debug = /** @class */ (function () {
  79208. function Debug() {
  79209. }
  79210. Debug.AxesViewer = /** @class */ (function () {
  79211. function AxesViewer(scene, scaleLines) {
  79212. if (scaleLines === void 0) { scaleLines = 1; }
  79213. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  79214. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  79215. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  79216. this.scaleLines = 1;
  79217. this.scaleLines = scaleLines;
  79218. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  79219. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  79220. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  79221. this._xmesh.renderingGroupId = 2;
  79222. this._ymesh.renderingGroupId = 2;
  79223. this._zmesh.renderingGroupId = 2;
  79224. this._xmesh.material.checkReadyOnlyOnce = true;
  79225. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  79226. this._ymesh.material.checkReadyOnlyOnce = true;
  79227. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  79228. this._zmesh.material.checkReadyOnlyOnce = true;
  79229. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  79230. this.scene = scene;
  79231. }
  79232. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  79233. var scaleLines = this.scaleLines;
  79234. if (this._xmesh) {
  79235. this._xmesh.position.copyFrom(position);
  79236. }
  79237. if (this._ymesh) {
  79238. this._ymesh.position.copyFrom(position);
  79239. }
  79240. if (this._zmesh) {
  79241. this._zmesh.position.copyFrom(position);
  79242. }
  79243. var point2 = this._xline[1];
  79244. point2.x = xaxis.x * scaleLines;
  79245. point2.y = xaxis.y * scaleLines;
  79246. point2.z = xaxis.z * scaleLines;
  79247. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  79248. point2 = this._yline[1];
  79249. point2.x = yaxis.x * scaleLines;
  79250. point2.y = yaxis.y * scaleLines;
  79251. point2.z = yaxis.z * scaleLines;
  79252. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  79253. point2 = this._zline[1];
  79254. point2.x = zaxis.x * scaleLines;
  79255. point2.y = zaxis.y * scaleLines;
  79256. point2.z = zaxis.z * scaleLines;
  79257. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  79258. };
  79259. AxesViewer.prototype.dispose = function () {
  79260. if (this._xmesh) {
  79261. this._xmesh.dispose();
  79262. }
  79263. if (this._ymesh) {
  79264. this._ymesh.dispose();
  79265. }
  79266. if (this._zmesh) {
  79267. this._zmesh.dispose();
  79268. }
  79269. this._xmesh = null;
  79270. this._ymesh = null;
  79271. this._zmesh = null;
  79272. this.scene = null;
  79273. };
  79274. return AxesViewer;
  79275. }());
  79276. Debug.BoneAxesViewer = /** @class */ (function (_super) {
  79277. __extends(BoneAxesViewer, _super);
  79278. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  79279. if (scaleLines === void 0) { scaleLines = 1; }
  79280. var _this = _super.call(this, scene, scaleLines) || this;
  79281. _this.pos = BABYLON.Vector3.Zero();
  79282. _this.xaxis = BABYLON.Vector3.Zero();
  79283. _this.yaxis = BABYLON.Vector3.Zero();
  79284. _this.zaxis = BABYLON.Vector3.Zero();
  79285. _this.mesh = mesh;
  79286. _this.bone = bone;
  79287. return _this;
  79288. }
  79289. BoneAxesViewer.prototype.update = function () {
  79290. if (!this.mesh || !this.bone) {
  79291. return;
  79292. }
  79293. var bone = this.bone;
  79294. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  79295. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  79296. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  79297. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  79298. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  79299. };
  79300. BoneAxesViewer.prototype.dispose = function () {
  79301. if (this.mesh) {
  79302. this.mesh = null;
  79303. this.bone = null;
  79304. _super.prototype.dispose.call(this);
  79305. }
  79306. };
  79307. return BoneAxesViewer;
  79308. }(Debug.AxesViewer));
  79309. Debug.PhysicsViewer = /** @class */ (function () {
  79310. function PhysicsViewer(scene) {
  79311. this._impostors = [];
  79312. this._meshes = [];
  79313. this._numMeshes = 0;
  79314. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  79315. var physicEngine = this._scene.getPhysicsEngine();
  79316. if (physicEngine) {
  79317. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  79318. }
  79319. }
  79320. PhysicsViewer.prototype._updateDebugMeshes = function () {
  79321. var plugin = this._physicsEnginePlugin;
  79322. for (var i = 0; i < this._numMeshes; i++) {
  79323. var impostor = this._impostors[i];
  79324. if (!impostor) {
  79325. continue;
  79326. }
  79327. if (impostor.isDisposed) {
  79328. this.hideImpostor(this._impostors[i--]);
  79329. }
  79330. else {
  79331. var mesh = this._meshes[i];
  79332. if (mesh && plugin) {
  79333. plugin.syncMeshWithImpostor(mesh, impostor);
  79334. }
  79335. }
  79336. }
  79337. };
  79338. PhysicsViewer.prototype.showImpostor = function (impostor) {
  79339. if (!this._scene) {
  79340. return;
  79341. }
  79342. for (var i = 0; i < this._numMeshes; i++) {
  79343. if (this._impostors[i] == impostor) {
  79344. return;
  79345. }
  79346. }
  79347. var debugMesh = this._getDebugMesh(impostor, this._scene);
  79348. if (debugMesh) {
  79349. this._impostors[this._numMeshes] = impostor;
  79350. this._meshes[this._numMeshes] = debugMesh;
  79351. if (this._numMeshes === 0) {
  79352. this._renderFunction = this._updateDebugMeshes.bind(this);
  79353. this._scene.registerBeforeRender(this._renderFunction);
  79354. }
  79355. this._numMeshes++;
  79356. }
  79357. };
  79358. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  79359. if (!impostor || !this._scene) {
  79360. return;
  79361. }
  79362. var removed = false;
  79363. for (var i = 0; i < this._numMeshes; i++) {
  79364. if (this._impostors[i] == impostor) {
  79365. var mesh = this._meshes[i];
  79366. if (!mesh) {
  79367. continue;
  79368. }
  79369. this._scene.removeMesh(mesh);
  79370. mesh.dispose();
  79371. this._numMeshes--;
  79372. if (this._numMeshes > 0) {
  79373. this._meshes[i] = this._meshes[this._numMeshes];
  79374. this._impostors[i] = this._impostors[this._numMeshes];
  79375. this._meshes[this._numMeshes] = null;
  79376. this._impostors[this._numMeshes] = null;
  79377. }
  79378. else {
  79379. this._meshes[0] = null;
  79380. this._impostors[0] = null;
  79381. }
  79382. removed = true;
  79383. break;
  79384. }
  79385. }
  79386. if (removed && this._numMeshes === 0) {
  79387. this._scene.unregisterBeforeRender(this._renderFunction);
  79388. }
  79389. };
  79390. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  79391. if (!this._debugMaterial) {
  79392. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  79393. this._debugMaterial.wireframe = true;
  79394. }
  79395. return this._debugMaterial;
  79396. };
  79397. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  79398. if (!this._debugBoxMesh) {
  79399. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  79400. this._debugBoxMesh.renderingGroupId = 1;
  79401. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  79402. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  79403. scene.removeMesh(this._debugBoxMesh);
  79404. }
  79405. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  79406. };
  79407. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  79408. if (!this._debugSphereMesh) {
  79409. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  79410. this._debugSphereMesh.renderingGroupId = 1;
  79411. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  79412. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  79413. scene.removeMesh(this._debugSphereMesh);
  79414. }
  79415. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  79416. };
  79417. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  79418. var mesh = null;
  79419. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  79420. mesh = this._getDebugBoxMesh(scene);
  79421. impostor.getBoxSizeToRef(mesh.scaling);
  79422. }
  79423. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  79424. mesh = this._getDebugSphereMesh(scene);
  79425. var radius = impostor.getRadius();
  79426. mesh.scaling.x = radius * 2;
  79427. mesh.scaling.y = radius * 2;
  79428. mesh.scaling.z = radius * 2;
  79429. }
  79430. return mesh;
  79431. };
  79432. PhysicsViewer.prototype.dispose = function () {
  79433. for (var i = 0; i < this._numMeshes; i++) {
  79434. this.hideImpostor(this._impostors[i]);
  79435. }
  79436. if (this._debugBoxMesh) {
  79437. this._debugBoxMesh.dispose();
  79438. }
  79439. if (this._debugSphereMesh) {
  79440. this._debugSphereMesh.dispose();
  79441. }
  79442. if (this._debugMaterial) {
  79443. this._debugMaterial.dispose();
  79444. }
  79445. this._impostors.length = 0;
  79446. this._scene = null;
  79447. this._physicsEnginePlugin = null;
  79448. };
  79449. return PhysicsViewer;
  79450. }());
  79451. Debug.SkeletonViewer = /** @class */ (function () {
  79452. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  79453. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  79454. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  79455. this.skeleton = skeleton;
  79456. this.mesh = mesh;
  79457. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  79458. this.renderingGroupId = renderingGroupId;
  79459. this.color = BABYLON.Color3.White();
  79460. this._debugLines = new Array();
  79461. this._isEnabled = false;
  79462. this._scene = scene;
  79463. this.update();
  79464. this._renderFunction = this.update.bind(this);
  79465. }
  79466. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  79467. get: function () {
  79468. return this._isEnabled;
  79469. },
  79470. set: function (value) {
  79471. if (this._isEnabled === value) {
  79472. return;
  79473. }
  79474. this._isEnabled = value;
  79475. if (value) {
  79476. this._scene.registerBeforeRender(this._renderFunction);
  79477. }
  79478. else {
  79479. this._scene.unregisterBeforeRender(this._renderFunction);
  79480. }
  79481. },
  79482. enumerable: true,
  79483. configurable: true
  79484. });
  79485. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  79486. if (x === void 0) { x = 0; }
  79487. if (y === void 0) { y = 0; }
  79488. if (z === void 0) { z = 0; }
  79489. var tmat = BABYLON.Tmp.Matrix[0];
  79490. var parentBone = bone.getParent();
  79491. tmat.copyFrom(bone.getLocalMatrix());
  79492. if (x !== 0 || y !== 0 || z !== 0) {
  79493. var tmat2 = BABYLON.Tmp.Matrix[1];
  79494. BABYLON.Matrix.IdentityToRef(tmat2);
  79495. tmat2.m[12] = x;
  79496. tmat2.m[13] = y;
  79497. tmat2.m[14] = z;
  79498. tmat2.multiplyToRef(tmat, tmat);
  79499. }
  79500. if (parentBone) {
  79501. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  79502. }
  79503. tmat.multiplyToRef(meshMat, tmat);
  79504. position.x = tmat.m[12];
  79505. position.y = tmat.m[13];
  79506. position.z = tmat.m[14];
  79507. };
  79508. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  79509. var len = bones.length;
  79510. var meshPos = this.mesh.position;
  79511. for (var i = 0; i < len; i++) {
  79512. var bone = bones[i];
  79513. var points = this._debugLines[i];
  79514. if (!points) {
  79515. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  79516. this._debugLines[i] = points;
  79517. }
  79518. this._getBonePosition(points[0], bone, meshMat);
  79519. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  79520. points[0].subtractInPlace(meshPos);
  79521. points[1].subtractInPlace(meshPos);
  79522. }
  79523. };
  79524. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  79525. var len = bones.length;
  79526. var boneNum = 0;
  79527. var meshPos = this.mesh.position;
  79528. for (var i = len - 1; i >= 0; i--) {
  79529. var childBone = bones[i];
  79530. var parentBone = childBone.getParent();
  79531. if (!parentBone) {
  79532. continue;
  79533. }
  79534. var points = this._debugLines[boneNum];
  79535. if (!points) {
  79536. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  79537. this._debugLines[boneNum] = points;
  79538. }
  79539. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  79540. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  79541. points[0].subtractInPlace(meshPos);
  79542. points[1].subtractInPlace(meshPos);
  79543. boneNum++;
  79544. }
  79545. };
  79546. SkeletonViewer.prototype.update = function () {
  79547. if (this.autoUpdateBonesMatrices) {
  79548. this.skeleton.computeAbsoluteTransforms();
  79549. }
  79550. if (this.skeleton.bones[0].length === undefined) {
  79551. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  79552. }
  79553. else {
  79554. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  79555. }
  79556. if (!this._debugMesh) {
  79557. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  79558. this._debugMesh.renderingGroupId = this.renderingGroupId;
  79559. }
  79560. else {
  79561. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  79562. }
  79563. this._debugMesh.position.copyFrom(this.mesh.position);
  79564. this._debugMesh.color = this.color;
  79565. };
  79566. SkeletonViewer.prototype.dispose = function () {
  79567. if (this._debugMesh) {
  79568. this.isEnabled = false;
  79569. this._debugMesh.dispose();
  79570. this._debugMesh = null;
  79571. }
  79572. };
  79573. return SkeletonViewer;
  79574. }());
  79575. return Debug;
  79576. }());
  79577. BABYLON.Debug = Debug;
  79578. })(BABYLON || (BABYLON = {}));
  79579. //# sourceMappingURL=babylon.debugModules.js.map
  79580. var BABYLON;
  79581. (function (BABYLON) {
  79582. var RayHelper = /** @class */ (function () {
  79583. function RayHelper(ray) {
  79584. this.ray = ray;
  79585. }
  79586. RayHelper.CreateAndShow = function (ray, scene, color) {
  79587. var helper = new RayHelper(ray);
  79588. helper.show(scene, color);
  79589. return helper;
  79590. };
  79591. RayHelper.prototype.show = function (scene, color) {
  79592. if (!this._renderFunction && this.ray) {
  79593. var ray = this.ray;
  79594. this._renderFunction = this._render.bind(this);
  79595. this._scene = scene;
  79596. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  79597. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  79598. if (this._renderFunction) {
  79599. this._scene.registerBeforeRender(this._renderFunction);
  79600. }
  79601. }
  79602. if (color && this._renderLine) {
  79603. this._renderLine.color.copyFrom(color);
  79604. }
  79605. };
  79606. RayHelper.prototype.hide = function () {
  79607. if (this._renderFunction && this._scene) {
  79608. this._scene.unregisterBeforeRender(this._renderFunction);
  79609. this._scene = null;
  79610. this._renderFunction = null;
  79611. if (this._renderLine) {
  79612. this._renderLine.dispose();
  79613. this._renderLine = null;
  79614. }
  79615. this._renderPoints = [];
  79616. }
  79617. };
  79618. RayHelper.prototype._render = function () {
  79619. var ray = this.ray;
  79620. if (!ray) {
  79621. return;
  79622. }
  79623. var point = this._renderPoints[1];
  79624. var len = Math.min(ray.length, 1000000);
  79625. point.copyFrom(ray.direction);
  79626. point.scaleInPlace(len);
  79627. point.addInPlace(ray.origin);
  79628. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  79629. };
  79630. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  79631. this._attachedToMesh = mesh;
  79632. var ray = this.ray;
  79633. if (!ray) {
  79634. return;
  79635. }
  79636. if (!ray.direction) {
  79637. ray.direction = BABYLON.Vector3.Zero();
  79638. }
  79639. if (!ray.origin) {
  79640. ray.origin = BABYLON.Vector3.Zero();
  79641. }
  79642. if (length) {
  79643. ray.length = length;
  79644. }
  79645. if (!meshSpaceOrigin) {
  79646. meshSpaceOrigin = BABYLON.Vector3.Zero();
  79647. }
  79648. if (!meshSpaceDirection) {
  79649. // -1 so that this will work with Mesh.lookAt
  79650. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  79651. }
  79652. if (!this._meshSpaceDirection) {
  79653. this._meshSpaceDirection = meshSpaceDirection.clone();
  79654. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  79655. }
  79656. else {
  79657. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  79658. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  79659. }
  79660. if (!this._updateToMeshFunction) {
  79661. this._updateToMeshFunction = this._updateToMesh.bind(this);
  79662. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  79663. }
  79664. this._updateToMesh();
  79665. };
  79666. RayHelper.prototype.detachFromMesh = function () {
  79667. if (this._attachedToMesh) {
  79668. if (this._updateToMeshFunction) {
  79669. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  79670. }
  79671. this._attachedToMesh = null;
  79672. this._updateToMeshFunction = null;
  79673. }
  79674. };
  79675. RayHelper.prototype._updateToMesh = function () {
  79676. var ray = this.ray;
  79677. if (!this._attachedToMesh || !ray) {
  79678. return;
  79679. }
  79680. if (this._attachedToMesh._isDisposed) {
  79681. this.detachFromMesh();
  79682. return;
  79683. }
  79684. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  79685. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  79686. };
  79687. RayHelper.prototype.dispose = function () {
  79688. this.hide();
  79689. this.detachFromMesh();
  79690. this.ray = null;
  79691. };
  79692. return RayHelper;
  79693. }());
  79694. BABYLON.RayHelper = RayHelper;
  79695. })(BABYLON || (BABYLON = {}));
  79696. //# sourceMappingURL=babylon.rayHelper.js.map
  79697. var BABYLON;
  79698. (function (BABYLON) {
  79699. // load the inspector using require, if not present in the global namespace.
  79700. var DebugLayer = /** @class */ (function () {
  79701. function DebugLayer(scene) {
  79702. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  79703. this._scene = scene;
  79704. // load inspector using require, if it doesn't exist on the global namespace.
  79705. }
  79706. /** Creates the inspector window. */
  79707. DebugLayer.prototype._createInspector = function (config) {
  79708. if (config === void 0) { config = {}; }
  79709. var popup = config.popup || false;
  79710. var initialTab = config.initialTab || 0;
  79711. var parentElement = config.parentElement || null;
  79712. if (!this._inspector) {
  79713. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  79714. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  79715. } // else nothing to do,; instance is already existing
  79716. };
  79717. DebugLayer.prototype.isVisible = function () {
  79718. if (!this._inspector) {
  79719. return false;
  79720. }
  79721. return true;
  79722. };
  79723. DebugLayer.prototype.hide = function () {
  79724. if (this._inspector) {
  79725. try {
  79726. this._inspector.dispose();
  79727. }
  79728. catch (e) {
  79729. // If the inspector has been removed directly from the inspector tool
  79730. }
  79731. this._inspector = null;
  79732. }
  79733. };
  79734. DebugLayer.prototype.show = function (config) {
  79735. if (config === void 0) { config = {}; }
  79736. if (typeof this.BJSINSPECTOR == 'undefined') {
  79737. // Load inspector and add it to the DOM
  79738. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  79739. }
  79740. else {
  79741. // Otherwise creates the inspector
  79742. this._createInspector(config);
  79743. }
  79744. };
  79745. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  79746. return DebugLayer;
  79747. }());
  79748. BABYLON.DebugLayer = DebugLayer;
  79749. })(BABYLON || (BABYLON = {}));
  79750. //# sourceMappingURL=babylon.debugLayer.js.map
  79751. var BABYLON;
  79752. (function (BABYLON) {
  79753. var BoundingBoxRenderer = /** @class */ (function () {
  79754. function BoundingBoxRenderer(scene) {
  79755. this.frontColor = new BABYLON.Color3(1, 1, 1);
  79756. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  79757. this.showBackLines = true;
  79758. this.renderList = new BABYLON.SmartArray(32);
  79759. this._vertexBuffers = {};
  79760. this._scene = scene;
  79761. }
  79762. BoundingBoxRenderer.prototype._prepareRessources = function () {
  79763. if (this._colorShader) {
  79764. return;
  79765. }
  79766. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  79767. attributes: [BABYLON.VertexBuffer.PositionKind],
  79768. uniforms: ["world", "viewProjection", "color"]
  79769. });
  79770. var engine = this._scene.getEngine();
  79771. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  79772. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  79773. this._createIndexBuffer();
  79774. };
  79775. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  79776. var engine = this._scene.getEngine();
  79777. this._indexBuffer = engine.createIndexBuffer([0, 1, 1, 2, 2, 3, 3, 0, 4, 5, 5, 6, 6, 7, 7, 4, 0, 7, 1, 6, 2, 5, 3, 4]);
  79778. };
  79779. BoundingBoxRenderer.prototype._rebuild = function () {
  79780. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  79781. if (vb) {
  79782. vb._rebuild();
  79783. }
  79784. this._createIndexBuffer();
  79785. };
  79786. BoundingBoxRenderer.prototype.reset = function () {
  79787. this.renderList.reset();
  79788. };
  79789. BoundingBoxRenderer.prototype.render = function () {
  79790. if (this.renderList.length === 0) {
  79791. return;
  79792. }
  79793. this._prepareRessources();
  79794. if (!this._colorShader.isReady()) {
  79795. return;
  79796. }
  79797. var engine = this._scene.getEngine();
  79798. engine.setDepthWrite(false);
  79799. this._colorShader._preBind();
  79800. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  79801. var boundingBox = this.renderList.data[boundingBoxIndex];
  79802. var min = boundingBox.minimum;
  79803. var max = boundingBox.maximum;
  79804. var diff = max.subtract(min);
  79805. var median = min.add(diff.scale(0.5));
  79806. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  79807. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  79808. .multiply(boundingBox.getWorldMatrix());
  79809. // VBOs
  79810. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  79811. if (this.showBackLines) {
  79812. // Back
  79813. engine.setDepthFunctionToGreaterOrEqual();
  79814. this._scene.resetCachedMaterial();
  79815. this._colorShader.setColor4("color", this.backColor.toColor4());
  79816. this._colorShader.bind(worldMatrix);
  79817. // Draw order
  79818. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  79819. }
  79820. // Front
  79821. engine.setDepthFunctionToLess();
  79822. this._scene.resetCachedMaterial();
  79823. this._colorShader.setColor4("color", this.frontColor.toColor4());
  79824. this._colorShader.bind(worldMatrix);
  79825. // Draw order
  79826. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  79827. }
  79828. this._colorShader.unbind();
  79829. engine.setDepthFunctionToLessOrEqual();
  79830. engine.setDepthWrite(true);
  79831. };
  79832. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  79833. this._prepareRessources();
  79834. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  79835. return;
  79836. }
  79837. var engine = this._scene.getEngine();
  79838. engine.setDepthWrite(false);
  79839. engine.setColorWrite(false);
  79840. this._colorShader._preBind();
  79841. var boundingBox = mesh._boundingInfo.boundingBox;
  79842. var min = boundingBox.minimum;
  79843. var max = boundingBox.maximum;
  79844. var diff = max.subtract(min);
  79845. var median = min.add(diff.scale(0.5));
  79846. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  79847. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  79848. .multiply(boundingBox.getWorldMatrix());
  79849. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  79850. engine.setDepthFunctionToLess();
  79851. this._scene.resetCachedMaterial();
  79852. this._colorShader.bind(worldMatrix);
  79853. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  79854. this._colorShader.unbind();
  79855. engine.setDepthFunctionToLessOrEqual();
  79856. engine.setDepthWrite(true);
  79857. engine.setColorWrite(true);
  79858. };
  79859. BoundingBoxRenderer.prototype.dispose = function () {
  79860. if (!this._colorShader) {
  79861. return;
  79862. }
  79863. this.renderList.dispose();
  79864. this._colorShader.dispose();
  79865. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  79866. if (buffer) {
  79867. buffer.dispose();
  79868. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  79869. }
  79870. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  79871. };
  79872. return BoundingBoxRenderer;
  79873. }());
  79874. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  79875. })(BABYLON || (BABYLON = {}));
  79876. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  79877. var BABYLON;
  79878. (function (BABYLON) {
  79879. var MorphTarget = /** @class */ (function () {
  79880. function MorphTarget(name, influence) {
  79881. if (influence === void 0) { influence = 0; }
  79882. this.name = name;
  79883. this.animations = new Array();
  79884. this._positions = null;
  79885. this._normals = null;
  79886. this._tangents = null;
  79887. this.onInfluenceChanged = new BABYLON.Observable();
  79888. this.influence = influence;
  79889. }
  79890. Object.defineProperty(MorphTarget.prototype, "influence", {
  79891. get: function () {
  79892. return this._influence;
  79893. },
  79894. set: function (influence) {
  79895. if (this._influence === influence) {
  79896. return;
  79897. }
  79898. var previous = this._influence;
  79899. this._influence = influence;
  79900. if (this.onInfluenceChanged.hasObservers) {
  79901. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  79902. }
  79903. },
  79904. enumerable: true,
  79905. configurable: true
  79906. });
  79907. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  79908. get: function () {
  79909. return !!this._positions;
  79910. },
  79911. enumerable: true,
  79912. configurable: true
  79913. });
  79914. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  79915. get: function () {
  79916. return !!this._normals;
  79917. },
  79918. enumerable: true,
  79919. configurable: true
  79920. });
  79921. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  79922. get: function () {
  79923. return !!this._tangents;
  79924. },
  79925. enumerable: true,
  79926. configurable: true
  79927. });
  79928. MorphTarget.prototype.setPositions = function (data) {
  79929. this._positions = data;
  79930. };
  79931. MorphTarget.prototype.getPositions = function () {
  79932. return this._positions;
  79933. };
  79934. MorphTarget.prototype.setNormals = function (data) {
  79935. this._normals = data;
  79936. };
  79937. MorphTarget.prototype.getNormals = function () {
  79938. return this._normals;
  79939. };
  79940. MorphTarget.prototype.setTangents = function (data) {
  79941. this._tangents = data;
  79942. };
  79943. MorphTarget.prototype.getTangents = function () {
  79944. return this._tangents;
  79945. };
  79946. /**
  79947. * Serializes the current target into a Serialization object.
  79948. * Returns the serialized object.
  79949. */
  79950. MorphTarget.prototype.serialize = function () {
  79951. var serializationObject = {};
  79952. serializationObject.name = this.name;
  79953. serializationObject.influence = this.influence;
  79954. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  79955. if (this.hasNormals) {
  79956. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  79957. }
  79958. if (this.hasTangents) {
  79959. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  79960. }
  79961. // Animations
  79962. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  79963. return serializationObject;
  79964. };
  79965. // Statics
  79966. MorphTarget.Parse = function (serializationObject) {
  79967. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  79968. result.setPositions(serializationObject.positions);
  79969. if (serializationObject.normals) {
  79970. result.setNormals(serializationObject.normals);
  79971. }
  79972. if (serializationObject.tangents) {
  79973. result.setTangents(serializationObject.tangents);
  79974. }
  79975. // Animations
  79976. if (serializationObject.animations) {
  79977. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  79978. var parsedAnimation = serializationObject.animations[animationIndex];
  79979. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  79980. }
  79981. }
  79982. return result;
  79983. };
  79984. MorphTarget.FromMesh = function (mesh, name, influence) {
  79985. if (!name) {
  79986. name = mesh.name;
  79987. }
  79988. var result = new MorphTarget(name, influence);
  79989. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  79990. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  79991. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  79992. }
  79993. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  79994. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  79995. }
  79996. return result;
  79997. };
  79998. return MorphTarget;
  79999. }());
  80000. BABYLON.MorphTarget = MorphTarget;
  80001. })(BABYLON || (BABYLON = {}));
  80002. //# sourceMappingURL=babylon.morphTarget.js.map
  80003. var BABYLON;
  80004. (function (BABYLON) {
  80005. var MorphTargetManager = /** @class */ (function () {
  80006. function MorphTargetManager(scene) {
  80007. if (scene === void 0) { scene = null; }
  80008. this._targets = new Array();
  80009. this._targetObservable = new Array();
  80010. this._activeTargets = new BABYLON.SmartArray(16);
  80011. this._supportsNormals = false;
  80012. this._supportsTangents = false;
  80013. this._vertexCount = 0;
  80014. this._uniqueId = 0;
  80015. this._tempInfluences = new Array();
  80016. if (!scene) {
  80017. scene = BABYLON.Engine.LastCreatedScene;
  80018. }
  80019. this._scene = scene;
  80020. if (this._scene) {
  80021. this._scene.morphTargetManagers.push(this);
  80022. this._uniqueId = this._scene.getUniqueId();
  80023. }
  80024. }
  80025. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  80026. get: function () {
  80027. return this._uniqueId;
  80028. },
  80029. enumerable: true,
  80030. configurable: true
  80031. });
  80032. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  80033. get: function () {
  80034. return this._vertexCount;
  80035. },
  80036. enumerable: true,
  80037. configurable: true
  80038. });
  80039. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  80040. get: function () {
  80041. return this._supportsNormals;
  80042. },
  80043. enumerable: true,
  80044. configurable: true
  80045. });
  80046. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  80047. get: function () {
  80048. return this._supportsTangents;
  80049. },
  80050. enumerable: true,
  80051. configurable: true
  80052. });
  80053. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  80054. get: function () {
  80055. return this._targets.length;
  80056. },
  80057. enumerable: true,
  80058. configurable: true
  80059. });
  80060. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  80061. get: function () {
  80062. return this._activeTargets.length;
  80063. },
  80064. enumerable: true,
  80065. configurable: true
  80066. });
  80067. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  80068. get: function () {
  80069. return this._influences;
  80070. },
  80071. enumerable: true,
  80072. configurable: true
  80073. });
  80074. MorphTargetManager.prototype.getActiveTarget = function (index) {
  80075. return this._activeTargets.data[index];
  80076. };
  80077. MorphTargetManager.prototype.getTarget = function (index) {
  80078. return this._targets[index];
  80079. };
  80080. MorphTargetManager.prototype.addTarget = function (target) {
  80081. var _this = this;
  80082. this._targets.push(target);
  80083. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  80084. _this._syncActiveTargets(needUpdate);
  80085. }));
  80086. this._syncActiveTargets(true);
  80087. };
  80088. MorphTargetManager.prototype.removeTarget = function (target) {
  80089. var index = this._targets.indexOf(target);
  80090. if (index >= 0) {
  80091. this._targets.splice(index, 1);
  80092. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  80093. this._syncActiveTargets(true);
  80094. }
  80095. };
  80096. /**
  80097. * Serializes the current manager into a Serialization object.
  80098. * Returns the serialized object.
  80099. */
  80100. MorphTargetManager.prototype.serialize = function () {
  80101. var serializationObject = {};
  80102. serializationObject.id = this.uniqueId;
  80103. serializationObject.targets = [];
  80104. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  80105. var target = _a[_i];
  80106. serializationObject.targets.push(target.serialize());
  80107. }
  80108. return serializationObject;
  80109. };
  80110. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  80111. var influenceCount = 0;
  80112. this._activeTargets.reset();
  80113. this._supportsNormals = true;
  80114. this._supportsTangents = true;
  80115. this._vertexCount = 0;
  80116. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  80117. var target = _a[_i];
  80118. this._activeTargets.push(target);
  80119. this._tempInfluences[influenceCount++] = target.influence;
  80120. var positions = target.getPositions();
  80121. if (positions) {
  80122. this._supportsNormals = this._supportsNormals && target.hasNormals;
  80123. this._supportsTangents = this._supportsTangents && target.hasTangents;
  80124. var vertexCount = positions.length / 3;
  80125. if (this._vertexCount === 0) {
  80126. this._vertexCount = vertexCount;
  80127. }
  80128. else if (this._vertexCount !== vertexCount) {
  80129. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  80130. return;
  80131. }
  80132. }
  80133. }
  80134. if (!this._influences || this._influences.length !== influenceCount) {
  80135. this._influences = new Float32Array(influenceCount);
  80136. }
  80137. for (var index = 0; index < influenceCount; index++) {
  80138. this._influences[index] = this._tempInfluences[index];
  80139. }
  80140. if (needUpdate && this._scene) {
  80141. // Flag meshes as dirty to resync with the active targets
  80142. for (var _b = 0, _c = this._scene.meshes; _b < _c.length; _b++) {
  80143. var mesh = _c[_b];
  80144. if (mesh.morphTargetManager === this) {
  80145. mesh._syncGeometryWithMorphTargetManager();
  80146. }
  80147. }
  80148. }
  80149. };
  80150. // Statics
  80151. MorphTargetManager.Parse = function (serializationObject, scene) {
  80152. var result = new MorphTargetManager(scene);
  80153. result._uniqueId = serializationObject.id;
  80154. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  80155. var targetData = _a[_i];
  80156. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  80157. }
  80158. return result;
  80159. };
  80160. return MorphTargetManager;
  80161. }());
  80162. BABYLON.MorphTargetManager = MorphTargetManager;
  80163. })(BABYLON || (BABYLON = {}));
  80164. //# sourceMappingURL=babylon.morphTargetManager.js.map
  80165. var BABYLON;
  80166. (function (BABYLON) {
  80167. var Octree = /** @class */ (function () {
  80168. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  80169. if (maxDepth === void 0) { maxDepth = 2; }
  80170. this.maxDepth = maxDepth;
  80171. this.dynamicContent = new Array();
  80172. this._maxBlockCapacity = maxBlockCapacity || 64;
  80173. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  80174. this._creationFunc = creationFunc;
  80175. }
  80176. // Methods
  80177. Octree.prototype.update = function (worldMin, worldMax, entries) {
  80178. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  80179. };
  80180. Octree.prototype.addMesh = function (entry) {
  80181. for (var index = 0; index < this.blocks.length; index++) {
  80182. var block = this.blocks[index];
  80183. block.addEntry(entry);
  80184. }
  80185. };
  80186. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  80187. this._selectionContent.reset();
  80188. for (var index = 0; index < this.blocks.length; index++) {
  80189. var block = this.blocks[index];
  80190. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  80191. }
  80192. if (allowDuplicate) {
  80193. this._selectionContent.concat(this.dynamicContent);
  80194. }
  80195. else {
  80196. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  80197. }
  80198. return this._selectionContent;
  80199. };
  80200. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  80201. this._selectionContent.reset();
  80202. for (var index = 0; index < this.blocks.length; index++) {
  80203. var block = this.blocks[index];
  80204. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  80205. }
  80206. if (allowDuplicate) {
  80207. this._selectionContent.concat(this.dynamicContent);
  80208. }
  80209. else {
  80210. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  80211. }
  80212. return this._selectionContent;
  80213. };
  80214. Octree.prototype.intersectsRay = function (ray) {
  80215. this._selectionContent.reset();
  80216. for (var index = 0; index < this.blocks.length; index++) {
  80217. var block = this.blocks[index];
  80218. block.intersectsRay(ray, this._selectionContent);
  80219. }
  80220. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  80221. return this._selectionContent;
  80222. };
  80223. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  80224. target.blocks = new Array();
  80225. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  80226. // Segmenting space
  80227. for (var x = 0; x < 2; x++) {
  80228. for (var y = 0; y < 2; y++) {
  80229. for (var z = 0; z < 2; z++) {
  80230. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  80231. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  80232. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  80233. block.addEntries(entries);
  80234. target.blocks.push(block);
  80235. }
  80236. }
  80237. }
  80238. };
  80239. Octree.CreationFuncForMeshes = function (entry, block) {
  80240. var boundingInfo = entry.getBoundingInfo();
  80241. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  80242. block.entries.push(entry);
  80243. }
  80244. };
  80245. Octree.CreationFuncForSubMeshes = function (entry, block) {
  80246. var boundingInfo = entry.getBoundingInfo();
  80247. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  80248. block.entries.push(entry);
  80249. }
  80250. };
  80251. return Octree;
  80252. }());
  80253. BABYLON.Octree = Octree;
  80254. })(BABYLON || (BABYLON = {}));
  80255. //# sourceMappingURL=babylon.octree.js.map
  80256. var BABYLON;
  80257. (function (BABYLON) {
  80258. var OctreeBlock = /** @class */ (function () {
  80259. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  80260. this.entries = new Array();
  80261. this._boundingVectors = new Array();
  80262. this._capacity = capacity;
  80263. this._depth = depth;
  80264. this._maxDepth = maxDepth;
  80265. this._creationFunc = creationFunc;
  80266. this._minPoint = minPoint;
  80267. this._maxPoint = maxPoint;
  80268. this._boundingVectors.push(minPoint.clone());
  80269. this._boundingVectors.push(maxPoint.clone());
  80270. this._boundingVectors.push(minPoint.clone());
  80271. this._boundingVectors[2].x = maxPoint.x;
  80272. this._boundingVectors.push(minPoint.clone());
  80273. this._boundingVectors[3].y = maxPoint.y;
  80274. this._boundingVectors.push(minPoint.clone());
  80275. this._boundingVectors[4].z = maxPoint.z;
  80276. this._boundingVectors.push(maxPoint.clone());
  80277. this._boundingVectors[5].z = minPoint.z;
  80278. this._boundingVectors.push(maxPoint.clone());
  80279. this._boundingVectors[6].x = minPoint.x;
  80280. this._boundingVectors.push(maxPoint.clone());
  80281. this._boundingVectors[7].y = minPoint.y;
  80282. }
  80283. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  80284. // Property
  80285. get: function () {
  80286. return this._capacity;
  80287. },
  80288. enumerable: true,
  80289. configurable: true
  80290. });
  80291. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  80292. get: function () {
  80293. return this._minPoint;
  80294. },
  80295. enumerable: true,
  80296. configurable: true
  80297. });
  80298. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  80299. get: function () {
  80300. return this._maxPoint;
  80301. },
  80302. enumerable: true,
  80303. configurable: true
  80304. });
  80305. // Methods
  80306. OctreeBlock.prototype.addEntry = function (entry) {
  80307. if (this.blocks) {
  80308. for (var index = 0; index < this.blocks.length; index++) {
  80309. var block = this.blocks[index];
  80310. block.addEntry(entry);
  80311. }
  80312. return;
  80313. }
  80314. this._creationFunc(entry, this);
  80315. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  80316. this.createInnerBlocks();
  80317. }
  80318. };
  80319. OctreeBlock.prototype.addEntries = function (entries) {
  80320. for (var index = 0; index < entries.length; index++) {
  80321. var mesh = entries[index];
  80322. this.addEntry(mesh);
  80323. }
  80324. };
  80325. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  80326. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  80327. if (this.blocks) {
  80328. for (var index = 0; index < this.blocks.length; index++) {
  80329. var block = this.blocks[index];
  80330. block.select(frustumPlanes, selection, allowDuplicate);
  80331. }
  80332. return;
  80333. }
  80334. if (allowDuplicate) {
  80335. selection.concat(this.entries);
  80336. }
  80337. else {
  80338. selection.concatWithNoDuplicate(this.entries);
  80339. }
  80340. }
  80341. };
  80342. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  80343. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  80344. if (this.blocks) {
  80345. for (var index = 0; index < this.blocks.length; index++) {
  80346. var block = this.blocks[index];
  80347. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  80348. }
  80349. return;
  80350. }
  80351. if (allowDuplicate) {
  80352. selection.concat(this.entries);
  80353. }
  80354. else {
  80355. selection.concatWithNoDuplicate(this.entries);
  80356. }
  80357. }
  80358. };
  80359. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  80360. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  80361. if (this.blocks) {
  80362. for (var index = 0; index < this.blocks.length; index++) {
  80363. var block = this.blocks[index];
  80364. block.intersectsRay(ray, selection);
  80365. }
  80366. return;
  80367. }
  80368. selection.concatWithNoDuplicate(this.entries);
  80369. }
  80370. };
  80371. OctreeBlock.prototype.createInnerBlocks = function () {
  80372. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  80373. };
  80374. return OctreeBlock;
  80375. }());
  80376. BABYLON.OctreeBlock = OctreeBlock;
  80377. })(BABYLON || (BABYLON = {}));
  80378. //# sourceMappingURL=babylon.octreeBlock.js.map
  80379. var BABYLON;
  80380. (function (BABYLON) {
  80381. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  80382. __extends(VRDistortionCorrectionPostProcess, _super);
  80383. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  80384. var _this = _super.call(this, name, "vrDistortionCorrection", [
  80385. 'LensCenter',
  80386. 'Scale',
  80387. 'ScaleIn',
  80388. 'HmdWarpParam'
  80389. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  80390. _this._isRightEye = isRightEye;
  80391. _this._distortionFactors = vrMetrics.distortionK;
  80392. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  80393. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  80394. _this.adaptScaleToCurrentViewport = true;
  80395. _this.onSizeChangedObservable.add(function () {
  80396. _this.aspectRatio = _this.width * .5 / _this.height;
  80397. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  80398. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  80399. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  80400. });
  80401. _this.onApplyObservable.add(function (effect) {
  80402. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  80403. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  80404. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  80405. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  80406. });
  80407. return _this;
  80408. }
  80409. return VRDistortionCorrectionPostProcess;
  80410. }(BABYLON.PostProcess));
  80411. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  80412. })(BABYLON || (BABYLON = {}));
  80413. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  80414. var BABYLON;
  80415. (function (BABYLON) {
  80416. var AnaglyphPostProcess = /** @class */ (function (_super) {
  80417. __extends(AnaglyphPostProcess, _super);
  80418. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  80419. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  80420. _this._passedProcess = rigCameras[0]._rigPostProcess;
  80421. _this.onApplyObservable.add(function (effect) {
  80422. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  80423. });
  80424. return _this;
  80425. }
  80426. return AnaglyphPostProcess;
  80427. }(BABYLON.PostProcess));
  80428. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  80429. })(BABYLON || (BABYLON = {}));
  80430. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  80431. var BABYLON;
  80432. (function (BABYLON) {
  80433. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  80434. __extends(StereoscopicInterlacePostProcess, _super);
  80435. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  80436. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  80437. _this._passedProcess = rigCameras[0]._rigPostProcess;
  80438. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  80439. _this.onSizeChangedObservable.add(function () {
  80440. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  80441. });
  80442. _this.onApplyObservable.add(function (effect) {
  80443. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  80444. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  80445. });
  80446. return _this;
  80447. }
  80448. return StereoscopicInterlacePostProcess;
  80449. }(BABYLON.PostProcess));
  80450. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  80451. })(BABYLON || (BABYLON = {}));
  80452. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  80453. var BABYLON;
  80454. (function (BABYLON) {
  80455. /**
  80456. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  80457. * Screen rotation is taken into account.
  80458. */
  80459. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  80460. function FreeCameraDeviceOrientationInput() {
  80461. var _this = this;
  80462. this._screenOrientationAngle = 0;
  80463. this._screenQuaternion = new BABYLON.Quaternion();
  80464. this._alpha = 0;
  80465. this._beta = 0;
  80466. this._gamma = 0;
  80467. this._orientationChanged = function () {
  80468. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  80469. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  80470. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  80471. };
  80472. this._deviceOrientation = function (evt) {
  80473. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  80474. _this._beta = evt.beta !== null ? evt.beta : 0;
  80475. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  80476. };
  80477. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  80478. this._orientationChanged();
  80479. }
  80480. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  80481. get: function () {
  80482. return this._camera;
  80483. },
  80484. set: function (camera) {
  80485. this._camera = camera;
  80486. if (this._camera != null && !this._camera.rotationQuaternion) {
  80487. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  80488. }
  80489. },
  80490. enumerable: true,
  80491. configurable: true
  80492. });
  80493. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  80494. window.addEventListener("orientationchange", this._orientationChanged);
  80495. window.addEventListener("deviceorientation", this._deviceOrientation);
  80496. //In certain cases, the attach control is called AFTER orientation was changed,
  80497. //So this is needed.
  80498. this._orientationChanged();
  80499. };
  80500. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  80501. window.removeEventListener("orientationchange", this._orientationChanged);
  80502. window.removeEventListener("deviceorientation", this._deviceOrientation);
  80503. };
  80504. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  80505. //if no device orientation provided, don't update the rotation.
  80506. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  80507. if (!this._alpha)
  80508. return;
  80509. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  80510. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  80511. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  80512. //Mirror on XY Plane
  80513. this._camera.rotationQuaternion.z *= -1;
  80514. this._camera.rotationQuaternion.w *= -1;
  80515. };
  80516. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  80517. return "FreeCameraDeviceOrientationInput";
  80518. };
  80519. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  80520. return "deviceOrientation";
  80521. };
  80522. return FreeCameraDeviceOrientationInput;
  80523. }());
  80524. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  80525. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  80526. })(BABYLON || (BABYLON = {}));
  80527. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  80528. var BABYLON;
  80529. (function (BABYLON) {
  80530. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  80531. function ArcRotateCameraVRDeviceOrientationInput() {
  80532. this.alphaCorrection = 1;
  80533. this.betaCorrection = 1;
  80534. this.gammaCorrection = 1;
  80535. this._alpha = 0;
  80536. this._gamma = 0;
  80537. this._dirty = false;
  80538. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  80539. }
  80540. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  80541. this.camera.attachControl(element, noPreventDefault);
  80542. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  80543. };
  80544. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  80545. if (evt.alpha !== null) {
  80546. this._alpha = +evt.alpha | 0;
  80547. }
  80548. if (evt.gamma !== null) {
  80549. this._gamma = +evt.gamma | 0;
  80550. }
  80551. this._dirty = true;
  80552. };
  80553. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  80554. if (this._dirty) {
  80555. this._dirty = false;
  80556. if (this._gamma < 0) {
  80557. this._gamma = 180 + this._gamma;
  80558. }
  80559. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  80560. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  80561. }
  80562. };
  80563. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  80564. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  80565. };
  80566. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  80567. return "ArcRotateCameraVRDeviceOrientationInput";
  80568. };
  80569. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  80570. return "VRDeviceOrientation";
  80571. };
  80572. return ArcRotateCameraVRDeviceOrientationInput;
  80573. }());
  80574. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  80575. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  80576. })(BABYLON || (BABYLON = {}));
  80577. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  80578. var BABYLON;
  80579. (function (BABYLON) {
  80580. var VRCameraMetrics = /** @class */ (function () {
  80581. function VRCameraMetrics() {
  80582. this.compensateDistortion = true;
  80583. }
  80584. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  80585. get: function () {
  80586. return this.hResolution / (2 * this.vResolution);
  80587. },
  80588. enumerable: true,
  80589. configurable: true
  80590. });
  80591. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  80592. get: function () {
  80593. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  80594. },
  80595. enumerable: true,
  80596. configurable: true
  80597. });
  80598. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  80599. get: function () {
  80600. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  80601. var h = (4 * meters) / this.hScreenSize;
  80602. return BABYLON.Matrix.Translation(h, 0, 0);
  80603. },
  80604. enumerable: true,
  80605. configurable: true
  80606. });
  80607. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  80608. get: function () {
  80609. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  80610. var h = (4 * meters) / this.hScreenSize;
  80611. return BABYLON.Matrix.Translation(-h, 0, 0);
  80612. },
  80613. enumerable: true,
  80614. configurable: true
  80615. });
  80616. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  80617. get: function () {
  80618. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  80619. },
  80620. enumerable: true,
  80621. configurable: true
  80622. });
  80623. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  80624. get: function () {
  80625. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  80626. },
  80627. enumerable: true,
  80628. configurable: true
  80629. });
  80630. VRCameraMetrics.GetDefault = function () {
  80631. var result = new VRCameraMetrics();
  80632. result.hResolution = 1280;
  80633. result.vResolution = 800;
  80634. result.hScreenSize = 0.149759993;
  80635. result.vScreenSize = 0.0935999975;
  80636. result.vScreenCenter = 0.0467999987;
  80637. result.eyeToScreenDistance = 0.0410000011;
  80638. result.lensSeparationDistance = 0.0635000020;
  80639. result.interpupillaryDistance = 0.0640000030;
  80640. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  80641. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  80642. result.postProcessScaleFactor = 1.714605507808412;
  80643. result.lensCenterOffset = 0.151976421;
  80644. return result;
  80645. };
  80646. return VRCameraMetrics;
  80647. }());
  80648. BABYLON.VRCameraMetrics = VRCameraMetrics;
  80649. })(BABYLON || (BABYLON = {}));
  80650. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  80651. var BABYLON;
  80652. (function (BABYLON) {
  80653. /**
  80654. * This represents a WebVR camera.
  80655. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  80656. * @example http://doc.babylonjs.com/how_to/webvr_camera
  80657. */
  80658. var WebVRFreeCamera = /** @class */ (function (_super) {
  80659. __extends(WebVRFreeCamera, _super);
  80660. /**
  80661. * Instantiates a WebVRFreeCamera.
  80662. * @param name The name of the WebVRFreeCamera
  80663. * @param position The starting anchor position for the camera
  80664. * @param scene The scene the camera belongs to
  80665. * @param webVROptions a set of customizable options for the webVRCamera
  80666. */
  80667. function WebVRFreeCamera(name, position, scene, webVROptions) {
  80668. if (webVROptions === void 0) { webVROptions = {}; }
  80669. var _this = _super.call(this, name, position, scene) || this;
  80670. _this.webVROptions = webVROptions;
  80671. /**
  80672. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  80673. */
  80674. _this._vrDevice = null;
  80675. /**
  80676. * The rawPose of the vrDevice.
  80677. */
  80678. _this.rawPose = null;
  80679. _this._specsVersion = "1.1";
  80680. _this._attached = false;
  80681. _this._descendants = [];
  80682. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  80683. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  80684. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  80685. _this._standingMatrix = null;
  80686. /**
  80687. * Represents device position in babylon space.
  80688. */
  80689. _this.devicePosition = BABYLON.Vector3.Zero();
  80690. /**
  80691. * Represents device rotation in babylon space.
  80692. */
  80693. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  80694. /**
  80695. * The scale of the device to be used when translating from device space to babylon space.
  80696. */
  80697. _this.deviceScaleFactor = 1;
  80698. _this._deviceToWorld = BABYLON.Matrix.Identity();
  80699. _this._worldToDevice = BABYLON.Matrix.Identity();
  80700. /**
  80701. * References to the webVR controllers for the vrDevice.
  80702. */
  80703. _this.controllers = [];
  80704. /**
  80705. * Emits an event when a controller is attached.
  80706. */
  80707. _this.onControllersAttachedObservable = new BABYLON.Observable();
  80708. /**
  80709. * Emits an event when a controller's mesh has been loaded;
  80710. */
  80711. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  80712. /**
  80713. * If the rig cameras be used as parent instead of this camera.
  80714. */
  80715. _this.rigParenting = true;
  80716. _this._defaultHeight = undefined;
  80717. _this._workingVector = BABYLON.Vector3.Zero();
  80718. _this._oneVector = BABYLON.Vector3.One();
  80719. _this._workingMatrix = BABYLON.Matrix.Identity();
  80720. _this._cache.position = BABYLON.Vector3.Zero();
  80721. if (webVROptions.defaultHeight) {
  80722. _this._defaultHeight = webVROptions.defaultHeight;
  80723. _this.position.y = _this._defaultHeight;
  80724. }
  80725. _this.minZ = 0.1;
  80726. //legacy support - the compensation boolean was removed.
  80727. if (arguments.length === 5) {
  80728. _this.webVROptions = arguments[4];
  80729. }
  80730. // default webVR options
  80731. if (_this.webVROptions.trackPosition == undefined) {
  80732. _this.webVROptions.trackPosition = true;
  80733. }
  80734. if (_this.webVROptions.controllerMeshes == undefined) {
  80735. _this.webVROptions.controllerMeshes = true;
  80736. }
  80737. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  80738. _this.webVROptions.defaultLightingOnControllers = true;
  80739. }
  80740. _this.rotationQuaternion = new BABYLON.Quaternion();
  80741. if (_this.webVROptions && _this.webVROptions.positionScale) {
  80742. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  80743. }
  80744. //enable VR
  80745. var engine = _this.getEngine();
  80746. _this._onVREnabled = function (success) { if (success) {
  80747. _this.initControllers();
  80748. } };
  80749. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  80750. engine.initWebVR().add(function (event) {
  80751. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  80752. return;
  80753. }
  80754. _this._vrDevice = event.vrDisplay;
  80755. //reset the rig parameters.
  80756. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  80757. if (_this._attached) {
  80758. _this.getEngine().enableVR();
  80759. }
  80760. });
  80761. if (typeof (VRFrameData) !== "undefined")
  80762. _this._frameData = new VRFrameData();
  80763. /**
  80764. * The idea behind the following lines:
  80765. * objects that have the camera as parent should actually have the rig cameras as a parent.
  80766. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  80767. * the second will not show it correctly.
  80768. *
  80769. * To solve this - each object that has the camera as parent will be added to a protected array.
  80770. * When the rig camera renders, it will take this array and set all of those to be its children.
  80771. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  80772. * Amazing!
  80773. */
  80774. scene.onBeforeCameraRenderObservable.add(function (camera) {
  80775. if (camera.parent === _this && _this.rigParenting) {
  80776. _this._descendants = _this.getDescendants(true, function (n) {
  80777. // don't take the cameras or the controllers!
  80778. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  80779. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  80780. return !isController && !isRigCamera;
  80781. });
  80782. _this._descendants.forEach(function (node) {
  80783. node.parent = camera;
  80784. });
  80785. }
  80786. });
  80787. scene.onAfterCameraRenderObservable.add(function (camera) {
  80788. if (camera.parent === _this && _this.rigParenting) {
  80789. _this._descendants.forEach(function (node) {
  80790. node.parent = _this;
  80791. });
  80792. }
  80793. });
  80794. return _this;
  80795. }
  80796. /**
  80797. * Gets the device distance from the ground in meters.
  80798. * @returns the distance in meters from the vrDevice to ground in device space. If standing matrix is not supported for the vrDevice 0 is returned.
  80799. */
  80800. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  80801. if (this._standingMatrix) {
  80802. // Add standing matrix offset to get real offset from ground in room
  80803. this._standingMatrix.getTranslationToRef(this._workingVector);
  80804. return this._deviceRoomPosition.y + this._workingVector.y;
  80805. }
  80806. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  80807. return this._defaultHeight || 0;
  80808. };
  80809. /**
  80810. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  80811. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  80812. */
  80813. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  80814. var _this = this;
  80815. if (callback === void 0) { callback = function (bool) { }; }
  80816. // Use standing matrix if available
  80817. this.getEngine().initWebVRAsync().then(function (result) {
  80818. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform) {
  80819. callback(false);
  80820. }
  80821. else {
  80822. _this._standingMatrix = new BABYLON.Matrix();
  80823. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  80824. if (!_this.getScene().useRightHandedSystem) {
  80825. [2, 6, 8, 9, 14].forEach(function (num) {
  80826. if (_this._standingMatrix) {
  80827. _this._standingMatrix.m[num] *= -1;
  80828. }
  80829. });
  80830. }
  80831. callback(true);
  80832. }
  80833. });
  80834. };
  80835. /**
  80836. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  80837. * @returns A promise with a boolean set to if the standing matrix is supported.
  80838. */
  80839. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  80840. var _this = this;
  80841. return new Promise(function (res, rej) {
  80842. _this.useStandingMatrix(function (supported) {
  80843. res(supported);
  80844. });
  80845. });
  80846. };
  80847. /**
  80848. * Disposes the camera
  80849. */
  80850. WebVRFreeCamera.prototype.dispose = function () {
  80851. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  80852. _super.prototype.dispose.call(this);
  80853. };
  80854. /**
  80855. * Gets a vrController by name.
  80856. * @param name The name of the controller to retreive
  80857. * @returns the controller matching the name specified or null if not found
  80858. */
  80859. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  80860. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  80861. var gp = _a[_i];
  80862. if (gp.hand === name) {
  80863. return gp;
  80864. }
  80865. }
  80866. return null;
  80867. };
  80868. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  80869. /**
  80870. * The controller corrisponding to the users left hand.
  80871. */
  80872. get: function () {
  80873. if (!this._leftController) {
  80874. this._leftController = this.getControllerByName("left");
  80875. }
  80876. return this._leftController;
  80877. },
  80878. enumerable: true,
  80879. configurable: true
  80880. });
  80881. ;
  80882. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  80883. /**
  80884. * The controller corrisponding to the users right hand.
  80885. */
  80886. get: function () {
  80887. if (!this._rightController) {
  80888. this._rightController = this.getControllerByName("right");
  80889. }
  80890. return this._rightController;
  80891. },
  80892. enumerable: true,
  80893. configurable: true
  80894. });
  80895. ;
  80896. /**
  80897. * Casts a ray forward from the vrCamera's gaze.
  80898. * @param length Length of the ray (default: 100)
  80899. * @returns the ray corrisponding to the gaze
  80900. */
  80901. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  80902. if (length === void 0) { length = 100; }
  80903. if (this.leftCamera) {
  80904. // Use left eye to avoid computation to compute center on every call
  80905. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  80906. }
  80907. else {
  80908. return _super.prototype.getForwardRay.call(this, length);
  80909. }
  80910. };
  80911. /**
  80912. * Updates the camera based on device's frame data
  80913. */
  80914. WebVRFreeCamera.prototype._checkInputs = function () {
  80915. if (this._vrDevice && this._vrDevice.isPresenting) {
  80916. this._vrDevice.getFrameData(this._frameData);
  80917. this.updateFromDevice(this._frameData.pose);
  80918. }
  80919. _super.prototype._checkInputs.call(this);
  80920. };
  80921. /**
  80922. * Updates the poseControlled values based on the input device pose.
  80923. * @param poseData Pose coming from the device
  80924. */
  80925. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  80926. if (poseData && poseData.orientation) {
  80927. this.rawPose = poseData;
  80928. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  80929. if (this.getScene().useRightHandedSystem) {
  80930. this._deviceRoomRotationQuaternion.z *= -1;
  80931. this._deviceRoomRotationQuaternion.w *= -1;
  80932. }
  80933. if (this.webVROptions.trackPosition && this.rawPose.position) {
  80934. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  80935. if (this.getScene().useRightHandedSystem) {
  80936. this._deviceRoomPosition.z *= -1;
  80937. }
  80938. }
  80939. }
  80940. };
  80941. /**
  80942. * WebVR's attach control will start broadcasting frames to the device.
  80943. * Note that in certain browsers (chrome for example) this function must be called
  80944. * within a user-interaction callback. Example:
  80945. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  80946. *
  80947. * @param element html element to attach the vrDevice to
  80948. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  80949. */
  80950. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  80951. _super.prototype.attachControl.call(this, element, noPreventDefault);
  80952. this._attached = true;
  80953. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  80954. if (this._vrDevice) {
  80955. this.getEngine().enableVR();
  80956. }
  80957. };
  80958. /**
  80959. * Detaches the camera from the html element and disables VR
  80960. *
  80961. * @param element html element to detach from
  80962. */
  80963. WebVRFreeCamera.prototype.detachControl = function (element) {
  80964. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  80965. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  80966. _super.prototype.detachControl.call(this, element);
  80967. this._attached = false;
  80968. this.getEngine().disableVR();
  80969. };
  80970. /**
  80971. * @returns the name of this class
  80972. */
  80973. WebVRFreeCamera.prototype.getClassName = function () {
  80974. return "WebVRFreeCamera";
  80975. };
  80976. /**
  80977. * Calls resetPose on the vrDisplay
  80978. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  80979. */
  80980. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  80981. //uses the vrDisplay's "resetPose()".
  80982. //pitch and roll won't be affected.
  80983. this._vrDevice.resetPose();
  80984. };
  80985. /**
  80986. * Updates the rig cameras (left and right eye)
  80987. */
  80988. WebVRFreeCamera.prototype._updateRigCameras = function () {
  80989. var camLeft = this._rigCameras[0];
  80990. var camRight = this._rigCameras[1];
  80991. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  80992. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  80993. camLeft.position.copyFrom(this._deviceRoomPosition);
  80994. camRight.position.copyFrom(this._deviceRoomPosition);
  80995. };
  80996. /**
  80997. * Updates the cached values of the camera
  80998. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  80999. */
  81000. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  81001. var _this = this;
  81002. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  81003. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  81004. if (!this.updateCacheCalled) {
  81005. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  81006. this.updateCacheCalled = true;
  81007. this.update();
  81008. }
  81009. // Set working vector to the device position in room space rotated by the new rotation
  81010. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  81011. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  81012. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  81013. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  81014. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  81015. // Add translation from anchor position
  81016. this._deviceToWorld.getTranslationToRef(this._workingVector);
  81017. this._workingVector.addInPlace(this.position);
  81018. this._workingVector.subtractInPlace(this._cache.position);
  81019. this._deviceToWorld.setTranslation(this._workingVector);
  81020. // Set an inverted matrix to be used when updating the camera
  81021. this._deviceToWorld.invertToRef(this._worldToDevice);
  81022. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  81023. this.controllers.forEach(function (controller) {
  81024. controller._deviceToWorld.copyFrom(_this._deviceToWorld);
  81025. controller.update();
  81026. });
  81027. }
  81028. if (!ignoreParentClass) {
  81029. _super.prototype._updateCache.call(this);
  81030. }
  81031. this.updateCacheCalled = false;
  81032. };
  81033. /**
  81034. * Updates the current device position and rotation in the babylon world
  81035. */
  81036. WebVRFreeCamera.prototype.update = function () {
  81037. // Get current device position in babylon world
  81038. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  81039. // Get current device rotation in babylon world
  81040. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  81041. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  81042. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  81043. _super.prototype.update.call(this);
  81044. };
  81045. /**
  81046. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  81047. * @returns an identity matrix
  81048. */
  81049. WebVRFreeCamera.prototype._getViewMatrix = function () {
  81050. return BABYLON.Matrix.Identity();
  81051. };
  81052. /**
  81053. * This function is called by the two RIG cameras.
  81054. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  81055. */
  81056. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  81057. var _this = this;
  81058. // Update the parent camera prior to using a child camera to avoid desynchronization
  81059. var parentCamera = this._cameraRigParams["parentCamera"];
  81060. parentCamera._updateCache();
  81061. //WebVR 1.1
  81062. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  81063. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  81064. if (!this.getScene().useRightHandedSystem) {
  81065. [2, 6, 8, 9, 14].forEach(function (num) {
  81066. _this._webvrViewMatrix.m[num] *= -1;
  81067. });
  81068. }
  81069. // update the camera rotation matrix
  81070. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  81071. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  81072. // Computing target and final matrix
  81073. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  81074. // should the view matrix be updated with scale and position offset?
  81075. if (parentCamera.deviceScaleFactor !== 1) {
  81076. this._webvrViewMatrix.invert();
  81077. // scale the position, if set
  81078. if (parentCamera.deviceScaleFactor) {
  81079. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  81080. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  81081. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  81082. }
  81083. this._webvrViewMatrix.invert();
  81084. }
  81085. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  81086. return this._webvrViewMatrix;
  81087. };
  81088. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  81089. var _this = this;
  81090. var parentCamera = this.parent;
  81091. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  81092. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  81093. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  81094. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  81095. //babylon compatible matrix
  81096. if (!this.getScene().useRightHandedSystem) {
  81097. [8, 9, 10, 11].forEach(function (num) {
  81098. _this._projectionMatrix.m[num] *= -1;
  81099. });
  81100. }
  81101. return this._projectionMatrix;
  81102. };
  81103. /**
  81104. * Initializes the controllers and their meshes
  81105. */
  81106. WebVRFreeCamera.prototype.initControllers = function () {
  81107. var _this = this;
  81108. this.controllers = [];
  81109. var manager = this.getScene().gamepadManager;
  81110. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  81111. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  81112. var webVrController = gamepad;
  81113. if (webVrController.defaultModel) {
  81114. webVrController.defaultModel.setEnabled(false);
  81115. }
  81116. if (webVrController.hand === "right") {
  81117. _this._rightController = null;
  81118. }
  81119. if (webVrController.hand === "left") {
  81120. _this._leftController = null;
  81121. }
  81122. var controllerIndex = _this.controllers.indexOf(webVrController);
  81123. if (controllerIndex !== -1) {
  81124. _this.controllers.splice(controllerIndex, 1);
  81125. }
  81126. }
  81127. });
  81128. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  81129. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  81130. var webVrController_1 = gamepad;
  81131. webVrController_1.deviceScaleFactor = _this.deviceScaleFactor;
  81132. webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
  81133. if (_this.webVROptions.controllerMeshes) {
  81134. if (webVrController_1.defaultModel) {
  81135. webVrController_1.defaultModel.setEnabled(true);
  81136. }
  81137. else {
  81138. // Load the meshes
  81139. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  81140. loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor);
  81141. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  81142. if (_this.webVROptions.defaultLightingOnControllers) {
  81143. if (!_this._lightOnControllers) {
  81144. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  81145. }
  81146. var activateLightOnSubMeshes_1 = function (mesh, light) {
  81147. var children = mesh.getChildren();
  81148. if (children.length !== 0) {
  81149. children.forEach(function (mesh) {
  81150. light.includedOnlyMeshes.push(mesh);
  81151. activateLightOnSubMeshes_1(mesh, light);
  81152. });
  81153. }
  81154. };
  81155. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  81156. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  81157. }
  81158. });
  81159. }
  81160. }
  81161. webVrController_1.attachToPoseControlledCamera(_this);
  81162. // since this is async - sanity check. Is the controller already stored?
  81163. if (_this.controllers.indexOf(webVrController_1) === -1) {
  81164. //add to the controllers array
  81165. _this.controllers.push(webVrController_1);
  81166. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  81167. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  81168. // So we're overriding setting left & right manually to be sure
  81169. var firstViveWandDetected = false;
  81170. for (var i = 0; i < _this.controllers.length; i++) {
  81171. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  81172. if (!firstViveWandDetected) {
  81173. firstViveWandDetected = true;
  81174. _this.controllers[i].hand = "left";
  81175. }
  81176. else {
  81177. _this.controllers[i].hand = "right";
  81178. }
  81179. }
  81180. }
  81181. //did we find enough controllers? Great! let the developer know.
  81182. if (_this.controllers.length >= 2) {
  81183. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  81184. }
  81185. }
  81186. }
  81187. });
  81188. };
  81189. return WebVRFreeCamera;
  81190. }(BABYLON.FreeCamera));
  81191. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  81192. })(BABYLON || (BABYLON = {}));
  81193. //# sourceMappingURL=babylon.webVRCamera.js.map
  81194. var BABYLON;
  81195. (function (BABYLON) {
  81196. // We're mainly based on the logic defined into the FreeCamera code
  81197. /**
  81198. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  81199. * being tilted forward or back and left or right.
  81200. */
  81201. var DeviceOrientationCamera = /** @class */ (function (_super) {
  81202. __extends(DeviceOrientationCamera, _super);
  81203. /**
  81204. * Creates a new device orientation camera. @see DeviceOrientationCamera
  81205. * @param name The name of the camera
  81206. * @param position The start position camera
  81207. * @param scene The scene the camera belongs to
  81208. */
  81209. function DeviceOrientationCamera(name, position, scene) {
  81210. var _this = _super.call(this, name, position, scene) || this;
  81211. _this._quaternionCache = new BABYLON.Quaternion();
  81212. _this.inputs.addDeviceOrientation();
  81213. return _this;
  81214. }
  81215. /**
  81216. * Gets the current instance class name ("DeviceOrientationCamera").
  81217. * This helps avoiding instanceof at run time.
  81218. * @returns the class name
  81219. */
  81220. DeviceOrientationCamera.prototype.getClassName = function () {
  81221. return "DeviceOrientationCamera";
  81222. };
  81223. /**
  81224. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  81225. */
  81226. DeviceOrientationCamera.prototype._checkInputs = function () {
  81227. _super.prototype._checkInputs.call(this);
  81228. this._quaternionCache.copyFrom(this.rotationQuaternion);
  81229. if (this._initialQuaternion) {
  81230. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  81231. }
  81232. };
  81233. /**
  81234. * Reset the camera to its default orientation on the specified axis only.
  81235. * @param axis The axis to reset
  81236. */
  81237. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  81238. var _this = this;
  81239. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  81240. //can only work if this camera has a rotation quaternion already.
  81241. if (!this.rotationQuaternion)
  81242. return;
  81243. if (!this._initialQuaternion) {
  81244. this._initialQuaternion = new BABYLON.Quaternion();
  81245. }
  81246. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  81247. ['x', 'y', 'z'].forEach(function (axisName) {
  81248. if (!axis[axisName]) {
  81249. _this._initialQuaternion[axisName] = 0;
  81250. }
  81251. else {
  81252. _this._initialQuaternion[axisName] *= -1;
  81253. }
  81254. });
  81255. this._initialQuaternion.normalize();
  81256. //force rotation update
  81257. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  81258. };
  81259. return DeviceOrientationCamera;
  81260. }(BABYLON.FreeCamera));
  81261. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  81262. })(BABYLON || (BABYLON = {}));
  81263. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  81264. var BABYLON;
  81265. (function (BABYLON) {
  81266. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  81267. __extends(VRDeviceOrientationFreeCamera, _super);
  81268. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  81269. if (compensateDistortion === void 0) { compensateDistortion = true; }
  81270. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  81271. var _this = _super.call(this, name, position, scene) || this;
  81272. vrCameraMetrics.compensateDistortion = compensateDistortion;
  81273. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  81274. return _this;
  81275. }
  81276. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  81277. return "VRDeviceOrientationFreeCamera";
  81278. };
  81279. return VRDeviceOrientationFreeCamera;
  81280. }(BABYLON.DeviceOrientationCamera));
  81281. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  81282. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  81283. __extends(VRDeviceOrientationGamepadCamera, _super);
  81284. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  81285. if (compensateDistortion === void 0) { compensateDistortion = true; }
  81286. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  81287. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  81288. _this.inputs.addGamepad();
  81289. return _this;
  81290. }
  81291. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  81292. return "VRDeviceOrientationGamepadCamera";
  81293. };
  81294. return VRDeviceOrientationGamepadCamera;
  81295. }(VRDeviceOrientationFreeCamera));
  81296. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  81297. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  81298. __extends(VRDeviceOrientationArcRotateCamera, _super);
  81299. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  81300. if (compensateDistortion === void 0) { compensateDistortion = true; }
  81301. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  81302. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  81303. vrCameraMetrics.compensateDistortion = compensateDistortion;
  81304. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  81305. _this.inputs.addVRDeviceOrientation();
  81306. return _this;
  81307. }
  81308. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  81309. return "VRDeviceOrientationArcRotateCamera";
  81310. };
  81311. return VRDeviceOrientationArcRotateCamera;
  81312. }(BABYLON.ArcRotateCamera));
  81313. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  81314. })(BABYLON || (BABYLON = {}));
  81315. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  81316. var BABYLON;
  81317. (function (BABYLON) {
  81318. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  81319. __extends(AnaglyphFreeCamera, _super);
  81320. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  81321. var _this = _super.call(this, name, position, scene) || this;
  81322. _this.interaxialDistance = interaxialDistance;
  81323. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  81324. return _this;
  81325. }
  81326. AnaglyphFreeCamera.prototype.getClassName = function () {
  81327. return "AnaglyphFreeCamera";
  81328. };
  81329. return AnaglyphFreeCamera;
  81330. }(BABYLON.FreeCamera));
  81331. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  81332. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  81333. __extends(AnaglyphArcRotateCamera, _super);
  81334. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  81335. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  81336. _this.interaxialDistance = interaxialDistance;
  81337. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  81338. return _this;
  81339. }
  81340. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  81341. return "AnaglyphArcRotateCamera";
  81342. };
  81343. return AnaglyphArcRotateCamera;
  81344. }(BABYLON.ArcRotateCamera));
  81345. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  81346. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  81347. __extends(AnaglyphGamepadCamera, _super);
  81348. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  81349. var _this = _super.call(this, name, position, scene) || this;
  81350. _this.interaxialDistance = interaxialDistance;
  81351. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  81352. return _this;
  81353. }
  81354. AnaglyphGamepadCamera.prototype.getClassName = function () {
  81355. return "AnaglyphGamepadCamera";
  81356. };
  81357. return AnaglyphGamepadCamera;
  81358. }(BABYLON.GamepadCamera));
  81359. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  81360. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  81361. __extends(AnaglyphUniversalCamera, _super);
  81362. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  81363. var _this = _super.call(this, name, position, scene) || this;
  81364. _this.interaxialDistance = interaxialDistance;
  81365. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  81366. return _this;
  81367. }
  81368. AnaglyphUniversalCamera.prototype.getClassName = function () {
  81369. return "AnaglyphUniversalCamera";
  81370. };
  81371. return AnaglyphUniversalCamera;
  81372. }(BABYLON.UniversalCamera));
  81373. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  81374. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  81375. __extends(StereoscopicFreeCamera, _super);
  81376. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  81377. var _this = _super.call(this, name, position, scene) || this;
  81378. _this.interaxialDistance = interaxialDistance;
  81379. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  81380. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  81381. return _this;
  81382. }
  81383. StereoscopicFreeCamera.prototype.getClassName = function () {
  81384. return "StereoscopicFreeCamera";
  81385. };
  81386. return StereoscopicFreeCamera;
  81387. }(BABYLON.FreeCamera));
  81388. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  81389. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  81390. __extends(StereoscopicArcRotateCamera, _super);
  81391. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  81392. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  81393. _this.interaxialDistance = interaxialDistance;
  81394. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  81395. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  81396. return _this;
  81397. }
  81398. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  81399. return "StereoscopicArcRotateCamera";
  81400. };
  81401. return StereoscopicArcRotateCamera;
  81402. }(BABYLON.ArcRotateCamera));
  81403. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  81404. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  81405. __extends(StereoscopicGamepadCamera, _super);
  81406. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  81407. var _this = _super.call(this, name, position, scene) || this;
  81408. _this.interaxialDistance = interaxialDistance;
  81409. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  81410. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  81411. return _this;
  81412. }
  81413. StereoscopicGamepadCamera.prototype.getClassName = function () {
  81414. return "StereoscopicGamepadCamera";
  81415. };
  81416. return StereoscopicGamepadCamera;
  81417. }(BABYLON.GamepadCamera));
  81418. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  81419. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  81420. __extends(StereoscopicUniversalCamera, _super);
  81421. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  81422. var _this = _super.call(this, name, position, scene) || this;
  81423. _this.interaxialDistance = interaxialDistance;
  81424. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  81425. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  81426. return _this;
  81427. }
  81428. StereoscopicUniversalCamera.prototype.getClassName = function () {
  81429. return "StereoscopicUniversalCamera";
  81430. };
  81431. return StereoscopicUniversalCamera;
  81432. }(BABYLON.UniversalCamera));
  81433. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  81434. })(BABYLON || (BABYLON = {}));
  81435. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  81436. var BABYLON;
  81437. (function (BABYLON) {
  81438. var VRExperienceHelperGazer = /** @class */ (function () {
  81439. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  81440. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  81441. this.scene = scene;
  81442. this._pointerDownOnMeshAsked = false;
  81443. this._isActionableMesh = false;
  81444. this._teleportationRequestInitiated = false;
  81445. this._teleportationBackRequestInitiated = false;
  81446. this._dpadPressed = true;
  81447. this._activePointer = false;
  81448. this._id = VRExperienceHelperGazer._idCounter++;
  81449. // Gaze tracker
  81450. if (!gazeTrackerToClone) {
  81451. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  81452. this._gazeTracker.bakeCurrentTransformIntoVertices();
  81453. this._gazeTracker.isPickable = false;
  81454. this._gazeTracker.isVisible = false;
  81455. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  81456. targetMat.specularColor = BABYLON.Color3.Black();
  81457. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  81458. targetMat.backFaceCulling = false;
  81459. this._gazeTracker.material = targetMat;
  81460. }
  81461. else {
  81462. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  81463. }
  81464. }
  81465. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  81466. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  81467. };
  81468. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  81469. this._pointerDownOnMeshAsked = true;
  81470. if (this._currentMeshSelected && this._currentHit) {
  81471. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  81472. }
  81473. };
  81474. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  81475. if (this._currentMeshSelected && this._currentHit) {
  81476. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  81477. }
  81478. this._pointerDownOnMeshAsked = false;
  81479. };
  81480. VRExperienceHelperGazer.prototype._activatePointer = function () {
  81481. this._activePointer = true;
  81482. };
  81483. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  81484. this._activePointer = false;
  81485. };
  81486. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  81487. };
  81488. VRExperienceHelperGazer.prototype.dispose = function () {
  81489. this._interactionsEnabled = false;
  81490. this._teleportationEnabled = false;
  81491. };
  81492. VRExperienceHelperGazer._idCounter = 0;
  81493. return VRExperienceHelperGazer;
  81494. }());
  81495. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  81496. __extends(VRExperienceHelperControllerGazer, _super);
  81497. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  81498. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  81499. _this.webVRController = webVRController;
  81500. // Laser pointer
  81501. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  81502. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  81503. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  81504. laserPointerMaterial.alpha = 0.6;
  81505. _this._laserPointer.material = laserPointerMaterial;
  81506. _this._laserPointer.rotation.x = Math.PI / 2;
  81507. _this._laserPointer.position.z = -0.5;
  81508. _this._laserPointer.isVisible = false;
  81509. if (!webVRController.mesh) {
  81510. // Create an empty mesh that is used prior to loading the high quality model
  81511. var preloadMesh = new BABYLON.Mesh("preloadControllerMesh", scene);
  81512. var preloadPointerPose = new BABYLON.Mesh(BABYLON.PoseEnabledController.POINTING_POSE, scene);
  81513. preloadPointerPose.rotation.x = -0.7;
  81514. preloadMesh.addChild(preloadPointerPose);
  81515. webVRController.attachToMesh(preloadMesh);
  81516. }
  81517. _this._setLaserPointerParent(webVRController.mesh);
  81518. return _this;
  81519. }
  81520. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  81521. return this.webVRController.getForwardRay(length);
  81522. };
  81523. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  81524. _super.prototype._activatePointer.call(this);
  81525. this._laserPointer.isVisible = true;
  81526. };
  81527. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  81528. _super.prototype._deactivatePointer.call(this);
  81529. this._laserPointer.isVisible = false;
  81530. };
  81531. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  81532. this._laserPointer.material.emissiveColor = color;
  81533. };
  81534. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  81535. var makeNotPick = function (root) {
  81536. root.name += " laserPointer";
  81537. root.getChildMeshes().forEach(function (c) {
  81538. makeNotPick(c);
  81539. });
  81540. };
  81541. makeNotPick(mesh);
  81542. var childMeshes = mesh.getChildMeshes();
  81543. this.webVRController._pointingPoseNode = null;
  81544. for (var i = 0; i < childMeshes.length; i++) {
  81545. if (childMeshes[i].name && childMeshes[i].name.indexOf(BABYLON.PoseEnabledController.POINTING_POSE) >= 0) {
  81546. mesh = childMeshes[i];
  81547. this.webVRController._pointingPoseNode = mesh;
  81548. break;
  81549. }
  81550. }
  81551. this._laserPointer.parent = mesh;
  81552. };
  81553. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  81554. this._laserPointer.scaling.y = distance;
  81555. this._laserPointer.position.z = -distance / 2;
  81556. };
  81557. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  81558. _super.prototype.dispose.call(this);
  81559. this._laserPointer.dispose();
  81560. };
  81561. return VRExperienceHelperControllerGazer;
  81562. }(VRExperienceHelperGazer));
  81563. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  81564. __extends(VRExperienceHelperCameraGazer, _super);
  81565. function VRExperienceHelperCameraGazer(getCamera, scene) {
  81566. var _this = _super.call(this, scene) || this;
  81567. _this.getCamera = getCamera;
  81568. return _this;
  81569. }
  81570. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  81571. var camera = this.getCamera();
  81572. if (camera) {
  81573. return camera.getForwardRay(length);
  81574. }
  81575. else {
  81576. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  81577. }
  81578. };
  81579. return VRExperienceHelperCameraGazer;
  81580. }(VRExperienceHelperGazer));
  81581. /**
  81582. * Helps to quickly add VR support to an existing scene.
  81583. * See http://doc.babylonjs.com/how_to/webvr_helper
  81584. */
  81585. var VRExperienceHelper = /** @class */ (function () {
  81586. /**
  81587. * Instantiates a VRExperienceHelper.
  81588. * Helps to quickly add VR support to an existing scene.
  81589. * @param scene The scene the VRExperienceHelper belongs to.
  81590. * @param webVROptions Options to modify the vr experience helper's behavior.
  81591. */
  81592. function VRExperienceHelper(scene, /** Options to modify the vr experience helper's behavior. */ webVROptions) {
  81593. if (webVROptions === void 0) { webVROptions = {}; }
  81594. var _this = this;
  81595. this.webVROptions = webVROptions;
  81596. // Can the system support WebVR, even if a headset isn't plugged in?
  81597. this._webVRsupported = false;
  81598. // If WebVR is supported, is a headset plugged in and are we ready to present?
  81599. this._webVRready = false;
  81600. // Are we waiting for the requestPresent callback to complete?
  81601. this._webVRrequesting = false;
  81602. // Are we presenting to the headset right now?
  81603. this._webVRpresenting = false;
  81604. // Are we presenting in the fullscreen fallback?
  81605. this._fullscreenVRpresenting = false;
  81606. /**
  81607. * Observable raised when entering VR.
  81608. */
  81609. this.onEnteringVRObservable = new BABYLON.Observable();
  81610. /**
  81611. * Observable raised when exiting VR.
  81612. */
  81613. this.onExitingVRObservable = new BABYLON.Observable();
  81614. /**
  81615. * Observable raised when controller mesh is loaded.
  81616. */
  81617. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  81618. this._useCustomVRButton = false;
  81619. this._teleportationRequested = false;
  81620. this._teleportActive = false;
  81621. this._floorMeshesCollection = [];
  81622. this._rotationAllowed = true;
  81623. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  81624. this._rotationRightAsked = false;
  81625. this._rotationLeftAsked = false;
  81626. this._isDefaultTeleportationTarget = true;
  81627. this._teleportationFillColor = "#444444";
  81628. this._teleportationBorderColor = "#FFFFFF";
  81629. this._rotationAngle = 0;
  81630. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  81631. this._padSensibilityUp = 0.65;
  81632. this._padSensibilityDown = 0.35;
  81633. this.leftController = null;
  81634. this.rightController = null;
  81635. /**
  81636. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  81637. */
  81638. this.onNewMeshSelected = new BABYLON.Observable();
  81639. /**
  81640. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  81641. */
  81642. this.onNewMeshPicked = new BABYLON.Observable();
  81643. /**
  81644. * Observable raised before camera teleportation
  81645. */
  81646. this.onBeforeCameraTeleport = new BABYLON.Observable();
  81647. /**
  81648. * Observable raised after camera teleportation
  81649. */
  81650. this.onAfterCameraTeleport = new BABYLON.Observable();
  81651. /**
  81652. * Observable raised when current selected mesh gets unselected
  81653. */
  81654. this.onSelectedMeshUnselected = new BABYLON.Observable();
  81655. /**
  81656. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  81657. */
  81658. this.teleportationEnabled = true;
  81659. this._teleportationInitialized = false;
  81660. this._interactionsEnabled = false;
  81661. this._interactionsRequested = false;
  81662. this._displayGaze = true;
  81663. this._displayLaserPointer = true;
  81664. this._onResize = function () {
  81665. _this.moveButtonToBottomRight();
  81666. if (_this._fullscreenVRpresenting && _this._webVRready) {
  81667. _this.exitVR();
  81668. }
  81669. };
  81670. this._onFullscreenChange = function () {
  81671. if (document.fullscreen !== undefined) {
  81672. _this._fullscreenVRpresenting = document.fullscreen;
  81673. }
  81674. else if (document.mozFullScreen !== undefined) {
  81675. _this._fullscreenVRpresenting = document.mozFullScreen;
  81676. }
  81677. else if (document.webkitIsFullScreen !== undefined) {
  81678. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  81679. }
  81680. else if (document.msIsFullScreen !== undefined) {
  81681. _this._fullscreenVRpresenting = document.msIsFullScreen;
  81682. }
  81683. if (!_this._fullscreenVRpresenting && _this._canvas) {
  81684. _this.exitVR();
  81685. if (!_this._useCustomVRButton) {
  81686. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  81687. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  81688. }
  81689. }
  81690. };
  81691. this.beforeRender = function () {
  81692. if (_this.leftController && _this.leftController._activePointer) {
  81693. _this._castRayAndSelectObject(_this.leftController);
  81694. }
  81695. if (_this.rightController && _this.rightController._activePointer) {
  81696. _this._castRayAndSelectObject(_this.rightController);
  81697. }
  81698. if (!(_this.leftController && _this.leftController._activePointer) && !(_this.rightController && _this.rightController._activePointer)) {
  81699. _this._castRayAndSelectObject(_this._cameraGazer);
  81700. }
  81701. else {
  81702. _this._cameraGazer._gazeTracker.isVisible = false;
  81703. }
  81704. };
  81705. this._onNewGamepadConnected = function (gamepad) {
  81706. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  81707. if (gamepad.leftStick) {
  81708. gamepad.onleftstickchanged(function (stickValues) {
  81709. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  81710. // Listening to classic/xbox gamepad only if no VR controller is active
  81711. if ((!_this.leftController && !_this.rightController) ||
  81712. ((_this.leftController && !_this.leftController._activePointer) &&
  81713. (_this.rightController && !_this.rightController._activePointer))) {
  81714. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  81715. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  81716. }
  81717. }
  81718. });
  81719. }
  81720. if (gamepad.rightStick) {
  81721. gamepad.onrightstickchanged(function (stickValues) {
  81722. if (_this._teleportationInitialized) {
  81723. _this._checkRotate(stickValues, _this._cameraGazer);
  81724. }
  81725. });
  81726. }
  81727. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  81728. gamepad.onbuttondown(function (buttonPressed) {
  81729. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  81730. _this._cameraGazer._selectionPointerDown();
  81731. }
  81732. });
  81733. gamepad.onbuttonup(function (buttonPressed) {
  81734. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  81735. _this._cameraGazer._selectionPointerUp();
  81736. }
  81737. });
  81738. }
  81739. }
  81740. else {
  81741. var webVRController = gamepad;
  81742. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  81743. if (webVRController.hand === "right" || (_this.leftController && _this.leftController.webVRController != webVRController)) {
  81744. _this.rightController = controller;
  81745. }
  81746. else {
  81747. _this.leftController = controller;
  81748. }
  81749. _this._tryEnableInteractionOnController(controller);
  81750. }
  81751. };
  81752. // This only succeeds if the controller's mesh exists for the controller so this must be called whenever new controller is connected or when mesh is loaded
  81753. this._tryEnableInteractionOnController = function (controller) {
  81754. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  81755. _this._enableInteractionOnController(controller);
  81756. }
  81757. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  81758. _this._enableTeleportationOnController(controller);
  81759. }
  81760. };
  81761. this._onNewGamepadDisconnected = function (gamepad) {
  81762. if (gamepad instanceof BABYLON.WebVRController) {
  81763. if (gamepad.hand === "left" && _this.leftController != null) {
  81764. _this.leftController.dispose();
  81765. _this.leftController = null;
  81766. }
  81767. if (gamepad.hand === "right" && _this.rightController != null) {
  81768. _this.rightController.dispose();
  81769. _this.rightController = null;
  81770. }
  81771. }
  81772. };
  81773. this._workingVector = BABYLON.Vector3.Zero();
  81774. this._workingQuaternion = BABYLON.Quaternion.Identity();
  81775. this._workingMatrix = BABYLON.Matrix.Identity();
  81776. this._scene = scene;
  81777. this._canvas = scene.getEngine().getRenderingCanvas();
  81778. // Parse options
  81779. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  81780. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  81781. }
  81782. if (webVROptions.createDeviceOrientationCamera === undefined) {
  81783. webVROptions.createDeviceOrientationCamera = true;
  81784. }
  81785. if (webVROptions.defaultHeight === undefined) {
  81786. webVROptions.defaultHeight = 1.7;
  81787. }
  81788. if (webVROptions.useCustomVRButton) {
  81789. this._useCustomVRButton = true;
  81790. if (webVROptions.customVRButton) {
  81791. this._btnVR = webVROptions.customVRButton;
  81792. }
  81793. }
  81794. if (webVROptions.rayLength) {
  81795. this._rayLength = webVROptions.rayLength;
  81796. }
  81797. this._defaultHeight = webVROptions.defaultHeight;
  81798. if (webVROptions.positionScale) {
  81799. this._rayLength *= webVROptions.positionScale;
  81800. this._defaultHeight *= webVROptions.positionScale;
  81801. }
  81802. // Set position
  81803. if (this._scene.activeCamera) {
  81804. this._position = this._scene.activeCamera.position.clone();
  81805. }
  81806. else {
  81807. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  81808. }
  81809. // Set non-vr camera
  81810. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  81811. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  81812. // Copy data from existing camera
  81813. if (this._scene.activeCamera) {
  81814. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  81815. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  81816. // Set rotation from previous camera
  81817. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  81818. var targetCamera = this._scene.activeCamera;
  81819. if (targetCamera.rotationQuaternion) {
  81820. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  81821. }
  81822. else {
  81823. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  81824. }
  81825. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  81826. }
  81827. }
  81828. this._scene.activeCamera = this._deviceOrientationCamera;
  81829. if (this._canvas) {
  81830. this._scene.activeCamera.attachControl(this._canvas);
  81831. }
  81832. }
  81833. else {
  81834. this._existingCamera = this._scene.activeCamera;
  81835. }
  81836. // Create VR cameras
  81837. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  81838. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  81839. }
  81840. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  81841. this._webVRCamera.useStandingMatrix();
  81842. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  81843. // Create default button
  81844. if (!this._useCustomVRButton) {
  81845. this._btnVR = document.createElement("BUTTON");
  81846. this._btnVR.className = "babylonVRicon";
  81847. this._btnVR.id = "babylonVRiconbtn";
  81848. this._btnVR.title = "Click to switch to VR";
  81849. var css = ".babylonVRicon { position: absolute; right: 20px; height: 50px; width: 80px; background-color: rgba(51,51,51,0.7); background-image: url(data:image/svg+xml;charset=UTF-8,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20width%3D%222048%22%20height%3D%221152%22%20viewBox%3D%220%200%202048%201152%22%20version%3D%221.1%22%3E%3Cpath%20transform%3D%22rotate%28180%201024%2C576.0000000000001%29%22%20d%3D%22m1109%2C896q17%2C0%2030%2C-12t13%2C-30t-12.5%2C-30.5t-30.5%2C-12.5l-170%2C0q-18%2C0%20-30.5%2C12.5t-12.5%2C30.5t13%2C30t30%2C12l170%2C0zm-85%2C256q59%2C0%20132.5%2C-1.5t154.5%2C-5.5t164.5%2C-11.5t163%2C-20t150%2C-30t124.5%2C-41.5q23%2C-11%2042%2C-24t38%2C-30q27%2C-25%2041%2C-61.5t14%2C-72.5l0%2C-257q0%2C-123%20-47%2C-232t-128%2C-190t-190%2C-128t-232%2C-47l-81%2C0q-37%2C0%20-68.5%2C14t-60.5%2C34.5t-55.5%2C45t-53%2C45t-53%2C34.5t-55.5%2C14t-55.5%2C-14t-53%2C-34.5t-53%2C-45t-55.5%2C-45t-60.5%2C-34.5t-68.5%2C-14l-81%2C0q-123%2C0%20-232%2C47t-190%2C128t-128%2C190t-47%2C232l0%2C257q0%2C68%2038%2C115t97%2C73q54%2C24%20124.5%2C41.5t150%2C30t163%2C20t164.5%2C11.5t154.5%2C5.5t132.5%2C1.5zm939%2C-298q0%2C39%20-24.5%2C67t-58.5%2C42q-54%2C23%20-122%2C39.5t-143.5%2C28t-155.5%2C19t-157%2C11t-148.5%2C5t-129.5%2C1.5q-59%2C0%20-130%2C-1.5t-148%2C-5t-157%2C-11t-155.5%2C-19t-143.5%2C-28t-122%2C-39.5q-34%2C-14%20-58.5%2C-42t-24.5%2C-67l0%2C-257q0%2C-106%2040.5%2C-199t110%2C-162.5t162.5%2C-109.5t199%2C-40l81%2C0q27%2C0%2052%2C14t50%2C34.5t51%2C44.5t55.5%2C44.5t63.5%2C34.5t74%2C14t74%2C-14t63.5%2C-34.5t55.5%2C-44.5t51%2C-44.5t50%2C-34.5t52%2C-14l14%2C0q37%2C0%2070%2C0.5t64.5%2C4.5t63.5%2C12t68%2C23q71%2C30%20128.5%2C78.5t98.5%2C110t63.5%2C133.5t22.5%2C149l0%2C257z%22%20fill%3D%22white%22%20/%3E%3C/svg%3E%0A); background-size: 80%; background-repeat:no-repeat; background-position: center; border: none; outline: none; transition: transform 0.125s ease-out } .babylonVRicon:hover { transform: scale(1.05) } .babylonVRicon:active {background-color: rgba(51,51,51,1) } .babylonVRicon:focus {background-color: rgba(51,51,51,1) }";
  81850. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  81851. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  81852. // css += ".babylonVRicon.vrdisplaysupported { }";
  81853. // css += ".babylonVRicon.vrdisplayready { }";
  81854. // css += ".babylonVRicon.vrdisplayrequesting { }";
  81855. var style = document.createElement('style');
  81856. style.appendChild(document.createTextNode(css));
  81857. document.getElementsByTagName('head')[0].appendChild(style);
  81858. this.moveButtonToBottomRight();
  81859. }
  81860. // VR button click event
  81861. if (this._btnVR) {
  81862. this._btnVR.addEventListener("click", function () {
  81863. if (!_this.isInVRMode) {
  81864. _this.enterVR();
  81865. }
  81866. else {
  81867. _this.exitVR();
  81868. }
  81869. });
  81870. }
  81871. // Window events
  81872. window.addEventListener("resize", this._onResize);
  81873. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  81874. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  81875. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  81876. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  81877. // Display vr button when headset is connected
  81878. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  81879. this.displayVRButton();
  81880. }
  81881. else {
  81882. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  81883. if (e.vrDisplay) {
  81884. _this.displayVRButton();
  81885. }
  81886. });
  81887. }
  81888. // Exiting VR mode using 'ESC' key on desktop
  81889. this._onKeyDown = function (event) {
  81890. if (event.keyCode === 27 && _this.isInVRMode) {
  81891. _this.exitVR();
  81892. }
  81893. };
  81894. document.addEventListener("keydown", this._onKeyDown);
  81895. // Exiting VR mode double tapping the touch screen
  81896. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  81897. if (_this.isInVRMode) {
  81898. _this.exitVR();
  81899. if (_this._fullscreenVRpresenting) {
  81900. _this._scene.getEngine().switchFullscreen(true);
  81901. }
  81902. }
  81903. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  81904. // Listen for WebVR display changes
  81905. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  81906. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  81907. this._onVRRequestPresentStart = function () {
  81908. _this._webVRrequesting = true;
  81909. _this.updateButtonVisibility();
  81910. };
  81911. this._onVRRequestPresentComplete = function (success) {
  81912. _this._webVRrequesting = false;
  81913. _this.updateButtonVisibility();
  81914. };
  81915. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  81916. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  81917. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  81918. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  81919. scene.onDisposeObservable.add(function () {
  81920. _this.dispose();
  81921. });
  81922. // Gamepad connection events
  81923. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  81924. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  81925. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  81926. this.updateButtonVisibility();
  81927. //create easing functions
  81928. this._circleEase = new BABYLON.CircleEase();
  81929. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  81930. }
  81931. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  81932. /** Return this.onEnteringVRObservable
  81933. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  81934. */
  81935. get: function () {
  81936. return this.onEnteringVRObservable;
  81937. },
  81938. enumerable: true,
  81939. configurable: true
  81940. });
  81941. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  81942. /** Return this.onExitingVRObservable
  81943. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  81944. */
  81945. get: function () {
  81946. return this.onExitingVRObservable;
  81947. },
  81948. enumerable: true,
  81949. configurable: true
  81950. });
  81951. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  81952. /** Return this.onControllerMeshLoadedObservable
  81953. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  81954. */
  81955. get: function () {
  81956. return this.onControllerMeshLoadedObservable;
  81957. },
  81958. enumerable: true,
  81959. configurable: true
  81960. });
  81961. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  81962. /**
  81963. * The mesh used to display where the user is going to teleport.
  81964. */
  81965. get: function () {
  81966. return this._teleportationTarget;
  81967. },
  81968. /**
  81969. * Sets the mesh to be used to display where the user is going to teleport.
  81970. */
  81971. set: function (value) {
  81972. if (value) {
  81973. value.name = "teleportationTarget";
  81974. this._isDefaultTeleportationTarget = false;
  81975. this._teleportationTarget = value;
  81976. }
  81977. },
  81978. enumerable: true,
  81979. configurable: true
  81980. });
  81981. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  81982. /**
  81983. * The mesh used to display where the user is selecting,
  81984. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  81985. * See http://doc.babylonjs.com/resources/baking_transformations
  81986. */
  81987. get: function () {
  81988. return this._cameraGazer._gazeTracker;
  81989. },
  81990. set: function (value) {
  81991. if (value) {
  81992. this._cameraGazer._gazeTracker = value;
  81993. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  81994. this._cameraGazer._gazeTracker.isPickable = false;
  81995. this._cameraGazer._gazeTracker.isVisible = false;
  81996. this._cameraGazer._gazeTracker.name = "gazeTracker";
  81997. if (this.leftController) {
  81998. this.leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  81999. }
  82000. if (this.rightController) {
  82001. this.rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  82002. }
  82003. }
  82004. },
  82005. enumerable: true,
  82006. configurable: true
  82007. });
  82008. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  82009. /**
  82010. * If the ray of the gaze should be displayed.
  82011. */
  82012. get: function () {
  82013. return this._displayGaze;
  82014. },
  82015. /**
  82016. * Sets if the ray of the gaze should be displayed.
  82017. */
  82018. set: function (value) {
  82019. this._displayGaze = value;
  82020. if (!value) {
  82021. this._cameraGazer._gazeTracker.isVisible = false;
  82022. if (this.leftController) {
  82023. this.leftController._gazeTracker.isVisible = false;
  82024. }
  82025. if (this.rightController) {
  82026. this.rightController._gazeTracker.isVisible = false;
  82027. }
  82028. }
  82029. },
  82030. enumerable: true,
  82031. configurable: true
  82032. });
  82033. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  82034. /**
  82035. * If the ray of the LaserPointer should be displayed.
  82036. */
  82037. get: function () {
  82038. return this._displayLaserPointer;
  82039. },
  82040. /**
  82041. * Sets if the ray of the LaserPointer should be displayed.
  82042. */
  82043. set: function (value) {
  82044. this._displayLaserPointer = value;
  82045. if (!value) {
  82046. if (this.rightController) {
  82047. this.rightController._deactivatePointer();
  82048. this.rightController._gazeTracker.isVisible = false;
  82049. }
  82050. if (this.leftController) {
  82051. this.leftController._deactivatePointer();
  82052. this.leftController._gazeTracker.isVisible = false;
  82053. }
  82054. }
  82055. else {
  82056. if (this.rightController) {
  82057. this.rightController._activatePointer();
  82058. }
  82059. else if (this.leftController) {
  82060. this.leftController._activatePointer();
  82061. }
  82062. }
  82063. },
  82064. enumerable: true,
  82065. configurable: true
  82066. });
  82067. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  82068. /**
  82069. * The deviceOrientationCamera used as the camera when not in VR.
  82070. */
  82071. get: function () {
  82072. return this._deviceOrientationCamera;
  82073. },
  82074. enumerable: true,
  82075. configurable: true
  82076. });
  82077. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  82078. /**
  82079. * Based on the current WebVR support, returns the current VR camera used.
  82080. */
  82081. get: function () {
  82082. if (this._webVRready) {
  82083. return this._webVRCamera;
  82084. }
  82085. else {
  82086. return this._scene.activeCamera;
  82087. }
  82088. },
  82089. enumerable: true,
  82090. configurable: true
  82091. });
  82092. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  82093. /**
  82094. * The webVRCamera which is used when in VR.
  82095. */
  82096. get: function () {
  82097. return this._webVRCamera;
  82098. },
  82099. enumerable: true,
  82100. configurable: true
  82101. });
  82102. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  82103. /**
  82104. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  82105. */
  82106. get: function () {
  82107. return this._vrDeviceOrientationCamera;
  82108. },
  82109. enumerable: true,
  82110. configurable: true
  82111. });
  82112. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  82113. get: function () {
  82114. var result = this._cameraGazer._teleportationRequestInitiated
  82115. || (this.leftController !== null && this.leftController._teleportationRequestInitiated)
  82116. || (this.rightController !== null && this.rightController._teleportationRequestInitiated);
  82117. return result;
  82118. },
  82119. enumerable: true,
  82120. configurable: true
  82121. });
  82122. // Raised when one of the controller has loaded successfully its associated default mesh
  82123. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  82124. if (this.leftController && this.leftController.webVRController == webVRController) {
  82125. if (webVRController.mesh) {
  82126. this.leftController._setLaserPointerParent(webVRController.mesh);
  82127. }
  82128. }
  82129. if (this.rightController && this.rightController.webVRController == webVRController) {
  82130. if (webVRController.mesh) {
  82131. this.rightController._setLaserPointerParent(webVRController.mesh);
  82132. }
  82133. }
  82134. try {
  82135. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  82136. }
  82137. catch (err) {
  82138. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  82139. }
  82140. };
  82141. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  82142. /**
  82143. * Gets a value indicating if we are currently in VR mode.
  82144. */
  82145. get: function () {
  82146. return this._webVRpresenting || this._fullscreenVRpresenting;
  82147. },
  82148. enumerable: true,
  82149. configurable: true
  82150. });
  82151. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  82152. var vrDisplay = this._scene.getEngine().getVRDevice();
  82153. if (vrDisplay) {
  82154. var wasPresenting = this._webVRpresenting;
  82155. // A VR display is connected
  82156. this._webVRpresenting = vrDisplay.isPresenting;
  82157. if (wasPresenting && !this._webVRpresenting)
  82158. this.exitVR();
  82159. }
  82160. else {
  82161. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  82162. }
  82163. this.updateButtonVisibility();
  82164. };
  82165. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  82166. this._webVRsupported = eventArgs.vrSupported;
  82167. this._webVRready = !!eventArgs.vrDisplay;
  82168. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  82169. this.updateButtonVisibility();
  82170. };
  82171. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  82172. if (this._canvas && !this._useCustomVRButton) {
  82173. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  82174. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  82175. }
  82176. };
  82177. VRExperienceHelper.prototype.displayVRButton = function () {
  82178. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  82179. document.body.appendChild(this._btnVR);
  82180. this._btnVRDisplayed = true;
  82181. }
  82182. };
  82183. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  82184. if (!this._btnVR || this._useCustomVRButton) {
  82185. return;
  82186. }
  82187. this._btnVR.className = "babylonVRicon";
  82188. if (this.isInVRMode) {
  82189. this._btnVR.className += " vrdisplaypresenting";
  82190. }
  82191. else {
  82192. if (this._webVRready)
  82193. this._btnVR.className += " vrdisplayready";
  82194. if (this._webVRsupported)
  82195. this._btnVR.className += " vrdisplaysupported";
  82196. if (this._webVRrequesting)
  82197. this._btnVR.className += " vrdisplayrequesting";
  82198. }
  82199. };
  82200. /**
  82201. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  82202. * Otherwise, will use the fullscreen API.
  82203. */
  82204. VRExperienceHelper.prototype.enterVR = function () {
  82205. if (this.onEnteringVRObservable) {
  82206. try {
  82207. this.onEnteringVRObservable.notifyObservers(this);
  82208. }
  82209. catch (err) {
  82210. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  82211. }
  82212. }
  82213. if (this._scene.activeCamera) {
  82214. this._position = this._scene.activeCamera.position.clone();
  82215. // make sure that we return to the last active camera
  82216. this._existingCamera = this._scene.activeCamera;
  82217. }
  82218. if (this._webVRrequesting)
  82219. return;
  82220. // If WebVR is supported and a headset is connected
  82221. if (this._webVRready) {
  82222. if (!this._webVRpresenting) {
  82223. this._webVRCamera.position = this._position;
  82224. this._scene.activeCamera = this._webVRCamera;
  82225. }
  82226. }
  82227. else if (this._vrDeviceOrientationCamera) {
  82228. this._vrDeviceOrientationCamera.position = this._position;
  82229. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  82230. this._scene.getEngine().switchFullscreen(true);
  82231. this.updateButtonVisibility();
  82232. }
  82233. if (this._scene.activeCamera && this._canvas) {
  82234. this._scene.activeCamera.attachControl(this._canvas);
  82235. }
  82236. if (this._interactionsEnabled) {
  82237. this._scene.registerBeforeRender(this.beforeRender);
  82238. }
  82239. };
  82240. /**
  82241. * Attempt to exit VR, or fullscreen.
  82242. */
  82243. VRExperienceHelper.prototype.exitVR = function () {
  82244. if (this.onExitingVRObservable) {
  82245. try {
  82246. this.onExitingVRObservable.notifyObservers(this);
  82247. }
  82248. catch (err) {
  82249. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  82250. }
  82251. }
  82252. if (this._webVRpresenting) {
  82253. this._scene.getEngine().disableVR();
  82254. }
  82255. if (this._scene.activeCamera) {
  82256. this._position = this._scene.activeCamera.position.clone();
  82257. }
  82258. if (this._deviceOrientationCamera) {
  82259. this._deviceOrientationCamera.position = this._position;
  82260. this._scene.activeCamera = this._deviceOrientationCamera;
  82261. if (this._canvas) {
  82262. this._scene.activeCamera.attachControl(this._canvas);
  82263. }
  82264. }
  82265. else if (this._existingCamera) {
  82266. this._existingCamera.position = this._position;
  82267. this._scene.activeCamera = this._existingCamera;
  82268. }
  82269. this.updateButtonVisibility();
  82270. if (this._interactionsEnabled) {
  82271. this._scene.unregisterBeforeRender(this.beforeRender);
  82272. }
  82273. };
  82274. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  82275. /**
  82276. * The position of the vr experience helper.
  82277. */
  82278. get: function () {
  82279. return this._position;
  82280. },
  82281. /**
  82282. * Sets the position of the vr experience helper.
  82283. */
  82284. set: function (value) {
  82285. this._position = value;
  82286. if (this._scene.activeCamera) {
  82287. this._scene.activeCamera.position = value;
  82288. }
  82289. },
  82290. enumerable: true,
  82291. configurable: true
  82292. });
  82293. /**
  82294. * Enables controllers and user interactions suck as selecting and object or clicking on an object.
  82295. */
  82296. VRExperienceHelper.prototype.enableInteractions = function () {
  82297. var _this = this;
  82298. if (!this._interactionsEnabled) {
  82299. this._interactionsRequested = true;
  82300. if (this.leftController) {
  82301. this._enableInteractionOnController(this.leftController);
  82302. }
  82303. if (this.rightController) {
  82304. this._enableInteractionOnController(this.rightController);
  82305. }
  82306. this.raySelectionPredicate = function (mesh) {
  82307. return mesh.isVisible;
  82308. };
  82309. this.meshSelectionPredicate = function (mesh) {
  82310. return true;
  82311. };
  82312. this._raySelectionPredicate = function (mesh) {
  82313. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  82314. && mesh.name.indexOf("teleportationTarget") === -1
  82315. && mesh.name.indexOf("torusTeleportation") === -1
  82316. && mesh.name.indexOf("laserPointer") === -1)) {
  82317. return _this.raySelectionPredicate(mesh);
  82318. }
  82319. return false;
  82320. };
  82321. this._interactionsEnabled = true;
  82322. }
  82323. };
  82324. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  82325. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  82326. if (this._floorMeshesCollection[i].id === mesh.id) {
  82327. return true;
  82328. }
  82329. }
  82330. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  82331. return true;
  82332. }
  82333. return false;
  82334. };
  82335. /**
  82336. * Adds a floor mesh to be used for teleportation.
  82337. * @param floorMesh the mesh to be used for teleportation.
  82338. */
  82339. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  82340. if (!this._floorMeshesCollection) {
  82341. return;
  82342. }
  82343. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  82344. return;
  82345. }
  82346. this._floorMeshesCollection.push(floorMesh);
  82347. };
  82348. /**
  82349. * Removes a floor mesh from being used for teleportation.
  82350. * @param floorMesh the mesh to be removed.
  82351. */
  82352. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  82353. if (!this._floorMeshesCollection) {
  82354. return;
  82355. }
  82356. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  82357. if (meshIndex !== -1) {
  82358. this._floorMeshesCollection.splice(meshIndex, 1);
  82359. }
  82360. };
  82361. /**
  82362. * Enables interactions and teleportation using the VR controllers and gaze.
  82363. * @param vrTeleportationOptions options to modify teleportation behavior.
  82364. */
  82365. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  82366. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  82367. if (!this._teleportationInitialized) {
  82368. this._teleportationRequested = true;
  82369. this.enableInteractions();
  82370. if (vrTeleportationOptions.floorMeshName) {
  82371. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  82372. }
  82373. if (vrTeleportationOptions.floorMeshes) {
  82374. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  82375. }
  82376. if (this.leftController != null) {
  82377. this._enableTeleportationOnController(this.leftController);
  82378. }
  82379. if (this.rightController != null) {
  82380. this._enableTeleportationOnController(this.rightController);
  82381. }
  82382. // Creates an image processing post process for the vignette not relying
  82383. // on the main scene configuration for image processing to reduce setup and spaces
  82384. // (gamma/linear) conflicts.
  82385. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  82386. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  82387. imageProcessingConfiguration.vignetteEnabled = true;
  82388. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  82389. this._webVRCamera.detachPostProcess(this._postProcessMove);
  82390. this._teleportationInitialized = true;
  82391. if (this._isDefaultTeleportationTarget) {
  82392. this._createTeleportationCircles();
  82393. this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);
  82394. }
  82395. }
  82396. };
  82397. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  82398. var _this = this;
  82399. var controllerMesh = controller.webVRController.mesh;
  82400. if (controllerMesh) {
  82401. controller._interactionsEnabled = true;
  82402. controller._activatePointer();
  82403. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  82404. // Enabling / disabling laserPointer
  82405. if (_this._displayLaserPointer && stateObject.value === 1) {
  82406. if (controller._activePointer) {
  82407. controller._deactivatePointer();
  82408. }
  82409. else {
  82410. controller._activatePointer();
  82411. }
  82412. if (_this.displayGaze) {
  82413. controller._gazeTracker.isVisible = controller._activePointer;
  82414. }
  82415. }
  82416. });
  82417. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  82418. if (!controller._pointerDownOnMeshAsked) {
  82419. if (stateObject.value > _this._padSensibilityUp) {
  82420. controller._selectionPointerDown();
  82421. }
  82422. }
  82423. else if (stateObject.value < _this._padSensibilityDown) {
  82424. controller._selectionPointerUp();
  82425. }
  82426. });
  82427. }
  82428. };
  82429. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  82430. // Dont teleport if another gaze already requested teleportation
  82431. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  82432. return;
  82433. }
  82434. if (!gazer._teleportationRequestInitiated) {
  82435. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  82436. gazer._activatePointer();
  82437. gazer._teleportationRequestInitiated = true;
  82438. }
  82439. }
  82440. else {
  82441. // Listening to the proper controller values changes to confirm teleportation
  82442. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  82443. if (this._teleportActive) {
  82444. this._teleportCamera(this._haloCenter);
  82445. }
  82446. gazer._teleportationRequestInitiated = false;
  82447. }
  82448. }
  82449. };
  82450. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  82451. // Only rotate when user is not currently selecting a teleportation location
  82452. if (gazer._teleportationRequestInitiated) {
  82453. return;
  82454. }
  82455. if (!this._rotationLeftAsked) {
  82456. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  82457. this._rotationLeftAsked = true;
  82458. if (this._rotationAllowed) {
  82459. this._rotateCamera(false);
  82460. }
  82461. }
  82462. }
  82463. else {
  82464. if (stateObject.x > -this._padSensibilityDown) {
  82465. this._rotationLeftAsked = false;
  82466. }
  82467. }
  82468. if (!this._rotationRightAsked) {
  82469. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  82470. this._rotationRightAsked = true;
  82471. if (this._rotationAllowed) {
  82472. this._rotateCamera(true);
  82473. }
  82474. }
  82475. }
  82476. else {
  82477. if (stateObject.x < this._padSensibilityDown) {
  82478. this._rotationRightAsked = false;
  82479. }
  82480. }
  82481. };
  82482. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  82483. // Only teleport backwards when user is not currently selecting a teleportation location
  82484. if (gazer._teleportationRequestInitiated) {
  82485. return;
  82486. }
  82487. // Teleport backwards
  82488. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  82489. if (!gazer._teleportationBackRequestInitiated) {
  82490. if (!this.currentVRCamera) {
  82491. return;
  82492. }
  82493. // Get rotation and position of the current camera
  82494. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  82495. var position = this.currentVRCamera.position;
  82496. // If the camera has device position, use that instead
  82497. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  82498. rotation = this.currentVRCamera.deviceRotationQuaternion;
  82499. position = this.currentVRCamera.devicePosition;
  82500. }
  82501. // Get matrix with only the y rotation of the device rotation
  82502. rotation.toEulerAnglesToRef(this._workingVector);
  82503. this._workingVector.z = 0;
  82504. this._workingVector.x = 0;
  82505. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  82506. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  82507. // Rotate backwards ray by device rotation to cast at the ground behind the user
  82508. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  82509. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  82510. var ray = new BABYLON.Ray(position, this._workingVector);
  82511. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  82512. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  82513. this._teleportCamera(hit.pickedPoint);
  82514. }
  82515. gazer._teleportationBackRequestInitiated = true;
  82516. }
  82517. }
  82518. else {
  82519. gazer._teleportationBackRequestInitiated = false;
  82520. }
  82521. };
  82522. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  82523. var _this = this;
  82524. var controllerMesh = controller.webVRController.mesh;
  82525. if (controllerMesh) {
  82526. if (!controller._interactionsEnabled) {
  82527. this._enableInteractionOnController(controller);
  82528. }
  82529. controller._interactionsEnabled = true;
  82530. controller._teleportationEnabled = true;
  82531. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  82532. controller._dpadPressed = false;
  82533. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  82534. controller._dpadPressed = stateObject.pressed;
  82535. if (!controller._dpadPressed) {
  82536. _this._rotationLeftAsked = false;
  82537. _this._rotationRightAsked = false;
  82538. controller._teleportationBackRequestInitiated = false;
  82539. }
  82540. });
  82541. }
  82542. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  82543. if (_this.teleportationEnabled) {
  82544. _this._checkTeleportBackwards(stateObject, controller);
  82545. _this._checkTeleportWithRay(stateObject, controller);
  82546. }
  82547. _this._checkRotate(stateObject, controller);
  82548. });
  82549. }
  82550. };
  82551. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  82552. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  82553. this._teleportationTarget.isPickable = false;
  82554. var length = 512;
  82555. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  82556. dynamicTexture.hasAlpha = true;
  82557. var context = dynamicTexture.getContext();
  82558. var centerX = length / 2;
  82559. var centerY = length / 2;
  82560. var radius = 200;
  82561. context.beginPath();
  82562. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  82563. context.fillStyle = this._teleportationFillColor;
  82564. context.fill();
  82565. context.lineWidth = 10;
  82566. context.strokeStyle = this._teleportationBorderColor;
  82567. context.stroke();
  82568. context.closePath();
  82569. dynamicTexture.update();
  82570. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  82571. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  82572. this._teleportationTarget.material = teleportationCircleMaterial;
  82573. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  82574. torus.isPickable = false;
  82575. torus.parent = this._teleportationTarget;
  82576. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  82577. var keys = [];
  82578. keys.push({
  82579. frame: 0,
  82580. value: 0
  82581. });
  82582. keys.push({
  82583. frame: 30,
  82584. value: 0.4
  82585. });
  82586. keys.push({
  82587. frame: 60,
  82588. value: 0
  82589. });
  82590. animationInnerCircle.setKeys(keys);
  82591. var easingFunction = new BABYLON.SineEase();
  82592. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  82593. animationInnerCircle.setEasingFunction(easingFunction);
  82594. torus.animations = [];
  82595. torus.animations.push(animationInnerCircle);
  82596. this._scene.beginAnimation(torus, 0, 60, true);
  82597. this._hideTeleportationTarget();
  82598. };
  82599. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  82600. this._teleportActive = true;
  82601. if (this._teleportationInitialized) {
  82602. this._teleportationTarget.isVisible = true;
  82603. if (this._isDefaultTeleportationTarget) {
  82604. this._teleportationTarget.getChildren()[0].isVisible = true;
  82605. }
  82606. }
  82607. };
  82608. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  82609. this._teleportActive = false;
  82610. if (this._teleportationInitialized) {
  82611. this._teleportationTarget.isVisible = false;
  82612. if (this._isDefaultTeleportationTarget) {
  82613. this._teleportationTarget.getChildren()[0].isVisible = false;
  82614. }
  82615. }
  82616. };
  82617. VRExperienceHelper.prototype._rotateCamera = function (right) {
  82618. var _this = this;
  82619. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  82620. return;
  82621. }
  82622. if (right) {
  82623. this._rotationAngle++;
  82624. }
  82625. else {
  82626. this._rotationAngle--;
  82627. }
  82628. this.currentVRCamera.animations = [];
  82629. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  82630. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  82631. var animationRotationKeys = [];
  82632. animationRotationKeys.push({
  82633. frame: 0,
  82634. value: this.currentVRCamera.rotationQuaternion
  82635. });
  82636. animationRotationKeys.push({
  82637. frame: 6,
  82638. value: target
  82639. });
  82640. animationRotation.setKeys(animationRotationKeys);
  82641. animationRotation.setEasingFunction(this._circleEase);
  82642. this.currentVRCamera.animations.push(animationRotation);
  82643. this._postProcessMove.animations = [];
  82644. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  82645. var vignetteWeightKeys = [];
  82646. vignetteWeightKeys.push({
  82647. frame: 0,
  82648. value: 0
  82649. });
  82650. vignetteWeightKeys.push({
  82651. frame: 3,
  82652. value: 4
  82653. });
  82654. vignetteWeightKeys.push({
  82655. frame: 6,
  82656. value: 0
  82657. });
  82658. animationPP.setKeys(vignetteWeightKeys);
  82659. animationPP.setEasingFunction(this._circleEase);
  82660. this._postProcessMove.animations.push(animationPP);
  82661. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  82662. var vignetteStretchKeys = [];
  82663. vignetteStretchKeys.push({
  82664. frame: 0,
  82665. value: 0
  82666. });
  82667. vignetteStretchKeys.push({
  82668. frame: 3,
  82669. value: 10
  82670. });
  82671. vignetteStretchKeys.push({
  82672. frame: 6,
  82673. value: 0
  82674. });
  82675. animationPP2.setKeys(vignetteStretchKeys);
  82676. animationPP2.setEasingFunction(this._circleEase);
  82677. this._postProcessMove.animations.push(animationPP2);
  82678. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  82679. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  82680. this._postProcessMove.samples = 4;
  82681. this._webVRCamera.attachPostProcess(this._postProcessMove);
  82682. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  82683. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  82684. });
  82685. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  82686. };
  82687. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer) {
  82688. if (hit.pickedPoint) {
  82689. if (gazer._teleportationRequestInitiated) {
  82690. this._displayTeleportationTarget();
  82691. this._haloCenter.copyFrom(hit.pickedPoint);
  82692. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  82693. }
  82694. var pickNormal = hit.getNormal(true, false);
  82695. if (pickNormal) {
  82696. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  82697. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  82698. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  82699. }
  82700. this._teleportationTarget.position.y += 0.1;
  82701. }
  82702. };
  82703. VRExperienceHelper.prototype._teleportCamera = function (location) {
  82704. var _this = this;
  82705. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  82706. return;
  82707. }
  82708. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  82709. // offset of the headset from the anchor.
  82710. if (this.webVRCamera.leftCamera) {
  82711. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  82712. this._workingVector.subtractInPlace(this.webVRCamera.position);
  82713. location.subtractToRef(this._workingVector, this._workingVector);
  82714. }
  82715. else {
  82716. this._workingVector.copyFrom(location);
  82717. }
  82718. // Add height to account for user's height offset
  82719. if (this.isInVRMode) {
  82720. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;
  82721. }
  82722. else {
  82723. this._workingVector.y += this._defaultHeight;
  82724. }
  82725. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  82726. // Create animation from the camera's position to the new location
  82727. this.currentVRCamera.animations = [];
  82728. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  82729. var animationCameraTeleportationKeys = [{
  82730. frame: 0,
  82731. value: this.currentVRCamera.position
  82732. },
  82733. {
  82734. frame: 11,
  82735. value: this._workingVector
  82736. }
  82737. ];
  82738. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  82739. animationCameraTeleportation.setEasingFunction(this._circleEase);
  82740. this.currentVRCamera.animations.push(animationCameraTeleportation);
  82741. this._postProcessMove.animations = [];
  82742. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  82743. var vignetteWeightKeys = [];
  82744. vignetteWeightKeys.push({
  82745. frame: 0,
  82746. value: 0
  82747. });
  82748. vignetteWeightKeys.push({
  82749. frame: 5,
  82750. value: 8
  82751. });
  82752. vignetteWeightKeys.push({
  82753. frame: 11,
  82754. value: 0
  82755. });
  82756. animationPP.setKeys(vignetteWeightKeys);
  82757. this._postProcessMove.animations.push(animationPP);
  82758. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  82759. var vignetteStretchKeys = [];
  82760. vignetteStretchKeys.push({
  82761. frame: 0,
  82762. value: 0
  82763. });
  82764. vignetteStretchKeys.push({
  82765. frame: 5,
  82766. value: 10
  82767. });
  82768. vignetteStretchKeys.push({
  82769. frame: 11,
  82770. value: 0
  82771. });
  82772. animationPP2.setKeys(vignetteStretchKeys);
  82773. this._postProcessMove.animations.push(animationPP2);
  82774. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  82775. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  82776. this._webVRCamera.attachPostProcess(this._postProcessMove);
  82777. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  82778. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  82779. });
  82780. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  82781. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  82782. });
  82783. this._hideTeleportationTarget();
  82784. };
  82785. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  82786. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  82787. return;
  82788. }
  82789. var hit = this._scene.pickWithRay(gazer._getForwardRay(this._rayLength), this._raySelectionPredicate);
  82790. // Moving the gazeTracker on the mesh face targetted
  82791. if (hit && hit.pickedPoint) {
  82792. if (this._displayGaze) {
  82793. var multiplier = 1;
  82794. gazer._gazeTracker.isVisible = true;
  82795. if (gazer._isActionableMesh) {
  82796. multiplier = 3;
  82797. }
  82798. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  82799. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  82800. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  82801. var pickNormal = hit.getNormal();
  82802. // To avoid z-fighting
  82803. var deltaFighting = 0.002;
  82804. if (pickNormal) {
  82805. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  82806. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  82807. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  82808. }
  82809. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  82810. if (gazer._gazeTracker.position.x < 0) {
  82811. gazer._gazeTracker.position.x += deltaFighting;
  82812. }
  82813. else {
  82814. gazer._gazeTracker.position.x -= deltaFighting;
  82815. }
  82816. if (gazer._gazeTracker.position.y < 0) {
  82817. gazer._gazeTracker.position.y += deltaFighting;
  82818. }
  82819. else {
  82820. gazer._gazeTracker.position.y -= deltaFighting;
  82821. }
  82822. if (gazer._gazeTracker.position.z < 0) {
  82823. gazer._gazeTracker.position.z += deltaFighting;
  82824. }
  82825. else {
  82826. gazer._gazeTracker.position.z -= deltaFighting;
  82827. }
  82828. }
  82829. // Changing the size of the laser pointer based on the distance from the targetted point
  82830. gazer._updatePointerDistance(hit.distance);
  82831. }
  82832. else {
  82833. gazer._gazeTracker.isVisible = false;
  82834. }
  82835. if (hit && hit.pickedMesh) {
  82836. gazer._currentHit = hit;
  82837. if (gazer._pointerDownOnMeshAsked) {
  82838. this._scene.simulatePointerMove(gazer._currentHit, { pointerId: gazer._id });
  82839. }
  82840. // The object selected is the floor, we're in a teleportation scenario
  82841. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  82842. // Moving the teleportation area to this targetted point
  82843. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  82844. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  82845. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  82846. }
  82847. gazer._currentMeshSelected = null;
  82848. if (gazer._teleportationRequestInitiated) {
  82849. this._moveTeleportationSelectorTo(hit, gazer);
  82850. }
  82851. return;
  82852. }
  82853. // If not, we're in a selection scenario
  82854. //this._teleportationAllowed = false;
  82855. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  82856. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  82857. this.onNewMeshPicked.notifyObservers(hit);
  82858. gazer._currentMeshSelected = hit.pickedMesh;
  82859. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  82860. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  82861. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  82862. gazer._isActionableMesh = true;
  82863. }
  82864. else {
  82865. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  82866. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  82867. gazer._isActionableMesh = false;
  82868. }
  82869. try {
  82870. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  82871. }
  82872. catch (err) {
  82873. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  82874. }
  82875. }
  82876. else {
  82877. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  82878. gazer._currentMeshSelected = null;
  82879. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  82880. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  82881. }
  82882. }
  82883. }
  82884. else {
  82885. gazer._currentHit = null;
  82886. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  82887. gazer._currentMeshSelected = null;
  82888. //this._teleportationAllowed = false;
  82889. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  82890. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  82891. }
  82892. };
  82893. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  82894. if (mesh) {
  82895. this.onSelectedMeshUnselected.notifyObservers(mesh);
  82896. }
  82897. };
  82898. /**
  82899. * Sets the color of the laser ray from the vr controllers.
  82900. * @param color new color for the ray.
  82901. */
  82902. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  82903. if (this.leftController) {
  82904. this.leftController._setLaserPointerColor(color);
  82905. }
  82906. if (this.rightController) {
  82907. this.rightController._setLaserPointerColor(color);
  82908. }
  82909. };
  82910. /**
  82911. * Sets the color of the ray from the vr headsets gaze.
  82912. * @param color new color for the ray.
  82913. */
  82914. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  82915. if (!this._cameraGazer._gazeTracker.material) {
  82916. return;
  82917. }
  82918. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  82919. if (this.leftController) {
  82920. this.leftController._gazeTracker.material.emissiveColor = color;
  82921. }
  82922. if (this.rightController) {
  82923. this.rightController._gazeTracker.material.emissiveColor = color;
  82924. }
  82925. };
  82926. /**
  82927. * Exits VR and disposes of the vr experience helper
  82928. */
  82929. VRExperienceHelper.prototype.dispose = function () {
  82930. if (this.isInVRMode) {
  82931. this.exitVR();
  82932. }
  82933. if (this._postProcessMove) {
  82934. this._postProcessMove.dispose();
  82935. }
  82936. if (this._webVRCamera) {
  82937. this._webVRCamera.dispose();
  82938. }
  82939. if (this._vrDeviceOrientationCamera) {
  82940. this._vrDeviceOrientationCamera.dispose();
  82941. }
  82942. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  82943. document.body.removeChild(this._btnVR);
  82944. }
  82945. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  82946. this._deviceOrientationCamera.dispose();
  82947. }
  82948. if (this._cameraGazer) {
  82949. this._cameraGazer.dispose();
  82950. }
  82951. if (this.leftController) {
  82952. this.leftController.dispose();
  82953. }
  82954. if (this.rightController) {
  82955. this.rightController.dispose();
  82956. }
  82957. if (this._teleportationTarget) {
  82958. this._teleportationTarget.dispose();
  82959. }
  82960. this._floorMeshesCollection = [];
  82961. document.removeEventListener("keydown", this._onKeyDown);
  82962. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  82963. window.removeEventListener("resize", this._onResize);
  82964. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  82965. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  82966. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  82967. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  82968. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  82969. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  82970. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  82971. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  82972. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  82973. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  82974. this._scene.unregisterBeforeRender(this.beforeRender);
  82975. };
  82976. /**
  82977. * Gets the name of the VRExperienceHelper class
  82978. * @returns "VRExperienceHelper"
  82979. */
  82980. VRExperienceHelper.prototype.getClassName = function () {
  82981. return "VRExperienceHelper";
  82982. };
  82983. return VRExperienceHelper;
  82984. }());
  82985. BABYLON.VRExperienceHelper = VRExperienceHelper;
  82986. })(BABYLON || (BABYLON = {}));
  82987. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  82988. // Mainly based on these 2 articles :
  82989. // Creating an universal virtual touch joystick working for all Touch models thanks to Hand.JS : http://blogs.msdn.com/b/davrous/archive/2013/02/22/creating-an-universal-virtual-touch-joystick-working-for-all-touch-models-thanks-to-hand-js.aspx
  82990. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  82991. var BABYLON;
  82992. (function (BABYLON) {
  82993. var JoystickAxis;
  82994. (function (JoystickAxis) {
  82995. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  82996. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  82997. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  82998. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  82999. var VirtualJoystick = /** @class */ (function () {
  83000. function VirtualJoystick(leftJoystick) {
  83001. var _this = this;
  83002. if (leftJoystick) {
  83003. this._leftJoystick = true;
  83004. }
  83005. else {
  83006. this._leftJoystick = false;
  83007. }
  83008. VirtualJoystick._globalJoystickIndex++;
  83009. // By default left & right arrow keys are moving the X
  83010. // and up & down keys are moving the Y
  83011. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  83012. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  83013. this.reverseLeftRight = false;
  83014. this.reverseUpDown = false;
  83015. // collections of pointers
  83016. this._touches = new BABYLON.StringDictionary();
  83017. this.deltaPosition = BABYLON.Vector3.Zero();
  83018. this._joystickSensibility = 25;
  83019. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  83020. this._onResize = function (evt) {
  83021. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  83022. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  83023. if (VirtualJoystick.vjCanvas) {
  83024. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  83025. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  83026. }
  83027. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  83028. };
  83029. // injecting a canvas element on top of the canvas 3D game
  83030. if (!VirtualJoystick.vjCanvas) {
  83031. window.addEventListener("resize", this._onResize, false);
  83032. VirtualJoystick.vjCanvas = document.createElement("canvas");
  83033. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  83034. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  83035. VirtualJoystick.vjCanvas.width = window.innerWidth;
  83036. VirtualJoystick.vjCanvas.height = window.innerHeight;
  83037. VirtualJoystick.vjCanvas.style.width = "100%";
  83038. VirtualJoystick.vjCanvas.style.height = "100%";
  83039. VirtualJoystick.vjCanvas.style.position = "absolute";
  83040. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  83041. VirtualJoystick.vjCanvas.style.top = "0px";
  83042. VirtualJoystick.vjCanvas.style.left = "0px";
  83043. VirtualJoystick.vjCanvas.style.zIndex = "5";
  83044. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  83045. // Support for jQuery PEP polyfill
  83046. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  83047. var context = VirtualJoystick.vjCanvas.getContext('2d');
  83048. if (!context) {
  83049. throw new Error("Unable to create canvas for virtual joystick");
  83050. }
  83051. VirtualJoystick.vjCanvasContext = context;
  83052. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  83053. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  83054. document.body.appendChild(VirtualJoystick.vjCanvas);
  83055. }
  83056. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  83057. this.pressed = false;
  83058. // default joystick color
  83059. this._joystickColor = "cyan";
  83060. this._joystickPointerID = -1;
  83061. // current joystick position
  83062. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  83063. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  83064. // origin joystick position
  83065. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  83066. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  83067. this._onPointerDownHandlerRef = function (evt) {
  83068. _this._onPointerDown(evt);
  83069. };
  83070. this._onPointerMoveHandlerRef = function (evt) {
  83071. _this._onPointerMove(evt);
  83072. };
  83073. this._onPointerUpHandlerRef = function (evt) {
  83074. _this._onPointerUp(evt);
  83075. };
  83076. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  83077. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  83078. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  83079. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  83080. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  83081. evt.preventDefault(); // Disables system menu
  83082. }, false);
  83083. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  83084. }
  83085. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  83086. this._joystickSensibility = newJoystickSensibility;
  83087. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  83088. };
  83089. VirtualJoystick.prototype._onPointerDown = function (e) {
  83090. var positionOnScreenCondition;
  83091. e.preventDefault();
  83092. if (this._leftJoystick === true) {
  83093. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  83094. }
  83095. else {
  83096. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  83097. }
  83098. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  83099. // First contact will be dedicated to the virtual joystick
  83100. this._joystickPointerID = e.pointerId;
  83101. this._joystickPointerStartPos.x = e.clientX;
  83102. this._joystickPointerStartPos.y = e.clientY;
  83103. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  83104. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  83105. this._deltaJoystickVector.x = 0;
  83106. this._deltaJoystickVector.y = 0;
  83107. this.pressed = true;
  83108. this._touches.add(e.pointerId.toString(), e);
  83109. }
  83110. else {
  83111. // You can only trigger the action buttons with a joystick declared
  83112. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  83113. this._action();
  83114. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  83115. }
  83116. }
  83117. };
  83118. VirtualJoystick.prototype._onPointerMove = function (e) {
  83119. // If the current pointer is the one associated to the joystick (first touch contact)
  83120. if (this._joystickPointerID == e.pointerId) {
  83121. this._joystickPointerPos.x = e.clientX;
  83122. this._joystickPointerPos.y = e.clientY;
  83123. this._deltaJoystickVector = this._joystickPointerPos.clone();
  83124. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  83125. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  83126. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  83127. switch (this._axisTargetedByLeftAndRight) {
  83128. case JoystickAxis.X:
  83129. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  83130. break;
  83131. case JoystickAxis.Y:
  83132. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  83133. break;
  83134. case JoystickAxis.Z:
  83135. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  83136. break;
  83137. }
  83138. var directionUpDown = this.reverseUpDown ? 1 : -1;
  83139. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  83140. switch (this._axisTargetedByUpAndDown) {
  83141. case JoystickAxis.X:
  83142. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  83143. break;
  83144. case JoystickAxis.Y:
  83145. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  83146. break;
  83147. case JoystickAxis.Z:
  83148. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  83149. break;
  83150. }
  83151. }
  83152. else {
  83153. var data = this._touches.get(e.pointerId.toString());
  83154. if (data) {
  83155. data.x = e.clientX;
  83156. data.y = e.clientY;
  83157. }
  83158. }
  83159. };
  83160. VirtualJoystick.prototype._onPointerUp = function (e) {
  83161. if (this._joystickPointerID == e.pointerId) {
  83162. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  83163. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  83164. this._joystickPointerID = -1;
  83165. this.pressed = false;
  83166. }
  83167. else {
  83168. var touch = this._touches.get(e.pointerId.toString());
  83169. if (touch) {
  83170. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  83171. }
  83172. }
  83173. this._deltaJoystickVector.x = 0;
  83174. this._deltaJoystickVector.y = 0;
  83175. this._touches.remove(e.pointerId.toString());
  83176. };
  83177. /**
  83178. * Change the color of the virtual joystick
  83179. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  83180. */
  83181. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  83182. this._joystickColor = newColor;
  83183. };
  83184. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  83185. this._action = action;
  83186. };
  83187. // Define which axis you'd like to control for left & right
  83188. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  83189. switch (axis) {
  83190. case JoystickAxis.X:
  83191. case JoystickAxis.Y:
  83192. case JoystickAxis.Z:
  83193. this._axisTargetedByLeftAndRight = axis;
  83194. break;
  83195. default:
  83196. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  83197. break;
  83198. }
  83199. };
  83200. // Define which axis you'd like to control for up & down
  83201. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  83202. switch (axis) {
  83203. case JoystickAxis.X:
  83204. case JoystickAxis.Y:
  83205. case JoystickAxis.Z:
  83206. this._axisTargetedByUpAndDown = axis;
  83207. break;
  83208. default:
  83209. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  83210. break;
  83211. }
  83212. };
  83213. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  83214. var _this = this;
  83215. if (this.pressed) {
  83216. this._touches.forEach(function (key, touch) {
  83217. if (touch.pointerId === _this._joystickPointerID) {
  83218. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  83219. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  83220. VirtualJoystick.vjCanvasContext.beginPath();
  83221. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  83222. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  83223. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  83224. VirtualJoystick.vjCanvasContext.stroke();
  83225. VirtualJoystick.vjCanvasContext.closePath();
  83226. VirtualJoystick.vjCanvasContext.beginPath();
  83227. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  83228. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  83229. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  83230. VirtualJoystick.vjCanvasContext.stroke();
  83231. VirtualJoystick.vjCanvasContext.closePath();
  83232. VirtualJoystick.vjCanvasContext.beginPath();
  83233. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  83234. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  83235. VirtualJoystick.vjCanvasContext.stroke();
  83236. VirtualJoystick.vjCanvasContext.closePath();
  83237. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  83238. }
  83239. else {
  83240. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  83241. VirtualJoystick.vjCanvasContext.beginPath();
  83242. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  83243. VirtualJoystick.vjCanvasContext.beginPath();
  83244. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  83245. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  83246. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  83247. VirtualJoystick.vjCanvasContext.stroke();
  83248. VirtualJoystick.vjCanvasContext.closePath();
  83249. touch.prevX = touch.x;
  83250. touch.prevY = touch.y;
  83251. }
  83252. ;
  83253. });
  83254. }
  83255. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  83256. };
  83257. VirtualJoystick.prototype.releaseCanvas = function () {
  83258. if (VirtualJoystick.vjCanvas) {
  83259. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  83260. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  83261. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  83262. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  83263. window.removeEventListener("resize", this._onResize);
  83264. document.body.removeChild(VirtualJoystick.vjCanvas);
  83265. VirtualJoystick.vjCanvas = null;
  83266. }
  83267. };
  83268. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  83269. VirtualJoystick._globalJoystickIndex = 0;
  83270. return VirtualJoystick;
  83271. }());
  83272. BABYLON.VirtualJoystick = VirtualJoystick;
  83273. })(BABYLON || (BABYLON = {}));
  83274. //# sourceMappingURL=babylon.virtualJoystick.js.map
  83275. var BABYLON;
  83276. (function (BABYLON) {
  83277. // We're mainly based on the logic defined into the FreeCamera code
  83278. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  83279. __extends(VirtualJoysticksCamera, _super);
  83280. function VirtualJoysticksCamera(name, position, scene) {
  83281. var _this = _super.call(this, name, position, scene) || this;
  83282. _this.inputs.addVirtualJoystick();
  83283. return _this;
  83284. }
  83285. VirtualJoysticksCamera.prototype.getClassName = function () {
  83286. return "VirtualJoysticksCamera";
  83287. };
  83288. return VirtualJoysticksCamera;
  83289. }(BABYLON.FreeCamera));
  83290. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  83291. })(BABYLON || (BABYLON = {}));
  83292. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  83293. var BABYLON;
  83294. (function (BABYLON) {
  83295. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  83296. function FreeCameraVirtualJoystickInput() {
  83297. }
  83298. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  83299. return this._leftjoystick;
  83300. };
  83301. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  83302. return this._rightjoystick;
  83303. };
  83304. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  83305. if (this._leftjoystick) {
  83306. var camera = this.camera;
  83307. var speed = camera._computeLocalCameraSpeed() * 50;
  83308. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  83309. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  83310. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  83311. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  83312. if (!this._leftjoystick.pressed) {
  83313. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  83314. }
  83315. if (!this._rightjoystick.pressed) {
  83316. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  83317. }
  83318. }
  83319. };
  83320. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  83321. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  83322. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  83323. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  83324. this._leftjoystick.setJoystickSensibility(0.15);
  83325. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  83326. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  83327. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  83328. this._rightjoystick.reverseUpDown = true;
  83329. this._rightjoystick.setJoystickSensibility(0.05);
  83330. this._rightjoystick.setJoystickColor("yellow");
  83331. };
  83332. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  83333. this._leftjoystick.releaseCanvas();
  83334. this._rightjoystick.releaseCanvas();
  83335. };
  83336. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  83337. return "FreeCameraVirtualJoystickInput";
  83338. };
  83339. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  83340. return "virtualJoystick";
  83341. };
  83342. return FreeCameraVirtualJoystickInput;
  83343. }());
  83344. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  83345. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  83346. })(BABYLON || (BABYLON = {}));
  83347. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  83348. var BABYLON;
  83349. (function (BABYLON) {
  83350. var SimplificationSettings = /** @class */ (function () {
  83351. function SimplificationSettings(quality, distance, optimizeMesh) {
  83352. this.quality = quality;
  83353. this.distance = distance;
  83354. this.optimizeMesh = optimizeMesh;
  83355. }
  83356. return SimplificationSettings;
  83357. }());
  83358. BABYLON.SimplificationSettings = SimplificationSettings;
  83359. var SimplificationQueue = /** @class */ (function () {
  83360. function SimplificationQueue() {
  83361. this.running = false;
  83362. this._simplificationArray = [];
  83363. }
  83364. SimplificationQueue.prototype.addTask = function (task) {
  83365. this._simplificationArray.push(task);
  83366. };
  83367. SimplificationQueue.prototype.executeNext = function () {
  83368. var task = this._simplificationArray.pop();
  83369. if (task) {
  83370. this.running = true;
  83371. this.runSimplification(task);
  83372. }
  83373. else {
  83374. this.running = false;
  83375. }
  83376. };
  83377. SimplificationQueue.prototype.runSimplification = function (task) {
  83378. var _this = this;
  83379. if (task.parallelProcessing) {
  83380. //parallel simplifier
  83381. task.settings.forEach(function (setting) {
  83382. var simplifier = _this.getSimplifier(task);
  83383. simplifier.simplify(setting, function (newMesh) {
  83384. task.mesh.addLODLevel(setting.distance, newMesh);
  83385. newMesh.isVisible = true;
  83386. //check if it is the last
  83387. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  83388. //all done, run the success callback.
  83389. task.successCallback();
  83390. }
  83391. _this.executeNext();
  83392. });
  83393. });
  83394. }
  83395. else {
  83396. //single simplifier.
  83397. var simplifier = this.getSimplifier(task);
  83398. var runDecimation = function (setting, callback) {
  83399. simplifier.simplify(setting, function (newMesh) {
  83400. task.mesh.addLODLevel(setting.distance, newMesh);
  83401. newMesh.isVisible = true;
  83402. //run the next quality level
  83403. callback();
  83404. });
  83405. };
  83406. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  83407. runDecimation(task.settings[loop.index], function () {
  83408. loop.executeNext();
  83409. });
  83410. }, function () {
  83411. //execution ended, run the success callback.
  83412. if (task.successCallback) {
  83413. task.successCallback();
  83414. }
  83415. _this.executeNext();
  83416. });
  83417. }
  83418. };
  83419. SimplificationQueue.prototype.getSimplifier = function (task) {
  83420. switch (task.simplificationType) {
  83421. case SimplificationType.QUADRATIC:
  83422. default:
  83423. return new QuadraticErrorSimplification(task.mesh);
  83424. }
  83425. };
  83426. return SimplificationQueue;
  83427. }());
  83428. BABYLON.SimplificationQueue = SimplificationQueue;
  83429. /**
  83430. * The implemented types of simplification.
  83431. * At the moment only Quadratic Error Decimation is implemented.
  83432. */
  83433. var SimplificationType;
  83434. (function (SimplificationType) {
  83435. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  83436. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  83437. var DecimationTriangle = /** @class */ (function () {
  83438. function DecimationTriangle(vertices) {
  83439. this.vertices = vertices;
  83440. this.error = new Array(4);
  83441. this.deleted = false;
  83442. this.isDirty = false;
  83443. this.deletePending = false;
  83444. this.borderFactor = 0;
  83445. }
  83446. return DecimationTriangle;
  83447. }());
  83448. BABYLON.DecimationTriangle = DecimationTriangle;
  83449. var DecimationVertex = /** @class */ (function () {
  83450. function DecimationVertex(position, id) {
  83451. this.position = position;
  83452. this.id = id;
  83453. this.isBorder = true;
  83454. this.q = new QuadraticMatrix();
  83455. this.triangleCount = 0;
  83456. this.triangleStart = 0;
  83457. this.originalOffsets = [];
  83458. }
  83459. DecimationVertex.prototype.updatePosition = function (newPosition) {
  83460. this.position.copyFrom(newPosition);
  83461. };
  83462. return DecimationVertex;
  83463. }());
  83464. BABYLON.DecimationVertex = DecimationVertex;
  83465. var QuadraticMatrix = /** @class */ (function () {
  83466. function QuadraticMatrix(data) {
  83467. this.data = new Array(10);
  83468. for (var i = 0; i < 10; ++i) {
  83469. if (data && data[i]) {
  83470. this.data[i] = data[i];
  83471. }
  83472. else {
  83473. this.data[i] = 0;
  83474. }
  83475. }
  83476. }
  83477. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  83478. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  83479. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  83480. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  83481. return det;
  83482. };
  83483. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  83484. for (var i = 0; i < 10; ++i) {
  83485. this.data[i] += matrix.data[i];
  83486. }
  83487. };
  83488. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  83489. for (var i = 0; i < 10; ++i) {
  83490. this.data[i] += data[i];
  83491. }
  83492. };
  83493. QuadraticMatrix.prototype.add = function (matrix) {
  83494. var m = new QuadraticMatrix();
  83495. for (var i = 0; i < 10; ++i) {
  83496. m.data[i] = this.data[i] + matrix.data[i];
  83497. }
  83498. return m;
  83499. };
  83500. QuadraticMatrix.FromData = function (a, b, c, d) {
  83501. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  83502. };
  83503. //returning an array to avoid garbage collection
  83504. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  83505. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  83506. };
  83507. return QuadraticMatrix;
  83508. }());
  83509. BABYLON.QuadraticMatrix = QuadraticMatrix;
  83510. var Reference = /** @class */ (function () {
  83511. function Reference(vertexId, triangleId) {
  83512. this.vertexId = vertexId;
  83513. this.triangleId = triangleId;
  83514. }
  83515. return Reference;
  83516. }());
  83517. BABYLON.Reference = Reference;
  83518. /**
  83519. * An implementation of the Quadratic Error simplification algorithm.
  83520. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  83521. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  83522. * @author RaananW
  83523. */
  83524. var QuadraticErrorSimplification = /** @class */ (function () {
  83525. function QuadraticErrorSimplification(_mesh) {
  83526. this._mesh = _mesh;
  83527. this.syncIterations = 5000;
  83528. this.aggressiveness = 7;
  83529. this.decimationIterations = 100;
  83530. this.boundingBoxEpsilon = BABYLON.Epsilon;
  83531. }
  83532. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  83533. var _this = this;
  83534. this.initDecimatedMesh();
  83535. //iterating through the submeshes array, one after the other.
  83536. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  83537. _this.initWithMesh(loop.index, function () {
  83538. _this.runDecimation(settings, loop.index, function () {
  83539. loop.executeNext();
  83540. });
  83541. }, settings.optimizeMesh);
  83542. }, function () {
  83543. setTimeout(function () {
  83544. successCallback(_this._reconstructedMesh);
  83545. }, 0);
  83546. });
  83547. };
  83548. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  83549. var _this = this;
  83550. var targetCount = ~~(this.triangles.length * settings.quality);
  83551. var deletedTriangles = 0;
  83552. var triangleCount = this.triangles.length;
  83553. var iterationFunction = function (iteration, callback) {
  83554. setTimeout(function () {
  83555. if (iteration % 5 === 0) {
  83556. _this.updateMesh(iteration === 0);
  83557. }
  83558. for (var i = 0; i < _this.triangles.length; ++i) {
  83559. _this.triangles[i].isDirty = false;
  83560. }
  83561. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  83562. var trianglesIterator = function (i) {
  83563. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  83564. var t = _this.triangles[tIdx];
  83565. if (!t)
  83566. return;
  83567. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  83568. return;
  83569. }
  83570. for (var j = 0; j < 3; ++j) {
  83571. if (t.error[j] < threshold) {
  83572. var deleted0 = [];
  83573. var deleted1 = [];
  83574. var v0 = t.vertices[j];
  83575. var v1 = t.vertices[(j + 1) % 3];
  83576. if (v0.isBorder || v1.isBorder)
  83577. continue;
  83578. var p = BABYLON.Vector3.Zero();
  83579. var n = BABYLON.Vector3.Zero();
  83580. var uv = BABYLON.Vector2.Zero();
  83581. var color = new BABYLON.Color4(0, 0, 0, 1);
  83582. _this.calculateError(v0, v1, p, n, uv, color);
  83583. var delTr = new Array();
  83584. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  83585. continue;
  83586. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  83587. continue;
  83588. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  83589. continue;
  83590. var uniqueArray = new Array();
  83591. delTr.forEach(function (deletedT) {
  83592. if (uniqueArray.indexOf(deletedT) === -1) {
  83593. deletedT.deletePending = true;
  83594. uniqueArray.push(deletedT);
  83595. }
  83596. });
  83597. if (uniqueArray.length % 2 !== 0) {
  83598. continue;
  83599. }
  83600. v0.q = v1.q.add(v0.q);
  83601. v0.updatePosition(p);
  83602. var tStart = _this.references.length;
  83603. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  83604. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  83605. var tCount = _this.references.length - tStart;
  83606. if (tCount <= v0.triangleCount) {
  83607. if (tCount) {
  83608. for (var c = 0; c < tCount; c++) {
  83609. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  83610. }
  83611. }
  83612. }
  83613. else {
  83614. v0.triangleStart = tStart;
  83615. }
  83616. v0.triangleCount = tCount;
  83617. break;
  83618. }
  83619. }
  83620. };
  83621. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  83622. }, 0);
  83623. };
  83624. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  83625. if (triangleCount - deletedTriangles <= targetCount)
  83626. loop.breakLoop();
  83627. else {
  83628. iterationFunction(loop.index, function () {
  83629. loop.executeNext();
  83630. });
  83631. }
  83632. }, function () {
  83633. setTimeout(function () {
  83634. //reconstruct this part of the mesh
  83635. _this.reconstructMesh(submeshIndex);
  83636. successCallback();
  83637. }, 0);
  83638. });
  83639. };
  83640. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  83641. var _this = this;
  83642. this.vertices = [];
  83643. this.triangles = [];
  83644. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  83645. var indices = this._mesh.getIndices();
  83646. var submesh = this._mesh.subMeshes[submeshIndex];
  83647. var findInVertices = function (positionToSearch) {
  83648. if (optimizeMesh) {
  83649. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  83650. if (_this.vertices[ii].position.equals(positionToSearch)) {
  83651. return _this.vertices[ii];
  83652. }
  83653. }
  83654. }
  83655. return null;
  83656. };
  83657. var vertexReferences = [];
  83658. var vertexInit = function (i) {
  83659. if (!positionData) {
  83660. return;
  83661. }
  83662. var offset = i + submesh.verticesStart;
  83663. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  83664. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  83665. vertex.originalOffsets.push(offset);
  83666. if (vertex.id === _this.vertices.length) {
  83667. _this.vertices.push(vertex);
  83668. }
  83669. vertexReferences.push(vertex.id);
  83670. };
  83671. //var totalVertices = mesh.getTotalVertices();
  83672. var totalVertices = submesh.verticesCount;
  83673. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  83674. var indicesInit = function (i) {
  83675. if (!indices) {
  83676. return;
  83677. }
  83678. var offset = (submesh.indexStart / 3) + i;
  83679. var pos = (offset * 3);
  83680. var i0 = indices[pos + 0];
  83681. var i1 = indices[pos + 1];
  83682. var i2 = indices[pos + 2];
  83683. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  83684. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  83685. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  83686. var triangle = new DecimationTriangle([v0, v1, v2]);
  83687. triangle.originalOffset = pos;
  83688. _this.triangles.push(triangle);
  83689. };
  83690. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  83691. _this.init(callback);
  83692. });
  83693. });
  83694. };
  83695. QuadraticErrorSimplification.prototype.init = function (callback) {
  83696. var _this = this;
  83697. var triangleInit1 = function (i) {
  83698. var t = _this.triangles[i];
  83699. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  83700. for (var j = 0; j < 3; j++) {
  83701. t.vertices[j].q.addArrayInPlace(QuadraticMatrix.DataFromNumbers(t.normal.x, t.normal.y, t.normal.z, -(BABYLON.Vector3.Dot(t.normal, t.vertices[0].position))));
  83702. }
  83703. };
  83704. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  83705. var triangleInit2 = function (i) {
  83706. var t = _this.triangles[i];
  83707. for (var j = 0; j < 3; ++j) {
  83708. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  83709. }
  83710. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  83711. };
  83712. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  83713. callback();
  83714. });
  83715. });
  83716. };
  83717. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  83718. var newTriangles = [];
  83719. var i;
  83720. for (i = 0; i < this.vertices.length; ++i) {
  83721. this.vertices[i].triangleCount = 0;
  83722. }
  83723. var t;
  83724. var j;
  83725. for (i = 0; i < this.triangles.length; ++i) {
  83726. if (!this.triangles[i].deleted) {
  83727. t = this.triangles[i];
  83728. for (j = 0; j < 3; ++j) {
  83729. t.vertices[j].triangleCount = 1;
  83730. }
  83731. newTriangles.push(t);
  83732. }
  83733. }
  83734. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  83735. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  83736. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  83737. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  83738. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  83739. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  83740. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  83741. var vertexCount = 0;
  83742. for (i = 0; i < this.vertices.length; ++i) {
  83743. var vertex = this.vertices[i];
  83744. vertex.id = vertexCount;
  83745. if (vertex.triangleCount) {
  83746. vertex.originalOffsets.forEach(function (originalOffset) {
  83747. if (!normalData) {
  83748. return;
  83749. }
  83750. newPositionData.push(vertex.position.x);
  83751. newPositionData.push(vertex.position.y);
  83752. newPositionData.push(vertex.position.z);
  83753. newNormalData.push(normalData[originalOffset * 3]);
  83754. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  83755. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  83756. if (uvs && uvs.length) {
  83757. newUVsData.push(uvs[(originalOffset * 2)]);
  83758. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  83759. }
  83760. else if (colorsData && colorsData.length) {
  83761. newColorsData.push(colorsData[(originalOffset * 4)]);
  83762. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  83763. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  83764. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  83765. }
  83766. ++vertexCount;
  83767. });
  83768. }
  83769. }
  83770. var startingIndex = this._reconstructedMesh.getTotalIndices();
  83771. var startingVertex = this._reconstructedMesh.getTotalVertices();
  83772. var submeshesArray = this._reconstructedMesh.subMeshes;
  83773. this._reconstructedMesh.subMeshes = [];
  83774. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  83775. var originalIndices = this._mesh.getIndices();
  83776. for (i = 0; i < newTriangles.length; ++i) {
  83777. t = newTriangles[i]; //now get the new referencing point for each vertex
  83778. [0, 1, 2].forEach(function (idx) {
  83779. var id = originalIndices[t.originalOffset + idx];
  83780. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  83781. if (offset < 0)
  83782. offset = 0;
  83783. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  83784. });
  83785. }
  83786. //overwriting the old vertex buffers and indices.
  83787. this._reconstructedMesh.setIndices(newIndicesArray);
  83788. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  83789. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  83790. if (newUVsData.length > 0)
  83791. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  83792. if (newColorsData.length > 0)
  83793. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  83794. //create submesh
  83795. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  83796. if (submeshIndex > 0) {
  83797. this._reconstructedMesh.subMeshes = [];
  83798. submeshesArray.forEach(function (submesh) {
  83799. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  83800. });
  83801. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  83802. }
  83803. };
  83804. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  83805. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  83806. this._reconstructedMesh.material = this._mesh.material;
  83807. this._reconstructedMesh.parent = this._mesh.parent;
  83808. this._reconstructedMesh.isVisible = false;
  83809. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  83810. };
  83811. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  83812. for (var i = 0; i < vertex1.triangleCount; ++i) {
  83813. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  83814. if (t.deleted)
  83815. continue;
  83816. var s = this.references[vertex1.triangleStart + i].vertexId;
  83817. var v1 = t.vertices[(s + 1) % 3];
  83818. var v2 = t.vertices[(s + 2) % 3];
  83819. if ((v1 === vertex2 || v2 === vertex2)) {
  83820. deletedArray[i] = true;
  83821. delTr.push(t);
  83822. continue;
  83823. }
  83824. var d1 = v1.position.subtract(point);
  83825. d1 = d1.normalize();
  83826. var d2 = v2.position.subtract(point);
  83827. d2 = d2.normalize();
  83828. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  83829. return true;
  83830. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  83831. deletedArray[i] = false;
  83832. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  83833. return true;
  83834. }
  83835. return false;
  83836. };
  83837. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  83838. var newDeleted = deletedTriangles;
  83839. for (var i = 0; i < vertex.triangleCount; ++i) {
  83840. var ref = this.references[vertex.triangleStart + i];
  83841. var t = this.triangles[ref.triangleId];
  83842. if (t.deleted)
  83843. continue;
  83844. if (deletedArray[i] && t.deletePending) {
  83845. t.deleted = true;
  83846. newDeleted++;
  83847. continue;
  83848. }
  83849. t.vertices[ref.vertexId] = origVertex;
  83850. t.isDirty = true;
  83851. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  83852. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  83853. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  83854. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  83855. this.references.push(ref);
  83856. }
  83857. return newDeleted;
  83858. };
  83859. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  83860. for (var i = 0; i < this.vertices.length; ++i) {
  83861. var vCount = [];
  83862. var vId = [];
  83863. var v = this.vertices[i];
  83864. var j;
  83865. for (j = 0; j < v.triangleCount; ++j) {
  83866. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  83867. for (var ii = 0; ii < 3; ii++) {
  83868. var ofs = 0;
  83869. var vv = triangle.vertices[ii];
  83870. while (ofs < vCount.length) {
  83871. if (vId[ofs] === vv.id)
  83872. break;
  83873. ++ofs;
  83874. }
  83875. if (ofs === vCount.length) {
  83876. vCount.push(1);
  83877. vId.push(vv.id);
  83878. }
  83879. else {
  83880. vCount[ofs]++;
  83881. }
  83882. }
  83883. }
  83884. for (j = 0; j < vCount.length; ++j) {
  83885. if (vCount[j] === 1) {
  83886. this.vertices[vId[j]].isBorder = true;
  83887. }
  83888. else {
  83889. this.vertices[vId[j]].isBorder = false;
  83890. }
  83891. }
  83892. }
  83893. };
  83894. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  83895. if (identifyBorders === void 0) { identifyBorders = false; }
  83896. var i;
  83897. if (!identifyBorders) {
  83898. var newTrianglesVector = [];
  83899. for (i = 0; i < this.triangles.length; ++i) {
  83900. if (!this.triangles[i].deleted) {
  83901. newTrianglesVector.push(this.triangles[i]);
  83902. }
  83903. }
  83904. this.triangles = newTrianglesVector;
  83905. }
  83906. for (i = 0; i < this.vertices.length; ++i) {
  83907. this.vertices[i].triangleCount = 0;
  83908. this.vertices[i].triangleStart = 0;
  83909. }
  83910. var t;
  83911. var j;
  83912. var v;
  83913. for (i = 0; i < this.triangles.length; ++i) {
  83914. t = this.triangles[i];
  83915. for (j = 0; j < 3; ++j) {
  83916. v = t.vertices[j];
  83917. v.triangleCount++;
  83918. }
  83919. }
  83920. var tStart = 0;
  83921. for (i = 0; i < this.vertices.length; ++i) {
  83922. this.vertices[i].triangleStart = tStart;
  83923. tStart += this.vertices[i].triangleCount;
  83924. this.vertices[i].triangleCount = 0;
  83925. }
  83926. var newReferences = new Array(this.triangles.length * 3);
  83927. for (i = 0; i < this.triangles.length; ++i) {
  83928. t = this.triangles[i];
  83929. for (j = 0; j < 3; ++j) {
  83930. v = t.vertices[j];
  83931. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  83932. v.triangleCount++;
  83933. }
  83934. }
  83935. this.references = newReferences;
  83936. if (identifyBorders) {
  83937. this.identifyBorder();
  83938. }
  83939. };
  83940. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  83941. var x = point.x;
  83942. var y = point.y;
  83943. var z = point.z;
  83944. return q.data[0] * x * x + 2 * q.data[1] * x * y + 2 * q.data[2] * x * z + 2 * q.data[3] * x + q.data[4] * y * y
  83945. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  83946. };
  83947. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  83948. var q = vertex1.q.add(vertex2.q);
  83949. var border = vertex1.isBorder && vertex2.isBorder;
  83950. var error = 0;
  83951. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  83952. if (qDet !== 0 && !border) {
  83953. if (!pointResult) {
  83954. pointResult = BABYLON.Vector3.Zero();
  83955. }
  83956. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  83957. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  83958. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  83959. error = this.vertexError(q, pointResult);
  83960. }
  83961. else {
  83962. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  83963. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  83964. var error1 = this.vertexError(q, vertex1.position);
  83965. var error2 = this.vertexError(q, vertex2.position);
  83966. var error3 = this.vertexError(q, p3);
  83967. error = Math.min(error1, error2, error3);
  83968. if (error === error1) {
  83969. if (pointResult) {
  83970. pointResult.copyFrom(vertex1.position);
  83971. }
  83972. }
  83973. else if (error === error2) {
  83974. if (pointResult) {
  83975. pointResult.copyFrom(vertex2.position);
  83976. }
  83977. }
  83978. else {
  83979. if (pointResult) {
  83980. pointResult.copyFrom(p3);
  83981. }
  83982. }
  83983. }
  83984. return error;
  83985. };
  83986. return QuadraticErrorSimplification;
  83987. }());
  83988. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  83989. })(BABYLON || (BABYLON = {}));
  83990. //# sourceMappingURL=babylon.meshSimplification.js.map
  83991. var BABYLON;
  83992. (function (BABYLON) {
  83993. var MeshLODLevel = /** @class */ (function () {
  83994. function MeshLODLevel(distance, mesh) {
  83995. this.distance = distance;
  83996. this.mesh = mesh;
  83997. }
  83998. return MeshLODLevel;
  83999. }());
  84000. BABYLON.MeshLODLevel = MeshLODLevel;
  84001. })(BABYLON || (BABYLON = {}));
  84002. //# sourceMappingURL=babylon.meshLODLevel.js.map
  84003. var BABYLON;
  84004. (function (BABYLON) {
  84005. /**
  84006. * Defines the root class used to create scene optimization to use with SceneOptimizer
  84007. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  84008. */
  84009. var SceneOptimization = /** @class */ (function () {
  84010. /**
  84011. * Creates the SceneOptimization object
  84012. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  84013. * @param desc defines the description associated with the optimization
  84014. */
  84015. function SceneOptimization(
  84016. /**
  84017. * Defines the priority of this optimization (0 by default which means first in the list)
  84018. */
  84019. priority) {
  84020. if (priority === void 0) { priority = 0; }
  84021. this.priority = priority;
  84022. }
  84023. /**
  84024. * Gets a string describing the action executed by the current optimization
  84025. * @returns description string
  84026. */
  84027. SceneOptimization.prototype.getDescription = function () {
  84028. return "";
  84029. };
  84030. /**
  84031. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  84032. * @param scene defines the current scene where to apply this optimization
  84033. * @param optimizer defines the current optimizer
  84034. * @returns true if everything that can be done was applied
  84035. */
  84036. SceneOptimization.prototype.apply = function (scene, optimizer) {
  84037. return true;
  84038. };
  84039. ;
  84040. return SceneOptimization;
  84041. }());
  84042. BABYLON.SceneOptimization = SceneOptimization;
  84043. /**
  84044. * Defines an optimization used to reduce the size of render target textures
  84045. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  84046. */
  84047. var TextureOptimization = /** @class */ (function (_super) {
  84048. __extends(TextureOptimization, _super);
  84049. /**
  84050. * Creates the TextureOptimization object
  84051. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  84052. * @param maximumSize defines the maximum sized allowed for textures (1024 is the default value). If a texture is bigger, it will be scaled down using a factor defined by the step parameter
  84053. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  84054. */
  84055. function TextureOptimization(
  84056. /**
  84057. * Defines the priority of this optimization (0 by default which means first in the list)
  84058. */
  84059. priority,
  84060. /**
  84061. * Defines the maximum sized allowed for textures (1024 is the default value). If a texture is bigger, it will be scaled down using a factor defined by the step parameter
  84062. */
  84063. maximumSize,
  84064. /**
  84065. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  84066. */
  84067. step) {
  84068. if (priority === void 0) { priority = 0; }
  84069. if (maximumSize === void 0) { maximumSize = 1024; }
  84070. if (step === void 0) { step = 0.5; }
  84071. var _this = _super.call(this, priority) || this;
  84072. _this.priority = priority;
  84073. _this.maximumSize = maximumSize;
  84074. _this.step = step;
  84075. return _this;
  84076. }
  84077. /**
  84078. * Gets a string describing the action executed by the current optimization
  84079. * @returns description string
  84080. */
  84081. TextureOptimization.prototype.getDescription = function () {
  84082. return "Reducing render target texture size to " + this.maximumSize;
  84083. };
  84084. /**
  84085. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  84086. * @param scene defines the current scene where to apply this optimization
  84087. * @param optimizer defines the current optimizer
  84088. * @returns true if everything that can be done was applied
  84089. */
  84090. TextureOptimization.prototype.apply = function (scene, optimizer) {
  84091. var allDone = true;
  84092. for (var index = 0; index < scene.textures.length; index++) {
  84093. var texture = scene.textures[index];
  84094. if (!texture.canRescale || texture.getContext) {
  84095. continue;
  84096. }
  84097. var currentSize = texture.getSize();
  84098. var maxDimension = Math.max(currentSize.width, currentSize.height);
  84099. if (maxDimension > this.maximumSize) {
  84100. texture.scale(this.step);
  84101. allDone = false;
  84102. }
  84103. }
  84104. return allDone;
  84105. };
  84106. return TextureOptimization;
  84107. }(SceneOptimization));
  84108. BABYLON.TextureOptimization = TextureOptimization;
  84109. /**
  84110. * Defines an optimization used to increase or decrease the rendering resolution
  84111. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  84112. */
  84113. var HardwareScalingOptimization = /** @class */ (function (_super) {
  84114. __extends(HardwareScalingOptimization, _super);
  84115. /**
  84116. * Creates the HardwareScalingOptimization object
  84117. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  84118. * @param maximumScale defines the maximum scale to use (2 by default)
  84119. * @param step defines the step to use between two passes (0.5 by default)
  84120. */
  84121. function HardwareScalingOptimization(
  84122. /**
  84123. * Defines the priority of this optimization (0 by default which means first in the list)
  84124. */
  84125. priority,
  84126. /**
  84127. * Defines the maximum scale to use (2 by default)
  84128. */
  84129. maximumScale,
  84130. /**
  84131. * Defines the step to use between two passes (0.5 by default)
  84132. */
  84133. step) {
  84134. if (priority === void 0) { priority = 0; }
  84135. if (maximumScale === void 0) { maximumScale = 2; }
  84136. if (step === void 0) { step = 0.25; }
  84137. var _this = _super.call(this, priority) || this;
  84138. _this.priority = priority;
  84139. _this.maximumScale = maximumScale;
  84140. _this.step = step;
  84141. _this._currentScale = -1;
  84142. _this._directionOffset = 1;
  84143. return _this;
  84144. }
  84145. /**
  84146. * Gets a string describing the action executed by the current optimization
  84147. * @return description string
  84148. */
  84149. HardwareScalingOptimization.prototype.getDescription = function () {
  84150. return "Setting hardware scaling level to " + this._currentScale;
  84151. };
  84152. /**
  84153. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  84154. * @param scene defines the current scene where to apply this optimization
  84155. * @param optimizer defines the current optimizer
  84156. * @returns true if everything that can be done was applied
  84157. */
  84158. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  84159. if (this._currentScale === -1) {
  84160. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  84161. if (this._currentScale > this.maximumScale) {
  84162. this._directionOffset = -1;
  84163. }
  84164. }
  84165. this._currentScale += this._directionOffset * this.step;
  84166. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  84167. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  84168. };
  84169. ;
  84170. return HardwareScalingOptimization;
  84171. }(SceneOptimization));
  84172. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  84173. /**
  84174. * Defines an optimization used to remove shadows
  84175. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  84176. */
  84177. var ShadowsOptimization = /** @class */ (function (_super) {
  84178. __extends(ShadowsOptimization, _super);
  84179. function ShadowsOptimization() {
  84180. return _super !== null && _super.apply(this, arguments) || this;
  84181. }
  84182. /**
  84183. * Gets a string describing the action executed by the current optimization
  84184. * @return description string
  84185. */
  84186. ShadowsOptimization.prototype.getDescription = function () {
  84187. return "Turning shadows on/off";
  84188. };
  84189. /**
  84190. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  84191. * @param scene defines the current scene where to apply this optimization
  84192. * @param optimizer defines the current optimizer
  84193. * @returns true if everything that can be done was applied
  84194. */
  84195. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  84196. scene.shadowsEnabled = optimizer.isInImprovementMode;
  84197. return true;
  84198. };
  84199. ;
  84200. return ShadowsOptimization;
  84201. }(SceneOptimization));
  84202. BABYLON.ShadowsOptimization = ShadowsOptimization;
  84203. /**
  84204. * Defines an optimization used to turn post-processes off
  84205. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  84206. */
  84207. var PostProcessesOptimization = /** @class */ (function (_super) {
  84208. __extends(PostProcessesOptimization, _super);
  84209. function PostProcessesOptimization() {
  84210. return _super !== null && _super.apply(this, arguments) || this;
  84211. }
  84212. /**
  84213. * Gets a string describing the action executed by the current optimization
  84214. * @return description string
  84215. */
  84216. PostProcessesOptimization.prototype.getDescription = function () {
  84217. return "Turning post-processes on/off";
  84218. };
  84219. /**
  84220. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  84221. * @param scene defines the current scene where to apply this optimization
  84222. * @param optimizer defines the current optimizer
  84223. * @returns true if everything that can be done was applied
  84224. */
  84225. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  84226. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  84227. return true;
  84228. };
  84229. ;
  84230. return PostProcessesOptimization;
  84231. }(SceneOptimization));
  84232. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  84233. /**
  84234. * Defines an optimization used to turn lens flares off
  84235. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  84236. */
  84237. var LensFlaresOptimization = /** @class */ (function (_super) {
  84238. __extends(LensFlaresOptimization, _super);
  84239. function LensFlaresOptimization() {
  84240. return _super !== null && _super.apply(this, arguments) || this;
  84241. }
  84242. /**
  84243. * Gets a string describing the action executed by the current optimization
  84244. * @return description string
  84245. */
  84246. LensFlaresOptimization.prototype.getDescription = function () {
  84247. return "Turning lens flares on/off";
  84248. };
  84249. /**
  84250. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  84251. * @param scene defines the current scene where to apply this optimization
  84252. * @param optimizer defines the current optimizer
  84253. * @returns true if everything that can be done was applied
  84254. */
  84255. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  84256. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  84257. return true;
  84258. };
  84259. ;
  84260. return LensFlaresOptimization;
  84261. }(SceneOptimization));
  84262. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  84263. /**
  84264. * Defines an optimization based on user defined callback.
  84265. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  84266. */
  84267. var CustomOptimization = /** @class */ (function (_super) {
  84268. __extends(CustomOptimization, _super);
  84269. function CustomOptimization() {
  84270. return _super !== null && _super.apply(this, arguments) || this;
  84271. }
  84272. /**
  84273. * Gets a string describing the action executed by the current optimization
  84274. * @returns description string
  84275. */
  84276. CustomOptimization.prototype.getDescription = function () {
  84277. if (this.onGetDescription) {
  84278. return this.onGetDescription();
  84279. }
  84280. return "Running user defined callback";
  84281. };
  84282. /**
  84283. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  84284. * @param scene defines the current scene where to apply this optimization
  84285. * @param optimizer defines the current optimizer
  84286. * @returns true if everything that can be done was applied
  84287. */
  84288. CustomOptimization.prototype.apply = function (scene, optimizer) {
  84289. if (this.onApply) {
  84290. return this.onApply(scene, optimizer);
  84291. }
  84292. return true;
  84293. };
  84294. ;
  84295. return CustomOptimization;
  84296. }(SceneOptimization));
  84297. BABYLON.CustomOptimization = CustomOptimization;
  84298. /**
  84299. * Defines an optimization used to turn particles off
  84300. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  84301. */
  84302. var ParticlesOptimization = /** @class */ (function (_super) {
  84303. __extends(ParticlesOptimization, _super);
  84304. function ParticlesOptimization() {
  84305. return _super !== null && _super.apply(this, arguments) || this;
  84306. }
  84307. /**
  84308. * Gets a string describing the action executed by the current optimization
  84309. * @return description string
  84310. */
  84311. ParticlesOptimization.prototype.getDescription = function () {
  84312. return "Turning particles on/off";
  84313. };
  84314. /**
  84315. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  84316. * @param scene defines the current scene where to apply this optimization
  84317. * @param optimizer defines the current optimizer
  84318. * @returns true if everything that can be done was applied
  84319. */
  84320. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  84321. scene.particlesEnabled = optimizer.isInImprovementMode;
  84322. return true;
  84323. };
  84324. ;
  84325. return ParticlesOptimization;
  84326. }(SceneOptimization));
  84327. BABYLON.ParticlesOptimization = ParticlesOptimization;
  84328. /**
  84329. * Defines an optimization used to turn render targets off
  84330. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  84331. */
  84332. var RenderTargetsOptimization = /** @class */ (function (_super) {
  84333. __extends(RenderTargetsOptimization, _super);
  84334. function RenderTargetsOptimization() {
  84335. return _super !== null && _super.apply(this, arguments) || this;
  84336. }
  84337. /**
  84338. * Gets a string describing the action executed by the current optimization
  84339. * @return description string
  84340. */
  84341. RenderTargetsOptimization.prototype.getDescription = function () {
  84342. return "Turning render targets off";
  84343. };
  84344. /**
  84345. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  84346. * @param scene defines the current scene where to apply this optimization
  84347. * @param optimizer defines the current optimizer
  84348. * @returns true if everything that can be done was applied
  84349. */
  84350. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  84351. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  84352. return true;
  84353. };
  84354. ;
  84355. return RenderTargetsOptimization;
  84356. }(SceneOptimization));
  84357. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  84358. /**
  84359. * Defines an optimization used to merge meshes with compatible materials
  84360. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  84361. */
  84362. var MergeMeshesOptimization = /** @class */ (function (_super) {
  84363. __extends(MergeMeshesOptimization, _super);
  84364. function MergeMeshesOptimization() {
  84365. var _this = _super !== null && _super.apply(this, arguments) || this;
  84366. _this._canBeMerged = function (abstractMesh) {
  84367. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  84368. return false;
  84369. }
  84370. var mesh = abstractMesh;
  84371. if (!mesh.isVisible || !mesh.isEnabled()) {
  84372. return false;
  84373. }
  84374. if (mesh.instances.length > 0) {
  84375. return false;
  84376. }
  84377. if (mesh.skeleton || mesh.hasLODLevels) {
  84378. return false;
  84379. }
  84380. if (mesh.parent) {
  84381. return false;
  84382. }
  84383. return true;
  84384. };
  84385. return _this;
  84386. }
  84387. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  84388. /**
  84389. * Gets or sets a boolean which defines if optimization octree has to be updated
  84390. */
  84391. get: function () {
  84392. return MergeMeshesOptimization._UpdateSelectionTree;
  84393. },
  84394. /**
  84395. * Gets or sets a boolean which defines if optimization octree has to be updated
  84396. */
  84397. set: function (value) {
  84398. MergeMeshesOptimization._UpdateSelectionTree = value;
  84399. },
  84400. enumerable: true,
  84401. configurable: true
  84402. });
  84403. /**
  84404. * Gets a string describing the action executed by the current optimization
  84405. * @return description string
  84406. */
  84407. MergeMeshesOptimization.prototype.getDescription = function () {
  84408. return "Merging similar meshes together";
  84409. };
  84410. /**
  84411. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  84412. * @param scene defines the current scene where to apply this optimization
  84413. * @param optimizer defines the current optimizer
  84414. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  84415. * @returns true if everything that can be done was applied
  84416. */
  84417. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  84418. var globalPool = scene.meshes.slice(0);
  84419. var globalLength = globalPool.length;
  84420. for (var index = 0; index < globalLength; index++) {
  84421. var currentPool = new Array();
  84422. var current = globalPool[index];
  84423. // Checks
  84424. if (!this._canBeMerged(current)) {
  84425. continue;
  84426. }
  84427. currentPool.push(current);
  84428. // Find compatible meshes
  84429. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  84430. var otherMesh = globalPool[subIndex];
  84431. if (!this._canBeMerged(otherMesh)) {
  84432. continue;
  84433. }
  84434. if (otherMesh.material !== current.material) {
  84435. continue;
  84436. }
  84437. if (otherMesh.checkCollisions !== current.checkCollisions) {
  84438. continue;
  84439. }
  84440. currentPool.push(otherMesh);
  84441. globalLength--;
  84442. globalPool.splice(subIndex, 1);
  84443. subIndex--;
  84444. }
  84445. if (currentPool.length < 2) {
  84446. continue;
  84447. }
  84448. // Merge meshes
  84449. BABYLON.Mesh.MergeMeshes(currentPool);
  84450. }
  84451. if (updateSelectionTree != undefined) {
  84452. if (updateSelectionTree) {
  84453. scene.createOrUpdateSelectionOctree();
  84454. }
  84455. }
  84456. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  84457. scene.createOrUpdateSelectionOctree();
  84458. }
  84459. return true;
  84460. };
  84461. ;
  84462. MergeMeshesOptimization._UpdateSelectionTree = false;
  84463. return MergeMeshesOptimization;
  84464. }(SceneOptimization));
  84465. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  84466. /**
  84467. * Defines a list of options used by SceneOptimizer
  84468. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  84469. */
  84470. var SceneOptimizerOptions = /** @class */ (function () {
  84471. /**
  84472. * Creates a new list of options used by SceneOptimizer
  84473. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  84474. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  84475. */
  84476. function SceneOptimizerOptions(
  84477. /**
  84478. * Defines the target frame rate to reach (60 by default)
  84479. */
  84480. targetFrameRate,
  84481. /**
  84482. * Defines the interval between two checkes (2000ms by default)
  84483. */
  84484. trackerDuration) {
  84485. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  84486. if (trackerDuration === void 0) { trackerDuration = 2000; }
  84487. this.targetFrameRate = targetFrameRate;
  84488. this.trackerDuration = trackerDuration;
  84489. /**
  84490. * Gets the list of optimizations to apply
  84491. */
  84492. this.optimizations = new Array();
  84493. }
  84494. /**
  84495. * Add a new optimization
  84496. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  84497. * @returns the current SceneOptimizerOptions
  84498. */
  84499. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  84500. this.optimizations.push(optimization);
  84501. return this;
  84502. };
  84503. /**
  84504. * Add a new custom optimization
  84505. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  84506. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  84507. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  84508. * @returns the current SceneOptimizerOptions
  84509. */
  84510. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  84511. if (priority === void 0) { priority = 0; }
  84512. var optimization = new CustomOptimization(priority);
  84513. optimization.onApply = onApply;
  84514. optimization.onGetDescription = onGetDescription;
  84515. this.optimizations.push(optimization);
  84516. return this;
  84517. };
  84518. /**
  84519. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  84520. * @param targetFrameRate defines the target frame rate (60 by default)
  84521. * @returns a SceneOptimizerOptions object
  84522. */
  84523. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  84524. var result = new SceneOptimizerOptions(targetFrameRate);
  84525. var priority = 0;
  84526. result.addOptimization(new MergeMeshesOptimization(priority));
  84527. result.addOptimization(new ShadowsOptimization(priority));
  84528. result.addOptimization(new LensFlaresOptimization(priority));
  84529. // Next priority
  84530. priority++;
  84531. result.addOptimization(new PostProcessesOptimization(priority));
  84532. result.addOptimization(new ParticlesOptimization(priority));
  84533. // Next priority
  84534. priority++;
  84535. result.addOptimization(new TextureOptimization(priority, 1024));
  84536. return result;
  84537. };
  84538. /**
  84539. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  84540. * @param targetFrameRate defines the target frame rate (60 by default)
  84541. * @returns a SceneOptimizerOptions object
  84542. */
  84543. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  84544. var result = new SceneOptimizerOptions(targetFrameRate);
  84545. var priority = 0;
  84546. result.addOptimization(new MergeMeshesOptimization(priority));
  84547. result.addOptimization(new ShadowsOptimization(priority));
  84548. result.addOptimization(new LensFlaresOptimization(priority));
  84549. // Next priority
  84550. priority++;
  84551. result.addOptimization(new PostProcessesOptimization(priority));
  84552. result.addOptimization(new ParticlesOptimization(priority));
  84553. // Next priority
  84554. priority++;
  84555. result.addOptimization(new TextureOptimization(priority, 512));
  84556. // Next priority
  84557. priority++;
  84558. result.addOptimization(new RenderTargetsOptimization(priority));
  84559. // Next priority
  84560. priority++;
  84561. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  84562. return result;
  84563. };
  84564. /**
  84565. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  84566. * @param targetFrameRate defines the target frame rate (60 by default)
  84567. * @returns a SceneOptimizerOptions object
  84568. */
  84569. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  84570. var result = new SceneOptimizerOptions(targetFrameRate);
  84571. var priority = 0;
  84572. result.addOptimization(new MergeMeshesOptimization(priority));
  84573. result.addOptimization(new ShadowsOptimization(priority));
  84574. result.addOptimization(new LensFlaresOptimization(priority));
  84575. // Next priority
  84576. priority++;
  84577. result.addOptimization(new PostProcessesOptimization(priority));
  84578. result.addOptimization(new ParticlesOptimization(priority));
  84579. // Next priority
  84580. priority++;
  84581. result.addOptimization(new TextureOptimization(priority, 256));
  84582. // Next priority
  84583. priority++;
  84584. result.addOptimization(new RenderTargetsOptimization(priority));
  84585. // Next priority
  84586. priority++;
  84587. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  84588. return result;
  84589. };
  84590. return SceneOptimizerOptions;
  84591. }());
  84592. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  84593. /**
  84594. * Class used to run optimizations in order to reach a target frame rate
  84595. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  84596. */
  84597. var SceneOptimizer = /** @class */ (function () {
  84598. /**
  84599. * Creates a new SceneOptimizer
  84600. * @param scene defines the scene to work on
  84601. * @param options defines the options to use with the SceneOptimizer
  84602. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  84603. * @param improvementMode defines if the scene optimizer must run the maximum optimization while staying over a target frame instead of trying to reach the target framerate (false by default)
  84604. */
  84605. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  84606. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  84607. if (improvementMode === void 0) { improvementMode = false; }
  84608. var _this = this;
  84609. this._isRunning = false;
  84610. this._currentPriorityLevel = 0;
  84611. this._targetFrameRate = 60;
  84612. this._trackerDuration = 2000;
  84613. this._currentFrameRate = 0;
  84614. this._improvementMode = false;
  84615. /**
  84616. * Defines an observable called when the optimizer reaches the target frame rate
  84617. */
  84618. this.onSuccessObservable = new BABYLON.Observable();
  84619. /**
  84620. * Defines an observable called when the optimizer enables an optimization
  84621. */
  84622. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  84623. /**
  84624. * Defines an observable called when the optimizer is not able to reach the target frame rate
  84625. */
  84626. this.onFailureObservable = new BABYLON.Observable();
  84627. if (!options) {
  84628. this._options = new SceneOptimizerOptions();
  84629. }
  84630. else {
  84631. this._options = options;
  84632. }
  84633. if (this._options.targetFrameRate) {
  84634. this._targetFrameRate = this._options.targetFrameRate;
  84635. }
  84636. if (this._options.trackerDuration) {
  84637. this._trackerDuration = this._options.trackerDuration;
  84638. }
  84639. if (autoGeneratePriorities) {
  84640. var priority = 0;
  84641. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  84642. var optim = _a[_i];
  84643. optim.priority = priority++;
  84644. }
  84645. }
  84646. this._improvementMode = improvementMode;
  84647. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  84648. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  84649. _this._sceneDisposeObserver = null;
  84650. _this.dispose();
  84651. });
  84652. }
  84653. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  84654. /**
  84655. * Gets a boolean indicating if the optimizer is in improvement mode
  84656. */
  84657. get: function () {
  84658. return this._improvementMode;
  84659. },
  84660. enumerable: true,
  84661. configurable: true
  84662. });
  84663. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  84664. /**
  84665. * Gets the current priority level (0 at start)
  84666. */
  84667. get: function () {
  84668. return this._currentPriorityLevel;
  84669. },
  84670. enumerable: true,
  84671. configurable: true
  84672. });
  84673. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  84674. /**
  84675. * Gets the current frame rate checked by the SceneOptimizer
  84676. */
  84677. get: function () {
  84678. return this._currentFrameRate;
  84679. },
  84680. enumerable: true,
  84681. configurable: true
  84682. });
  84683. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  84684. /**
  84685. * Gets or sets the current target frame rate (60 by default)
  84686. */
  84687. get: function () {
  84688. return this._targetFrameRate;
  84689. },
  84690. /**
  84691. * Gets or sets the current target frame rate (60 by default)
  84692. */
  84693. set: function (value) {
  84694. this._targetFrameRate = value;
  84695. },
  84696. enumerable: true,
  84697. configurable: true
  84698. });
  84699. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  84700. /**
  84701. * Gets or sets the current interval between two checks (every 2000ms by default)
  84702. */
  84703. get: function () {
  84704. return this._trackerDuration;
  84705. },
  84706. /**
  84707. * Gets or sets the current interval between two checks (every 2000ms by default)
  84708. */
  84709. set: function (value) {
  84710. this._trackerDuration = value;
  84711. },
  84712. enumerable: true,
  84713. configurable: true
  84714. });
  84715. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  84716. /**
  84717. * Gets the list of active optimizations
  84718. */
  84719. get: function () {
  84720. return this._options.optimizations;
  84721. },
  84722. enumerable: true,
  84723. configurable: true
  84724. });
  84725. /**
  84726. * Stops the current optimizer
  84727. */
  84728. SceneOptimizer.prototype.stop = function () {
  84729. this._isRunning = false;
  84730. };
  84731. /**
  84732. * Reset the optimizer to initial step (current priority level = 0)
  84733. */
  84734. SceneOptimizer.prototype.reset = function () {
  84735. this._currentPriorityLevel = 0;
  84736. };
  84737. /**
  84738. * Start the optimizer. By default it will try to reach a specific framerate
  84739. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  84740. */
  84741. SceneOptimizer.prototype.start = function () {
  84742. var _this = this;
  84743. if (this._isRunning) {
  84744. return;
  84745. }
  84746. this._isRunning = true;
  84747. // Let's wait for the scene to be ready before running our check
  84748. this._scene.executeWhenReady(function () {
  84749. setTimeout(function () {
  84750. _this._checkCurrentState();
  84751. }, _this._trackerDuration);
  84752. });
  84753. };
  84754. SceneOptimizer.prototype._checkCurrentState = function () {
  84755. var _this = this;
  84756. if (!this._isRunning) {
  84757. return;
  84758. }
  84759. var scene = this._scene;
  84760. var options = this._options;
  84761. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  84762. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  84763. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  84764. this._isRunning = false;
  84765. this.onSuccessObservable.notifyObservers(this);
  84766. return;
  84767. }
  84768. // Apply current level of optimizations
  84769. var allDone = true;
  84770. var noOptimizationApplied = true;
  84771. for (var index = 0; index < options.optimizations.length; index++) {
  84772. var optimization = options.optimizations[index];
  84773. if (optimization.priority === this._currentPriorityLevel) {
  84774. noOptimizationApplied = false;
  84775. allDone = allDone && optimization.apply(scene, this);
  84776. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  84777. }
  84778. }
  84779. // If no optimization was applied, this is a failure :(
  84780. if (noOptimizationApplied) {
  84781. this._isRunning = false;
  84782. this.onFailureObservable.notifyObservers(this);
  84783. return;
  84784. }
  84785. // If all optimizations were done, move to next level
  84786. if (allDone) {
  84787. this._currentPriorityLevel++;
  84788. }
  84789. // Let's the system running for a specific amount of time before checking FPS
  84790. scene.executeWhenReady(function () {
  84791. setTimeout(function () {
  84792. _this._checkCurrentState();
  84793. }, _this._trackerDuration);
  84794. });
  84795. };
  84796. /**
  84797. * Release all resources
  84798. */
  84799. SceneOptimizer.prototype.dispose = function () {
  84800. this.stop();
  84801. this.onSuccessObservable.clear();
  84802. this.onFailureObservable.clear();
  84803. this.onNewOptimizationAppliedObservable.clear();
  84804. if (this._sceneDisposeObserver) {
  84805. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  84806. }
  84807. };
  84808. /**
  84809. * Helper function to create a SceneOptimizer with one single line of code
  84810. * @param scene defines the scene to work on
  84811. * @param options defines the options to use with the SceneOptimizer
  84812. * @param onSuccess defines a callback to call on success
  84813. * @param onFailure defines a callback to call on failure
  84814. * @returns the new SceneOptimizer object
  84815. */
  84816. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  84817. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  84818. if (onSuccess) {
  84819. optimizer.onSuccessObservable.add(function () {
  84820. onSuccess();
  84821. });
  84822. }
  84823. if (onFailure) {
  84824. optimizer.onFailureObservable.add(function () {
  84825. onFailure();
  84826. });
  84827. }
  84828. optimizer.start();
  84829. return optimizer;
  84830. };
  84831. return SceneOptimizer;
  84832. }());
  84833. BABYLON.SceneOptimizer = SceneOptimizer;
  84834. })(BABYLON || (BABYLON = {}));
  84835. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  84836. var BABYLON;
  84837. (function (BABYLON) {
  84838. var OutlineRenderer = /** @class */ (function () {
  84839. function OutlineRenderer(scene) {
  84840. this.zOffset = 1;
  84841. this._scene = scene;
  84842. }
  84843. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  84844. var _this = this;
  84845. if (useOverlay === void 0) { useOverlay = false; }
  84846. var scene = this._scene;
  84847. var engine = this._scene.getEngine();
  84848. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  84849. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  84850. return;
  84851. }
  84852. var mesh = subMesh.getRenderingMesh();
  84853. var material = subMesh.getMaterial();
  84854. if (!material || !scene.activeCamera) {
  84855. return;
  84856. }
  84857. engine.enableEffect(this._effect);
  84858. // Logarithmic depth
  84859. if (material.useLogarithmicDepth) {
  84860. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  84861. }
  84862. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  84863. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  84864. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  84865. // Bones
  84866. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  84867. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  84868. }
  84869. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  84870. // Alpha test
  84871. if (material && material.needAlphaTesting()) {
  84872. var alphaTexture = material.getAlphaTestTexture();
  84873. if (alphaTexture) {
  84874. this._effect.setTexture("diffuseSampler", alphaTexture);
  84875. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  84876. }
  84877. }
  84878. engine.setZOffset(-this.zOffset);
  84879. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  84880. engine.setZOffset(0);
  84881. };
  84882. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  84883. var defines = [];
  84884. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  84885. var mesh = subMesh.getMesh();
  84886. var material = subMesh.getMaterial();
  84887. if (material) {
  84888. // Alpha test
  84889. if (material.needAlphaTesting()) {
  84890. defines.push("#define ALPHATEST");
  84891. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  84892. attribs.push(BABYLON.VertexBuffer.UVKind);
  84893. defines.push("#define UV1");
  84894. }
  84895. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  84896. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  84897. defines.push("#define UV2");
  84898. }
  84899. }
  84900. //Logarithmic depth
  84901. if (material.useLogarithmicDepth) {
  84902. defines.push("#define LOGARITHMICDEPTH");
  84903. }
  84904. }
  84905. // Bones
  84906. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  84907. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  84908. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  84909. if (mesh.numBoneInfluencers > 4) {
  84910. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  84911. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  84912. }
  84913. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  84914. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  84915. }
  84916. else {
  84917. defines.push("#define NUM_BONE_INFLUENCERS 0");
  84918. }
  84919. // Instances
  84920. if (useInstances) {
  84921. defines.push("#define INSTANCES");
  84922. attribs.push("world0");
  84923. attribs.push("world1");
  84924. attribs.push("world2");
  84925. attribs.push("world3");
  84926. }
  84927. // Get correct effect
  84928. var join = defines.join("\n");
  84929. if (this._cachedDefines !== join) {
  84930. this._cachedDefines = join;
  84931. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  84932. }
  84933. return this._effect.isReady();
  84934. };
  84935. return OutlineRenderer;
  84936. }());
  84937. BABYLON.OutlineRenderer = OutlineRenderer;
  84938. })(BABYLON || (BABYLON = {}));
  84939. //# sourceMappingURL=babylon.outlineRenderer.js.map
  84940. var BABYLON;
  84941. (function (BABYLON) {
  84942. var FaceAdjacencies = /** @class */ (function () {
  84943. function FaceAdjacencies() {
  84944. this.edges = new Array();
  84945. this.edgesConnectedCount = 0;
  84946. }
  84947. return FaceAdjacencies;
  84948. }());
  84949. var EdgesRenderer = /** @class */ (function () {
  84950. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  84951. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  84952. if (epsilon === void 0) { epsilon = 0.95; }
  84953. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  84954. this.edgesWidthScalerForOrthographic = 1000.0;
  84955. this.edgesWidthScalerForPerspective = 50.0;
  84956. this._linesPositions = new Array();
  84957. this._linesNormals = new Array();
  84958. this._linesIndices = new Array();
  84959. this._buffers = {};
  84960. this._checkVerticesInsteadOfIndices = false;
  84961. this._source = source;
  84962. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  84963. this._epsilon = epsilon;
  84964. this._prepareRessources();
  84965. this._generateEdgesLines();
  84966. }
  84967. EdgesRenderer.prototype._prepareRessources = function () {
  84968. if (this._lineShader) {
  84969. return;
  84970. }
  84971. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  84972. attributes: ["position", "normal"],
  84973. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  84974. });
  84975. this._lineShader.disableDepthWrite = true;
  84976. this._lineShader.backFaceCulling = false;
  84977. };
  84978. EdgesRenderer.prototype._rebuild = function () {
  84979. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  84980. if (buffer) {
  84981. buffer._rebuild();
  84982. }
  84983. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  84984. if (buffer) {
  84985. buffer._rebuild();
  84986. }
  84987. var scene = this._source.getScene();
  84988. var engine = scene.getEngine();
  84989. this._ib = engine.createIndexBuffer(this._linesIndices);
  84990. };
  84991. EdgesRenderer.prototype.dispose = function () {
  84992. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  84993. if (buffer) {
  84994. buffer.dispose();
  84995. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  84996. }
  84997. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  84998. if (buffer) {
  84999. buffer.dispose();
  85000. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  85001. }
  85002. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  85003. this._lineShader.dispose();
  85004. };
  85005. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  85006. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  85007. return 0;
  85008. }
  85009. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  85010. return 1;
  85011. }
  85012. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  85013. return 2;
  85014. }
  85015. return -1;
  85016. };
  85017. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  85018. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  85019. return 0;
  85020. }
  85021. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  85022. return 1;
  85023. }
  85024. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  85025. return 2;
  85026. }
  85027. return -1;
  85028. };
  85029. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  85030. var needToCreateLine;
  85031. if (edge === undefined) {
  85032. needToCreateLine = true;
  85033. }
  85034. else {
  85035. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  85036. needToCreateLine = dotProduct < this._epsilon;
  85037. }
  85038. if (needToCreateLine) {
  85039. var offset = this._linesPositions.length / 3;
  85040. var normal = p0.subtract(p1);
  85041. normal.normalize();
  85042. // Positions
  85043. this._linesPositions.push(p0.x);
  85044. this._linesPositions.push(p0.y);
  85045. this._linesPositions.push(p0.z);
  85046. this._linesPositions.push(p0.x);
  85047. this._linesPositions.push(p0.y);
  85048. this._linesPositions.push(p0.z);
  85049. this._linesPositions.push(p1.x);
  85050. this._linesPositions.push(p1.y);
  85051. this._linesPositions.push(p1.z);
  85052. this._linesPositions.push(p1.x);
  85053. this._linesPositions.push(p1.y);
  85054. this._linesPositions.push(p1.z);
  85055. // Normals
  85056. this._linesNormals.push(p1.x);
  85057. this._linesNormals.push(p1.y);
  85058. this._linesNormals.push(p1.z);
  85059. this._linesNormals.push(-1);
  85060. this._linesNormals.push(p1.x);
  85061. this._linesNormals.push(p1.y);
  85062. this._linesNormals.push(p1.z);
  85063. this._linesNormals.push(1);
  85064. this._linesNormals.push(p0.x);
  85065. this._linesNormals.push(p0.y);
  85066. this._linesNormals.push(p0.z);
  85067. this._linesNormals.push(-1);
  85068. this._linesNormals.push(p0.x);
  85069. this._linesNormals.push(p0.y);
  85070. this._linesNormals.push(p0.z);
  85071. this._linesNormals.push(1);
  85072. // Indices
  85073. this._linesIndices.push(offset);
  85074. this._linesIndices.push(offset + 1);
  85075. this._linesIndices.push(offset + 2);
  85076. this._linesIndices.push(offset);
  85077. this._linesIndices.push(offset + 2);
  85078. this._linesIndices.push(offset + 3);
  85079. }
  85080. };
  85081. EdgesRenderer.prototype._generateEdgesLines = function () {
  85082. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  85083. var indices = this._source.getIndices();
  85084. if (!indices || !positions) {
  85085. return;
  85086. }
  85087. // First let's find adjacencies
  85088. var adjacencies = new Array();
  85089. var faceNormals = new Array();
  85090. var index;
  85091. var faceAdjacencies;
  85092. // Prepare faces
  85093. for (index = 0; index < indices.length; index += 3) {
  85094. faceAdjacencies = new FaceAdjacencies();
  85095. var p0Index = indices[index];
  85096. var p1Index = indices[index + 1];
  85097. var p2Index = indices[index + 2];
  85098. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  85099. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  85100. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  85101. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  85102. faceNormal.normalize();
  85103. faceNormals.push(faceNormal);
  85104. adjacencies.push(faceAdjacencies);
  85105. }
  85106. // Scan
  85107. for (index = 0; index < adjacencies.length; index++) {
  85108. faceAdjacencies = adjacencies[index];
  85109. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  85110. var otherFaceAdjacencies = adjacencies[otherIndex];
  85111. if (faceAdjacencies.edgesConnectedCount === 3) {
  85112. break;
  85113. }
  85114. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  85115. continue;
  85116. }
  85117. var otherP0 = indices[otherIndex * 3];
  85118. var otherP1 = indices[otherIndex * 3 + 1];
  85119. var otherP2 = indices[otherIndex * 3 + 2];
  85120. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  85121. var otherEdgeIndex = 0;
  85122. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  85123. continue;
  85124. }
  85125. switch (edgeIndex) {
  85126. case 0:
  85127. if (this._checkVerticesInsteadOfIndices) {
  85128. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  85129. }
  85130. else {
  85131. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  85132. }
  85133. break;
  85134. case 1:
  85135. if (this._checkVerticesInsteadOfIndices) {
  85136. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  85137. }
  85138. else {
  85139. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  85140. }
  85141. break;
  85142. case 2:
  85143. if (this._checkVerticesInsteadOfIndices) {
  85144. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  85145. }
  85146. else {
  85147. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  85148. }
  85149. break;
  85150. }
  85151. if (otherEdgeIndex === -1) {
  85152. continue;
  85153. }
  85154. faceAdjacencies.edges[edgeIndex] = otherIndex;
  85155. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  85156. faceAdjacencies.edgesConnectedCount++;
  85157. otherFaceAdjacencies.edgesConnectedCount++;
  85158. if (faceAdjacencies.edgesConnectedCount === 3) {
  85159. break;
  85160. }
  85161. }
  85162. }
  85163. }
  85164. // Create lines
  85165. for (index = 0; index < adjacencies.length; index++) {
  85166. // We need a line when a face has no adjacency on a specific edge or if all the adjacencies has an angle greater than epsilon
  85167. var current = adjacencies[index];
  85168. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  85169. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  85170. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  85171. }
  85172. // Merge into a single mesh
  85173. var engine = this._source.getScene().getEngine();
  85174. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  85175. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  85176. this._ib = engine.createIndexBuffer(this._linesIndices);
  85177. this._indicesCount = this._linesIndices.length;
  85178. };
  85179. EdgesRenderer.prototype.render = function () {
  85180. var scene = this._source.getScene();
  85181. if (!this._lineShader.isReady() || !scene.activeCamera) {
  85182. return;
  85183. }
  85184. var engine = scene.getEngine();
  85185. this._lineShader._preBind();
  85186. // VBOs
  85187. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  85188. scene.resetCachedMaterial();
  85189. this._lineShader.setColor4("color", this._source.edgesColor);
  85190. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  85191. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  85192. }
  85193. else {
  85194. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  85195. }
  85196. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  85197. this._lineShader.bind(this._source.getWorldMatrix());
  85198. // Draw order
  85199. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  85200. this._lineShader.unbind();
  85201. engine.setDepthWrite(true);
  85202. };
  85203. return EdgesRenderer;
  85204. }());
  85205. BABYLON.EdgesRenderer = EdgesRenderer;
  85206. })(BABYLON || (BABYLON = {}));
  85207. //# sourceMappingURL=babylon.edgesRenderer.js.map
  85208. var __assign = (this && this.__assign) || Object.assign || function(t) {
  85209. for (var s, i = 1, n = arguments.length; i < n; i++) {
  85210. s = arguments[i];
  85211. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  85212. t[p] = s[p];
  85213. }
  85214. return t;
  85215. };
  85216. var BABYLON;
  85217. (function (BABYLON) {
  85218. /**
  85219. * The effect layer Helps adding post process effect blended with the main pass.
  85220. *
  85221. * This can be for instance use to generate glow or higlight effects on the scene.
  85222. *
  85223. * The effect layer class can not be used directly and is intented to inherited from to be
  85224. * customized per effects.
  85225. */
  85226. var EffectLayer = /** @class */ (function () {
  85227. /**
  85228. * Instantiates a new effect Layer and references it in the scene.
  85229. * @param name The name of the layer
  85230. * @param scene The scene to use the layer in
  85231. */
  85232. function EffectLayer(
  85233. /** The Friendly of the effect in the scene */
  85234. name, scene) {
  85235. this.name = name;
  85236. this._vertexBuffers = {};
  85237. this._maxSize = 0;
  85238. this._mainTextureDesiredSize = { width: 0, height: 0 };
  85239. this._shouldRender = true;
  85240. this._postProcesses = [];
  85241. this._textures = [];
  85242. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  85243. /**
  85244. * The clear color of the texture used to generate the glow map.
  85245. */
  85246. this.neutralColor = new BABYLON.Color4();
  85247. /**
  85248. * Specifies wether the highlight layer is enabled or not.
  85249. */
  85250. this.isEnabled = true;
  85251. /**
  85252. * An event triggered when the effect layer has been disposed.
  85253. */
  85254. this.onDisposeObservable = new BABYLON.Observable();
  85255. /**
  85256. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  85257. */
  85258. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  85259. /**
  85260. * An event triggered when the generated texture is being merged in the scene.
  85261. */
  85262. this.onBeforeComposeObservable = new BABYLON.Observable();
  85263. /**
  85264. * An event triggered when the generated texture has been merged in the scene.
  85265. */
  85266. this.onAfterComposeObservable = new BABYLON.Observable();
  85267. /**
  85268. * An event triggered when the efffect layer changes its size.
  85269. */
  85270. this.onSizeChangedObservable = new BABYLON.Observable();
  85271. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  85272. this._engine = scene.getEngine();
  85273. this._maxSize = this._engine.getCaps().maxTextureSize;
  85274. this._scene.effectLayers.push(this);
  85275. // Generate Buffers
  85276. this._generateIndexBuffer();
  85277. this._genrateVertexBuffer();
  85278. }
  85279. Object.defineProperty(EffectLayer.prototype, "camera", {
  85280. /**
  85281. * Gets the camera attached to the layer.
  85282. */
  85283. get: function () {
  85284. return this._effectLayerOptions.camera;
  85285. },
  85286. enumerable: true,
  85287. configurable: true
  85288. });
  85289. /**
  85290. * Initializes the effect layer with the required options.
  85291. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  85292. */
  85293. EffectLayer.prototype._init = function (options) {
  85294. // Adapt options
  85295. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  85296. this._setMainTextureSize();
  85297. this._createMainTexture();
  85298. this._createTextureAndPostProcesses();
  85299. this._mergeEffect = this._createMergeEffect();
  85300. };
  85301. /**
  85302. * Generates the index buffer of the full screen quad blending to the main canvas.
  85303. */
  85304. EffectLayer.prototype._generateIndexBuffer = function () {
  85305. // Indices
  85306. var indices = [];
  85307. indices.push(0);
  85308. indices.push(1);
  85309. indices.push(2);
  85310. indices.push(0);
  85311. indices.push(2);
  85312. indices.push(3);
  85313. this._indexBuffer = this._engine.createIndexBuffer(indices);
  85314. };
  85315. /**
  85316. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  85317. */
  85318. EffectLayer.prototype._genrateVertexBuffer = function () {
  85319. // VBO
  85320. var vertices = [];
  85321. vertices.push(1, 1);
  85322. vertices.push(-1, 1);
  85323. vertices.push(-1, -1);
  85324. vertices.push(1, -1);
  85325. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  85326. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  85327. };
  85328. /**
  85329. * Sets the main texture desired size which is the closest power of two
  85330. * of the engine canvas size.
  85331. */
  85332. EffectLayer.prototype._setMainTextureSize = function () {
  85333. if (this._effectLayerOptions.mainTextureFixedSize) {
  85334. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  85335. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  85336. }
  85337. else {
  85338. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  85339. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  85340. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  85341. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  85342. }
  85343. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  85344. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  85345. };
  85346. /**
  85347. * Creates the main texture for the effect layer.
  85348. */
  85349. EffectLayer.prototype._createMainTexture = function () {
  85350. var _this = this;
  85351. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  85352. width: this._mainTextureDesiredSize.width,
  85353. height: this._mainTextureDesiredSize.height
  85354. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  85355. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  85356. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  85357. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  85358. this._mainTexture.anisotropicFilteringLevel = 1;
  85359. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  85360. this._mainTexture.renderParticles = false;
  85361. this._mainTexture.renderList = null;
  85362. this._mainTexture.ignoreCameraViewport = true;
  85363. // Custom render function
  85364. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  85365. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  85366. var index;
  85367. var engine = _this._scene.getEngine();
  85368. if (depthOnlySubMeshes.length) {
  85369. engine.setColorWrite(false);
  85370. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  85371. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  85372. }
  85373. engine.setColorWrite(true);
  85374. }
  85375. for (index = 0; index < opaqueSubMeshes.length; index++) {
  85376. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  85377. }
  85378. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  85379. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  85380. }
  85381. for (index = 0; index < transparentSubMeshes.length; index++) {
  85382. _this._renderSubMesh(transparentSubMeshes.data[index]);
  85383. }
  85384. };
  85385. this._mainTexture.onClearObservable.add(function (engine) {
  85386. engine.clear(_this.neutralColor, true, true, true);
  85387. });
  85388. };
  85389. /**
  85390. * Checks for the readiness of the element composing the layer.
  85391. * @param subMesh the mesh to check for
  85392. * @param useInstances specify wether or not to use instances to render the mesh
  85393. * @param emissiveTexture the associated emissive texture used to generate the glow
  85394. * @return true if ready otherwise, false
  85395. */
  85396. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  85397. var material = subMesh.getMaterial();
  85398. if (!material) {
  85399. return false;
  85400. }
  85401. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  85402. return false;
  85403. }
  85404. var defines = [];
  85405. var attribs = [BABYLON.VertexBuffer.PositionKind];
  85406. var mesh = subMesh.getMesh();
  85407. var uv1 = false;
  85408. var uv2 = false;
  85409. // Alpha test
  85410. if (material && material.needAlphaTesting()) {
  85411. var alphaTexture = material.getAlphaTestTexture();
  85412. if (alphaTexture) {
  85413. defines.push("#define ALPHATEST");
  85414. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  85415. alphaTexture.coordinatesIndex === 1) {
  85416. defines.push("#define DIFFUSEUV2");
  85417. uv2 = true;
  85418. }
  85419. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  85420. defines.push("#define DIFFUSEUV1");
  85421. uv1 = true;
  85422. }
  85423. }
  85424. }
  85425. // Emissive
  85426. if (emissiveTexture) {
  85427. defines.push("#define EMISSIVE");
  85428. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  85429. emissiveTexture.coordinatesIndex === 1) {
  85430. defines.push("#define EMISSIVEUV2");
  85431. uv2 = true;
  85432. }
  85433. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  85434. defines.push("#define EMISSIVEUV1");
  85435. uv1 = true;
  85436. }
  85437. }
  85438. if (uv1) {
  85439. attribs.push(BABYLON.VertexBuffer.UVKind);
  85440. defines.push("#define UV1");
  85441. }
  85442. if (uv2) {
  85443. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  85444. defines.push("#define UV2");
  85445. }
  85446. // Bones
  85447. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  85448. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  85449. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  85450. if (mesh.numBoneInfluencers > 4) {
  85451. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  85452. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  85453. }
  85454. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  85455. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  85456. }
  85457. else {
  85458. defines.push("#define NUM_BONE_INFLUENCERS 0");
  85459. }
  85460. // Instances
  85461. if (useInstances) {
  85462. defines.push("#define INSTANCES");
  85463. attribs.push("world0");
  85464. attribs.push("world1");
  85465. attribs.push("world2");
  85466. attribs.push("world3");
  85467. }
  85468. // Get correct effect
  85469. var join = defines.join("\n");
  85470. if (this._cachedDefines !== join) {
  85471. this._cachedDefines = join;
  85472. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix"], ["diffuseSampler", "emissiveSampler"], join);
  85473. }
  85474. return this._effectLayerMapGenerationEffect.isReady();
  85475. };
  85476. /**
  85477. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  85478. */
  85479. EffectLayer.prototype.render = function () {
  85480. var currentEffect = this._mergeEffect;
  85481. // Check
  85482. if (!currentEffect.isReady())
  85483. return;
  85484. for (var i = 0; i < this._postProcesses.length; i++) {
  85485. if (!this._postProcesses[i].isReady()) {
  85486. return;
  85487. }
  85488. }
  85489. var engine = this._scene.getEngine();
  85490. this.onBeforeComposeObservable.notifyObservers(this);
  85491. // Render
  85492. engine.enableEffect(currentEffect);
  85493. engine.setState(false);
  85494. // VBOs
  85495. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  85496. // Cache
  85497. var previousAlphaMode = engine.getAlphaMode();
  85498. // Go Blend.
  85499. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  85500. // Blends the map on the main canvas.
  85501. this._internalRender(currentEffect);
  85502. // Restore Alpha
  85503. engine.setAlphaMode(previousAlphaMode);
  85504. this.onAfterComposeObservable.notifyObservers(this);
  85505. // Handle size changes.
  85506. var size = this._mainTexture.getSize();
  85507. this._setMainTextureSize();
  85508. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  85509. // Recreate RTT and post processes on size change.
  85510. this.onSizeChangedObservable.notifyObservers(this);
  85511. this._disposeTextureAndPostProcesses();
  85512. this._createMainTexture();
  85513. this._createTextureAndPostProcesses();
  85514. }
  85515. };
  85516. /**
  85517. * Determine if a given mesh will be used in the current effect.
  85518. * @param mesh mesh to test
  85519. * @returns true if the mesh will be used
  85520. */
  85521. EffectLayer.prototype.hasMesh = function (mesh) {
  85522. return true;
  85523. };
  85524. /**
  85525. * Returns true if the layer contains information to display, otherwise false.
  85526. * @returns true if the glow layer should be rendered
  85527. */
  85528. EffectLayer.prototype.shouldRender = function () {
  85529. return this.isEnabled && this._shouldRender;
  85530. };
  85531. /**
  85532. * Returns true if the mesh should render, otherwise false.
  85533. * @param mesh The mesh to render
  85534. * @returns true if it should render otherwise false
  85535. */
  85536. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  85537. return true;
  85538. };
  85539. /**
  85540. * Returns true if the mesh should render, otherwise false.
  85541. * @param mesh The mesh to render
  85542. * @returns true if it should render otherwise false
  85543. */
  85544. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  85545. return true;
  85546. };
  85547. /**
  85548. * Renders the submesh passed in parameter to the generation map.
  85549. */
  85550. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  85551. var _this = this;
  85552. if (!this.shouldRender()) {
  85553. return;
  85554. }
  85555. var material = subMesh.getMaterial();
  85556. var mesh = subMesh.getRenderingMesh();
  85557. var scene = this._scene;
  85558. var engine = scene.getEngine();
  85559. if (!material) {
  85560. return;
  85561. }
  85562. // Do not block in blend mode.
  85563. if (material.needAlphaBlendingForMesh(mesh)) {
  85564. return;
  85565. }
  85566. // Culling
  85567. engine.setState(material.backFaceCulling);
  85568. // Managing instances
  85569. var batch = mesh._getInstancesRenderList(subMesh._id);
  85570. if (batch.mustReturn) {
  85571. return;
  85572. }
  85573. // Early Exit per mesh
  85574. if (!this._shouldRenderMesh(mesh)) {
  85575. return;
  85576. }
  85577. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  85578. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  85579. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  85580. engine.enableEffect(this._effectLayerMapGenerationEffect);
  85581. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  85582. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  85583. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  85584. // Alpha test
  85585. if (material && material.needAlphaTesting()) {
  85586. var alphaTexture = material.getAlphaTestTexture();
  85587. if (alphaTexture) {
  85588. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  85589. var textureMatrix = alphaTexture.getTextureMatrix();
  85590. if (textureMatrix) {
  85591. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  85592. }
  85593. }
  85594. }
  85595. // Glow emissive only
  85596. if (this._emissiveTextureAndColor.texture) {
  85597. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  85598. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  85599. }
  85600. // Bones
  85601. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  85602. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  85603. }
  85604. // Draw
  85605. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  85606. }
  85607. else {
  85608. // Need to reset refresh rate of the shadowMap
  85609. this._mainTexture.resetRefreshCounter();
  85610. }
  85611. };
  85612. /**
  85613. * Rebuild the required buffers.
  85614. * @ignore Internal use only.
  85615. */
  85616. EffectLayer.prototype._rebuild = function () {
  85617. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  85618. if (vb) {
  85619. vb._rebuild();
  85620. }
  85621. this._generateIndexBuffer();
  85622. };
  85623. /**
  85624. * Dispose only the render target textures and post process.
  85625. */
  85626. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  85627. this._mainTexture.dispose();
  85628. for (var i = 0; i < this._postProcesses.length; i++) {
  85629. if (this._postProcesses[i]) {
  85630. this._postProcesses[i].dispose();
  85631. }
  85632. }
  85633. this._postProcesses = [];
  85634. for (var i = 0; i < this._textures.length; i++) {
  85635. if (this._textures[i]) {
  85636. this._textures[i].dispose();
  85637. }
  85638. }
  85639. this._textures = [];
  85640. };
  85641. /**
  85642. * Dispose the highlight layer and free resources.
  85643. */
  85644. EffectLayer.prototype.dispose = function () {
  85645. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  85646. if (vertexBuffer) {
  85647. vertexBuffer.dispose();
  85648. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  85649. }
  85650. if (this._indexBuffer) {
  85651. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  85652. this._indexBuffer = null;
  85653. }
  85654. // Clean textures and post processes
  85655. this._disposeTextureAndPostProcesses();
  85656. // Remove from scene
  85657. var index = this._scene.effectLayers.indexOf(this, 0);
  85658. if (index > -1) {
  85659. this._scene.effectLayers.splice(index, 1);
  85660. }
  85661. // Callback
  85662. this.onDisposeObservable.notifyObservers(this);
  85663. this.onDisposeObservable.clear();
  85664. this.onBeforeRenderMainTextureObservable.clear();
  85665. this.onBeforeComposeObservable.clear();
  85666. this.onAfterComposeObservable.clear();
  85667. this.onSizeChangedObservable.clear();
  85668. };
  85669. return EffectLayer;
  85670. }());
  85671. BABYLON.EffectLayer = EffectLayer;
  85672. })(BABYLON || (BABYLON = {}));
  85673. //# sourceMappingURL=babylon.effectLayer.js.map
  85674. var BABYLON;
  85675. (function (BABYLON) {
  85676. /**
  85677. * Special Glow Blur post process only blurring the alpha channel
  85678. * It enforces keeping the most luminous color in the color channel.
  85679. */
  85680. var GlowBlurPostProcess = /** @class */ (function (_super) {
  85681. __extends(GlowBlurPostProcess, _super);
  85682. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  85683. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  85684. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  85685. _this.direction = direction;
  85686. _this.kernel = kernel;
  85687. _this.onApplyObservable.add(function (effect) {
  85688. effect.setFloat2("screenSize", _this.width, _this.height);
  85689. effect.setVector2("direction", _this.direction);
  85690. effect.setFloat("blurWidth", _this.kernel);
  85691. });
  85692. return _this;
  85693. }
  85694. return GlowBlurPostProcess;
  85695. }(BABYLON.PostProcess));
  85696. /**
  85697. * The highlight layer Helps adding a glow effect around a mesh.
  85698. *
  85699. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  85700. * glowy meshes to your scene.
  85701. *
  85702. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  85703. */
  85704. var HighlightLayer = /** @class */ (function (_super) {
  85705. __extends(HighlightLayer, _super);
  85706. /**
  85707. * Instantiates a new highlight Layer and references it to the scene..
  85708. * @param name The name of the layer
  85709. * @param scene The scene to use the layer in
  85710. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  85711. */
  85712. function HighlightLayer(name, scene, options) {
  85713. var _this = _super.call(this, name, scene) || this;
  85714. _this.name = name;
  85715. /**
  85716. * Specifies whether or not the inner glow is ACTIVE in the layer.
  85717. */
  85718. _this.innerGlow = true;
  85719. /**
  85720. * Specifies whether or not the outer glow is ACTIVE in the layer.
  85721. */
  85722. _this.outerGlow = true;
  85723. /**
  85724. * An event triggered when the highlight layer is being blurred.
  85725. */
  85726. _this.onBeforeBlurObservable = new BABYLON.Observable();
  85727. /**
  85728. * An event triggered when the highlight layer has been blurred.
  85729. */
  85730. _this.onAfterBlurObservable = new BABYLON.Observable();
  85731. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  85732. _this._meshes = {};
  85733. _this._excludedMeshes = {};
  85734. _this.neutralColor = HighlightLayer.NeutralColor;
  85735. // Warn on stencil
  85736. if (!_this._engine.isStencilEnable) {
  85737. BABYLON.Tools.Warn("Rendering the Highlight Layer requires the stencil to be active on the canvas. var engine = new BABYLON.Engine(canvas, antialias, { stencil: true }");
  85738. }
  85739. // Adapt options
  85740. _this._options = __assign({ mainTextureRatio: 0.5, blurTextureSizeRatio: 0.5, blurHorizontalSize: 1.0, blurVerticalSize: 1.0, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  85741. // Initialize the layer
  85742. _this._init({
  85743. alphaBlendingMode: _this._options.alphaBlendingMode,
  85744. camera: _this._options.camera,
  85745. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  85746. mainTextureRatio: _this._options.mainTextureRatio
  85747. });
  85748. // Do not render as long as no meshes have been added
  85749. _this._shouldRender = false;
  85750. return _this;
  85751. }
  85752. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  85753. /**
  85754. * Gets the horizontal size of the blur.
  85755. */
  85756. get: function () {
  85757. return this._horizontalBlurPostprocess.kernel;
  85758. },
  85759. /**
  85760. * Specifies the horizontal size of the blur.
  85761. */
  85762. set: function (value) {
  85763. this._horizontalBlurPostprocess.kernel = value;
  85764. },
  85765. enumerable: true,
  85766. configurable: true
  85767. });
  85768. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  85769. /**
  85770. * Gets the vertical size of the blur.
  85771. */
  85772. get: function () {
  85773. return this._verticalBlurPostprocess.kernel;
  85774. },
  85775. /**
  85776. * Specifies the vertical size of the blur.
  85777. */
  85778. set: function (value) {
  85779. this._verticalBlurPostprocess.kernel = value;
  85780. },
  85781. enumerable: true,
  85782. configurable: true
  85783. });
  85784. /**
  85785. * Get the effect name of the layer.
  85786. * @return The effect name
  85787. */
  85788. HighlightLayer.prototype.getEffectName = function () {
  85789. return HighlightLayer.EffectName;
  85790. };
  85791. /**
  85792. * Create the merge effect. This is the shader use to blit the information back
  85793. * to the main canvas at the end of the scene rendering.
  85794. */
  85795. HighlightLayer.prototype._createMergeEffect = function () {
  85796. // Effect
  85797. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  85798. };
  85799. /**
  85800. * Creates the render target textures and post processes used in the highlight layer.
  85801. */
  85802. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  85803. var _this = this;
  85804. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  85805. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  85806. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  85807. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  85808. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  85809. width: blurTextureWidth,
  85810. height: blurTextureHeight
  85811. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  85812. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  85813. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  85814. this._blurTexture.anisotropicFilteringLevel = 16;
  85815. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  85816. this._blurTexture.renderParticles = false;
  85817. this._blurTexture.ignoreCameraViewport = true;
  85818. this._textures = [this._blurTexture];
  85819. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  85820. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  85821. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  85822. effect.setTexture("textureSampler", _this._mainTexture);
  85823. });
  85824. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  85825. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  85826. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  85827. });
  85828. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  85829. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  85830. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  85831. });
  85832. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  85833. }
  85834. else {
  85835. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  85836. width: blurTextureWidth,
  85837. height: blurTextureHeight
  85838. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  85839. this._horizontalBlurPostprocess.width = blurTextureWidth;
  85840. this._horizontalBlurPostprocess.height = blurTextureHeight;
  85841. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  85842. effect.setTexture("textureSampler", _this._mainTexture);
  85843. });
  85844. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  85845. width: blurTextureWidth,
  85846. height: blurTextureHeight
  85847. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  85848. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  85849. }
  85850. this._mainTexture.onAfterUnbindObservable.add(function () {
  85851. _this.onBeforeBlurObservable.notifyObservers(_this);
  85852. var internalTexture = _this._blurTexture.getInternalTexture();
  85853. if (internalTexture) {
  85854. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  85855. }
  85856. _this.onAfterBlurObservable.notifyObservers(_this);
  85857. });
  85858. // Prevent autoClear.
  85859. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  85860. };
  85861. /**
  85862. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  85863. */
  85864. HighlightLayer.prototype.needStencil = function () {
  85865. return true;
  85866. };
  85867. /**
  85868. * Checks for the readiness of the element composing the layer.
  85869. * @param subMesh the mesh to check for
  85870. * @param useInstances specify wether or not to use instances to render the mesh
  85871. * @param emissiveTexture the associated emissive texture used to generate the glow
  85872. * @return true if ready otherwise, false
  85873. */
  85874. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  85875. var material = subMesh.getMaterial();
  85876. var mesh = subMesh.getRenderingMesh();
  85877. if (!material || !mesh || !this._meshes) {
  85878. return false;
  85879. }
  85880. var emissiveTexture = null;
  85881. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  85882. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  85883. emissiveTexture = material.emissiveTexture;
  85884. }
  85885. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  85886. };
  85887. /**
  85888. * Implementation specific of rendering the generating effect on the main canvas.
  85889. * @param effect The effect used to render through
  85890. */
  85891. HighlightLayer.prototype._internalRender = function (effect) {
  85892. // Texture
  85893. effect.setTexture("textureSampler", this._blurTexture);
  85894. // Cache
  85895. var engine = this._engine;
  85896. var previousStencilBuffer = engine.getStencilBuffer();
  85897. var previousStencilFunction = engine.getStencilFunction();
  85898. var previousStencilMask = engine.getStencilMask();
  85899. var previousStencilOperationPass = engine.getStencilOperationPass();
  85900. var previousStencilOperationFail = engine.getStencilOperationFail();
  85901. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  85902. var previousStencilReference = engine.getStencilFunctionReference();
  85903. // Stencil operations
  85904. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  85905. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  85906. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  85907. // Draw order
  85908. engine.setStencilMask(0x00);
  85909. engine.setStencilBuffer(true);
  85910. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  85911. // 2 passes inner outer
  85912. if (this.outerGlow) {
  85913. effect.setFloat("offset", 0);
  85914. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  85915. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  85916. }
  85917. if (this.innerGlow) {
  85918. effect.setFloat("offset", 1);
  85919. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  85920. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  85921. }
  85922. // Restore Cache
  85923. engine.setStencilFunction(previousStencilFunction);
  85924. engine.setStencilMask(previousStencilMask);
  85925. engine.setStencilBuffer(previousStencilBuffer);
  85926. engine.setStencilOperationPass(previousStencilOperationPass);
  85927. engine.setStencilOperationFail(previousStencilOperationFail);
  85928. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  85929. engine.setStencilFunctionReference(previousStencilReference);
  85930. };
  85931. /**
  85932. * Returns true if the layer contains information to display, otherwise false.
  85933. */
  85934. HighlightLayer.prototype.shouldRender = function () {
  85935. if (_super.prototype.shouldRender.call(this)) {
  85936. return this._meshes ? true : false;
  85937. }
  85938. return false;
  85939. };
  85940. /**
  85941. * Returns true if the mesh should render, otherwise false.
  85942. * @param mesh The mesh to render
  85943. * @returns true if it should render otherwise false
  85944. */
  85945. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  85946. // Excluded Mesh
  85947. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  85948. return false;
  85949. }
  85950. ;
  85951. return true;
  85952. };
  85953. /**
  85954. * Sets the required values for both the emissive texture and and the main color.
  85955. */
  85956. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  85957. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  85958. if (highlightLayerMesh) {
  85959. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  85960. }
  85961. else {
  85962. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  85963. }
  85964. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  85965. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  85966. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  85967. }
  85968. else {
  85969. this._emissiveTextureAndColor.texture = null;
  85970. }
  85971. };
  85972. /**
  85973. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  85974. * @param mesh The mesh to exclude from the highlight layer
  85975. */
  85976. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  85977. if (!this._excludedMeshes) {
  85978. return;
  85979. }
  85980. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  85981. if (!meshExcluded) {
  85982. this._excludedMeshes[mesh.uniqueId] = {
  85983. mesh: mesh,
  85984. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  85985. mesh.getEngine().setStencilBuffer(false);
  85986. }),
  85987. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  85988. mesh.getEngine().setStencilBuffer(true);
  85989. }),
  85990. };
  85991. }
  85992. };
  85993. /**
  85994. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  85995. * @param mesh The mesh to highlight
  85996. */
  85997. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  85998. if (!this._excludedMeshes) {
  85999. return;
  86000. }
  86001. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  86002. if (meshExcluded) {
  86003. if (meshExcluded.beforeRender) {
  86004. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  86005. }
  86006. if (meshExcluded.afterRender) {
  86007. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  86008. }
  86009. }
  86010. this._excludedMeshes[mesh.uniqueId] = null;
  86011. };
  86012. /**
  86013. * Determine if a given mesh will be highlighted by the current HighlightLayer
  86014. * @param mesh mesh to test
  86015. * @returns true if the mesh will be highlighted by the current HighlightLayer
  86016. */
  86017. HighlightLayer.prototype.hasMesh = function (mesh) {
  86018. if (!this._meshes) {
  86019. return false;
  86020. }
  86021. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  86022. };
  86023. /**
  86024. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  86025. * @param mesh The mesh to highlight
  86026. * @param color The color of the highlight
  86027. * @param glowEmissiveOnly Extract the glow from the emissive texture
  86028. */
  86029. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  86030. var _this = this;
  86031. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  86032. if (!this._meshes) {
  86033. return;
  86034. }
  86035. var meshHighlight = this._meshes[mesh.uniqueId];
  86036. if (meshHighlight) {
  86037. meshHighlight.color = color;
  86038. }
  86039. else {
  86040. this._meshes[mesh.uniqueId] = {
  86041. mesh: mesh,
  86042. color: color,
  86043. // Lambda required for capture due to Observable this context
  86044. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  86045. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  86046. _this._defaultStencilReference(mesh);
  86047. }
  86048. else {
  86049. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  86050. }
  86051. }),
  86052. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  86053. glowEmissiveOnly: glowEmissiveOnly
  86054. };
  86055. }
  86056. this._shouldRender = true;
  86057. };
  86058. /**
  86059. * Remove a mesh from the highlight layer in order to make it stop glowing.
  86060. * @param mesh The mesh to highlight
  86061. */
  86062. HighlightLayer.prototype.removeMesh = function (mesh) {
  86063. if (!this._meshes) {
  86064. return;
  86065. }
  86066. var meshHighlight = this._meshes[mesh.uniqueId];
  86067. if (meshHighlight) {
  86068. if (meshHighlight.observerHighlight) {
  86069. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  86070. }
  86071. if (meshHighlight.observerDefault) {
  86072. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  86073. }
  86074. delete this._meshes[mesh.uniqueId];
  86075. }
  86076. this._shouldRender = false;
  86077. for (var meshHighlightToCheck in this._meshes) {
  86078. if (this._meshes[meshHighlightToCheck]) {
  86079. this._shouldRender = true;
  86080. break;
  86081. }
  86082. }
  86083. };
  86084. /**
  86085. * Force the stencil to the normal expected value for none glowing parts
  86086. */
  86087. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  86088. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  86089. };
  86090. /**
  86091. * Free any resources and references associated to a mesh.
  86092. * Internal use
  86093. * @param mesh The mesh to free.
  86094. */
  86095. HighlightLayer.prototype._disposeMesh = function (mesh) {
  86096. this.removeMesh(mesh);
  86097. this.removeExcludedMesh(mesh);
  86098. };
  86099. /**
  86100. * Dispose the highlight layer and free resources.
  86101. */
  86102. HighlightLayer.prototype.dispose = function () {
  86103. if (this._meshes) {
  86104. // Clean mesh references
  86105. for (var id in this._meshes) {
  86106. var meshHighlight = this._meshes[id];
  86107. if (meshHighlight && meshHighlight.mesh) {
  86108. if (meshHighlight.observerHighlight) {
  86109. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  86110. }
  86111. if (meshHighlight.observerDefault) {
  86112. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  86113. }
  86114. }
  86115. }
  86116. this._meshes = null;
  86117. }
  86118. if (this._excludedMeshes) {
  86119. for (var id in this._excludedMeshes) {
  86120. var meshHighlight = this._excludedMeshes[id];
  86121. if (meshHighlight) {
  86122. if (meshHighlight.beforeRender) {
  86123. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  86124. }
  86125. if (meshHighlight.afterRender) {
  86126. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  86127. }
  86128. }
  86129. }
  86130. this._excludedMeshes = null;
  86131. }
  86132. _super.prototype.dispose.call(this);
  86133. };
  86134. /**
  86135. * Effect Name of the highlight layer.
  86136. */
  86137. HighlightLayer.EffectName = "HighlightLayer";
  86138. /**
  86139. * The neutral color used during the preparation of the glow effect.
  86140. * This is black by default as the blend operation is a blend operation.
  86141. */
  86142. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  86143. /**
  86144. * Stencil value used for glowing meshes.
  86145. */
  86146. HighlightLayer.GlowingMeshStencilReference = 0x02;
  86147. /**
  86148. * Stencil value used for the other meshes in the scene.
  86149. */
  86150. HighlightLayer.NormalMeshStencilReference = 0x01;
  86151. return HighlightLayer;
  86152. }(BABYLON.EffectLayer));
  86153. BABYLON.HighlightLayer = HighlightLayer;
  86154. })(BABYLON || (BABYLON = {}));
  86155. //# sourceMappingURL=babylon.highlightLayer.js.map
  86156. var BABYLON;
  86157. (function (BABYLON) {
  86158. /**
  86159. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  86160. *
  86161. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  86162. * glowy meshes to your scene.
  86163. *
  86164. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  86165. */
  86166. var GlowLayer = /** @class */ (function (_super) {
  86167. __extends(GlowLayer, _super);
  86168. /**
  86169. * Instantiates a new glow Layer and references it to the scene.
  86170. * @param name The name of the layer
  86171. * @param scene The scene to use the layer in
  86172. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  86173. */
  86174. function GlowLayer(name, scene, options) {
  86175. var _this = _super.call(this, name, scene) || this;
  86176. _this.name = name;
  86177. _this._intensity = 1.0;
  86178. _this._includedOnlyMeshes = [];
  86179. _this._excludedMeshes = [];
  86180. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  86181. // Adapt options
  86182. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1 }, options);
  86183. // Initialize the layer
  86184. _this._init({
  86185. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  86186. camera: _this._options.camera,
  86187. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  86188. mainTextureRatio: _this._options.mainTextureRatio
  86189. });
  86190. return _this;
  86191. }
  86192. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  86193. /**
  86194. * Gets the kernel size of the blur.
  86195. */
  86196. get: function () {
  86197. return this._horizontalBlurPostprocess1.kernel;
  86198. },
  86199. /**
  86200. * Sets the kernel size of the blur.
  86201. */
  86202. set: function (value) {
  86203. this._horizontalBlurPostprocess1.kernel = value;
  86204. this._verticalBlurPostprocess1.kernel = value;
  86205. this._horizontalBlurPostprocess2.kernel = value;
  86206. this._verticalBlurPostprocess2.kernel = value;
  86207. },
  86208. enumerable: true,
  86209. configurable: true
  86210. });
  86211. Object.defineProperty(GlowLayer.prototype, "intensity", {
  86212. /**
  86213. * Gets the glow intensity.
  86214. */
  86215. get: function () {
  86216. return this._intensity;
  86217. },
  86218. /**
  86219. * Sets the glow intensity.
  86220. */
  86221. set: function (value) {
  86222. this._intensity = value;
  86223. },
  86224. enumerable: true,
  86225. configurable: true
  86226. });
  86227. /**
  86228. * Get the effect name of the layer.
  86229. * @return The effect name
  86230. */
  86231. GlowLayer.prototype.getEffectName = function () {
  86232. return GlowLayer.EffectName;
  86233. };
  86234. /**
  86235. * Create the merge effect. This is the shader use to blit the information back
  86236. * to the main canvas at the end of the scene rendering.
  86237. */
  86238. GlowLayer.prototype._createMergeEffect = function () {
  86239. // Effect
  86240. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  86241. };
  86242. /**
  86243. * Creates the render target textures and post processes used in the glow layer.
  86244. */
  86245. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  86246. var _this = this;
  86247. var blurTextureWidth = this._mainTextureDesiredSize.width;
  86248. var blurTextureHeight = this._mainTextureDesiredSize.height;
  86249. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  86250. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  86251. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  86252. width: blurTextureWidth,
  86253. height: blurTextureHeight
  86254. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  86255. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86256. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86257. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  86258. this._blurTexture1.renderParticles = false;
  86259. this._blurTexture1.ignoreCameraViewport = true;
  86260. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  86261. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  86262. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  86263. width: blurTextureWidth2,
  86264. height: blurTextureHeight2
  86265. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  86266. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86267. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86268. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  86269. this._blurTexture2.renderParticles = false;
  86270. this._blurTexture2.ignoreCameraViewport = true;
  86271. this._textures = [this._blurTexture1, this._blurTexture2];
  86272. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  86273. width: blurTextureWidth,
  86274. height: blurTextureHeight
  86275. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  86276. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  86277. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  86278. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  86279. effect.setTexture("textureSampler", _this._mainTexture);
  86280. });
  86281. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  86282. width: blurTextureWidth,
  86283. height: blurTextureHeight
  86284. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  86285. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  86286. width: blurTextureWidth2,
  86287. height: blurTextureHeight2
  86288. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  86289. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  86290. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  86291. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  86292. effect.setTexture("textureSampler", _this._blurTexture1);
  86293. });
  86294. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  86295. width: blurTextureWidth2,
  86296. height: blurTextureHeight2
  86297. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  86298. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  86299. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  86300. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  86301. this._mainTexture.samples = this._options.mainTextureSamples;
  86302. this._mainTexture.onAfterUnbindObservable.add(function () {
  86303. var internalTexture = _this._blurTexture1.getInternalTexture();
  86304. if (internalTexture) {
  86305. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  86306. internalTexture = _this._blurTexture2.getInternalTexture();
  86307. if (internalTexture) {
  86308. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  86309. }
  86310. }
  86311. });
  86312. // Prevent autoClear.
  86313. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  86314. };
  86315. /**
  86316. * Checks for the readiness of the element composing the layer.
  86317. * @param subMesh the mesh to check for
  86318. * @param useInstances specify wether or not to use instances to render the mesh
  86319. * @param emissiveTexture the associated emissive texture used to generate the glow
  86320. * @return true if ready otherwise, false
  86321. */
  86322. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  86323. var material = subMesh.getMaterial();
  86324. var mesh = subMesh.getRenderingMesh();
  86325. if (!material || !mesh) {
  86326. return false;
  86327. }
  86328. var emissiveTexture = material.emissiveTexture;
  86329. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  86330. };
  86331. /**
  86332. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  86333. */
  86334. GlowLayer.prototype.needStencil = function () {
  86335. return false;
  86336. };
  86337. /**
  86338. * Implementation specific of rendering the generating effect on the main canvas.
  86339. * @param effect The effect used to render through
  86340. */
  86341. GlowLayer.prototype._internalRender = function (effect) {
  86342. // Texture
  86343. effect.setTexture("textureSampler", this._blurTexture1);
  86344. effect.setTexture("textureSampler2", this._blurTexture2);
  86345. effect.setFloat("offset", this._intensity);
  86346. // Cache
  86347. var engine = this._engine;
  86348. var previousStencilBuffer = engine.getStencilBuffer();
  86349. // Draw order
  86350. engine.setStencilBuffer(false);
  86351. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  86352. // Draw order
  86353. engine.setStencilBuffer(previousStencilBuffer);
  86354. };
  86355. /**
  86356. * Sets the required values for both the emissive texture and and the main color.
  86357. */
  86358. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  86359. var textureLevel = 1.0;
  86360. if (this.customEmissiveTextureSelector) {
  86361. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  86362. }
  86363. else {
  86364. if (material) {
  86365. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  86366. if (this._emissiveTextureAndColor.texture) {
  86367. textureLevel = this._emissiveTextureAndColor.texture.level;
  86368. }
  86369. }
  86370. else {
  86371. this._emissiveTextureAndColor.texture = null;
  86372. }
  86373. }
  86374. if (this.customEmissiveColorSelector) {
  86375. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  86376. }
  86377. else {
  86378. if (material.emissiveColor) {
  86379. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  86380. }
  86381. else {
  86382. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  86383. }
  86384. }
  86385. };
  86386. /**
  86387. * Returns true if the mesh should render, otherwise false.
  86388. * @param mesh The mesh to render
  86389. * @returns true if it should render otherwise false
  86390. */
  86391. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  86392. return this.hasMesh(mesh);
  86393. };
  86394. /**
  86395. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  86396. * @param mesh The mesh to exclude from the glow layer
  86397. */
  86398. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  86399. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  86400. this._excludedMeshes.push(mesh.uniqueId);
  86401. }
  86402. };
  86403. /**
  86404. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  86405. * @param mesh The mesh to remove
  86406. */
  86407. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  86408. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  86409. if (index !== -1) {
  86410. this._excludedMeshes.splice(index, 1);
  86411. }
  86412. };
  86413. /**
  86414. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  86415. * @param mesh The mesh to include in the glow layer
  86416. */
  86417. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  86418. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  86419. this._includedOnlyMeshes.push(mesh.uniqueId);
  86420. }
  86421. };
  86422. /**
  86423. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  86424. * @param mesh The mesh to remove
  86425. */
  86426. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  86427. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  86428. if (index !== -1) {
  86429. this._includedOnlyMeshes.splice(index, 1);
  86430. }
  86431. };
  86432. /**
  86433. * Determine if a given mesh will be used in the glow layer
  86434. * @param mesh The mesh to test
  86435. * @returns true if the mesh will be highlighted by the current glow layer
  86436. */
  86437. GlowLayer.prototype.hasMesh = function (mesh) {
  86438. // Included Mesh
  86439. if (this._includedOnlyMeshes.length) {
  86440. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  86441. }
  86442. ;
  86443. // Excluded Mesh
  86444. if (this._excludedMeshes.length) {
  86445. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  86446. }
  86447. ;
  86448. return true;
  86449. };
  86450. /**
  86451. * Free any resources and references associated to a mesh.
  86452. * Internal use
  86453. * @param mesh The mesh to free.
  86454. */
  86455. GlowLayer.prototype._disposeMesh = function (mesh) {
  86456. this.removeIncludedOnlyMesh(mesh);
  86457. this.removeExcludedMesh(mesh);
  86458. };
  86459. /**
  86460. * Effect Name of the layer.
  86461. */
  86462. GlowLayer.EffectName = "GlowLayer";
  86463. /**
  86464. * The default blur kernel size used for the glow.
  86465. */
  86466. GlowLayer.DefaultBlurKernelSize = 32;
  86467. /**
  86468. * The default texture size ratio used for the glow.
  86469. */
  86470. GlowLayer.DefaultTextureRatio = 0.5;
  86471. return GlowLayer;
  86472. }(BABYLON.EffectLayer));
  86473. BABYLON.GlowLayer = GlowLayer;
  86474. })(BABYLON || (BABYLON = {}));
  86475. //# sourceMappingURL=babylon.glowLayer.js.map
  86476. var BABYLON;
  86477. (function (BABYLON) {
  86478. /**
  86479. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  86480. */
  86481. var AssetTaskState;
  86482. (function (AssetTaskState) {
  86483. /**
  86484. * Initialization
  86485. */
  86486. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  86487. /**
  86488. * Running
  86489. */
  86490. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  86491. /**
  86492. * Done
  86493. */
  86494. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  86495. /**
  86496. * Error
  86497. */
  86498. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  86499. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  86500. /**
  86501. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  86502. */
  86503. var AbstractAssetTask = /** @class */ (function () {
  86504. /**
  86505. * Creates a new {BABYLON.AssetsManager}
  86506. * @param name defines the name of the task
  86507. */
  86508. function AbstractAssetTask(
  86509. /**
  86510. * Task name
  86511. */ name) {
  86512. this.name = name;
  86513. this._isCompleted = false;
  86514. this._taskState = AssetTaskState.INIT;
  86515. }
  86516. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  86517. /**
  86518. * Get if the task is completed
  86519. */
  86520. get: function () {
  86521. return this._isCompleted;
  86522. },
  86523. enumerable: true,
  86524. configurable: true
  86525. });
  86526. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  86527. /**
  86528. * Gets the current state of the task
  86529. */
  86530. get: function () {
  86531. return this._taskState;
  86532. },
  86533. enumerable: true,
  86534. configurable: true
  86535. });
  86536. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  86537. /**
  86538. * Gets the current error object (if task is in error)
  86539. */
  86540. get: function () {
  86541. return this._errorObject;
  86542. },
  86543. enumerable: true,
  86544. configurable: true
  86545. });
  86546. /**
  86547. * Internal only
  86548. * @ignore
  86549. */
  86550. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  86551. if (this._errorObject) {
  86552. return;
  86553. }
  86554. this._errorObject = {
  86555. message: message,
  86556. exception: exception
  86557. };
  86558. };
  86559. /**
  86560. * Execute the current task
  86561. * @param scene defines the scene where you want your assets to be loaded
  86562. * @param onSuccess is a callback called when the task is successfully executed
  86563. * @param onError is a callback called if an error occurs
  86564. */
  86565. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  86566. var _this = this;
  86567. this._taskState = AssetTaskState.RUNNING;
  86568. this.runTask(scene, function () {
  86569. _this.onDoneCallback(onSuccess, onError);
  86570. }, function (msg, exception) {
  86571. _this.onErrorCallback(onError, msg, exception);
  86572. });
  86573. };
  86574. /**
  86575. * Execute the current task
  86576. * @param scene defines the scene where you want your assets to be loaded
  86577. * @param onSuccess is a callback called when the task is successfully executed
  86578. * @param onError is a callback called if an error occurs
  86579. */
  86580. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  86581. throw new Error("runTask is not implemented");
  86582. };
  86583. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  86584. this._taskState = AssetTaskState.ERROR;
  86585. this._errorObject = {
  86586. message: message,
  86587. exception: exception
  86588. };
  86589. if (this.onError) {
  86590. this.onError(this, message, exception);
  86591. }
  86592. onError();
  86593. };
  86594. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  86595. try {
  86596. this._taskState = AssetTaskState.DONE;
  86597. this._isCompleted = true;
  86598. if (this.onSuccess) {
  86599. this.onSuccess(this);
  86600. }
  86601. onSuccess();
  86602. }
  86603. catch (e) {
  86604. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  86605. }
  86606. };
  86607. return AbstractAssetTask;
  86608. }());
  86609. BABYLON.AbstractAssetTask = AbstractAssetTask;
  86610. /**
  86611. * Class used to share progress information about assets loading
  86612. */
  86613. var AssetsProgressEvent = /** @class */ (function () {
  86614. /**
  86615. * Creates a {BABYLON.AssetsProgressEvent}
  86616. * @param remainingCount defines the number of remaining tasks to process
  86617. * @param totalCount defines the total number of tasks
  86618. * @param task defines the task that was just processed
  86619. */
  86620. function AssetsProgressEvent(remainingCount, totalCount, task) {
  86621. this.remainingCount = remainingCount;
  86622. this.totalCount = totalCount;
  86623. this.task = task;
  86624. }
  86625. return AssetsProgressEvent;
  86626. }());
  86627. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  86628. /**
  86629. * Define a task used by {BABYLON.AssetsManager} to load meshes
  86630. */
  86631. var MeshAssetTask = /** @class */ (function (_super) {
  86632. __extends(MeshAssetTask, _super);
  86633. /**
  86634. * Creates a new {BABYLON.MeshAssetTask}
  86635. * @param name defines the name of the task
  86636. * @param meshesNames defines the list of mesh's names you want to load
  86637. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  86638. * @param sceneFilename defines the filename of the scene to load from
  86639. */
  86640. function MeshAssetTask(
  86641. /**
  86642. * Defines the name of the task
  86643. */
  86644. name,
  86645. /**
  86646. * Defines the list of mesh's names you want to load
  86647. */
  86648. meshesNames,
  86649. /**
  86650. * Defines the root url to use as a base to load your meshes and associated resources
  86651. */
  86652. rootUrl,
  86653. /**
  86654. * Defines the filename of the scene to load from
  86655. */
  86656. sceneFilename) {
  86657. var _this = _super.call(this, name) || this;
  86658. _this.name = name;
  86659. _this.meshesNames = meshesNames;
  86660. _this.rootUrl = rootUrl;
  86661. _this.sceneFilename = sceneFilename;
  86662. return _this;
  86663. }
  86664. /**
  86665. * Execute the current task
  86666. * @param scene defines the scene where you want your assets to be loaded
  86667. * @param onSuccess is a callback called when the task is successfully executed
  86668. * @param onError is a callback called if an error occurs
  86669. */
  86670. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  86671. var _this = this;
  86672. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  86673. _this.loadedMeshes = meshes;
  86674. _this.loadedParticleSystems = particleSystems;
  86675. _this.loadedSkeletons = skeletons;
  86676. onSuccess();
  86677. }, null, function (scene, message, exception) {
  86678. onError(message, exception);
  86679. });
  86680. };
  86681. return MeshAssetTask;
  86682. }(AbstractAssetTask));
  86683. BABYLON.MeshAssetTask = MeshAssetTask;
  86684. /**
  86685. * Define a task used by {BABYLON.AssetsManager} to load text content
  86686. */
  86687. var TextFileAssetTask = /** @class */ (function (_super) {
  86688. __extends(TextFileAssetTask, _super);
  86689. /**
  86690. * Creates a new TextFileAssetTask object
  86691. * @param name defines the name of the task
  86692. * @param url defines the location of the file to load
  86693. */
  86694. function TextFileAssetTask(
  86695. /**
  86696. * Defines the name of the task
  86697. */
  86698. name,
  86699. /**
  86700. * Defines the location of the file to load
  86701. */
  86702. url) {
  86703. var _this = _super.call(this, name) || this;
  86704. _this.name = name;
  86705. _this.url = url;
  86706. return _this;
  86707. }
  86708. /**
  86709. * Execute the current task
  86710. * @param scene defines the scene where you want your assets to be loaded
  86711. * @param onSuccess is a callback called when the task is successfully executed
  86712. * @param onError is a callback called if an error occurs
  86713. */
  86714. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  86715. var _this = this;
  86716. scene._loadFile(this.url, function (data) {
  86717. _this.text = data;
  86718. onSuccess();
  86719. }, undefined, false, false, function (request, exception) {
  86720. if (request) {
  86721. onError(request.status + " " + request.statusText, exception);
  86722. }
  86723. });
  86724. };
  86725. return TextFileAssetTask;
  86726. }(AbstractAssetTask));
  86727. BABYLON.TextFileAssetTask = TextFileAssetTask;
  86728. /**
  86729. * Define a task used by {BABYLON.AssetsManager} to load binary data
  86730. */
  86731. var BinaryFileAssetTask = /** @class */ (function (_super) {
  86732. __extends(BinaryFileAssetTask, _super);
  86733. /**
  86734. * Creates a new BinaryFileAssetTask object
  86735. * @param name defines the name of the new task
  86736. * @param url defines the location of the file to load
  86737. */
  86738. function BinaryFileAssetTask(
  86739. /**
  86740. * Defines the name of the task
  86741. */
  86742. name,
  86743. /**
  86744. * Defines the location of the file to load
  86745. */
  86746. url) {
  86747. var _this = _super.call(this, name) || this;
  86748. _this.name = name;
  86749. _this.url = url;
  86750. return _this;
  86751. }
  86752. /**
  86753. * Execute the current task
  86754. * @param scene defines the scene where you want your assets to be loaded
  86755. * @param onSuccess is a callback called when the task is successfully executed
  86756. * @param onError is a callback called if an error occurs
  86757. */
  86758. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  86759. var _this = this;
  86760. scene._loadFile(this.url, function (data) {
  86761. _this.data = data;
  86762. onSuccess();
  86763. }, undefined, true, true, function (request, exception) {
  86764. if (request) {
  86765. onError(request.status + " " + request.statusText, exception);
  86766. }
  86767. });
  86768. };
  86769. return BinaryFileAssetTask;
  86770. }(AbstractAssetTask));
  86771. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  86772. /**
  86773. * Define a task used by {BABYLON.AssetsManager} to load images
  86774. */
  86775. var ImageAssetTask = /** @class */ (function (_super) {
  86776. __extends(ImageAssetTask, _super);
  86777. /**
  86778. * Creates a new ImageAssetTask
  86779. * @param name defines the name of the task
  86780. * @param url defines the location of the image to load
  86781. */
  86782. function ImageAssetTask(
  86783. /**
  86784. * Defines the name of the task
  86785. */
  86786. name,
  86787. /**
  86788. * Defines the location of the image to load
  86789. */
  86790. url) {
  86791. var _this = _super.call(this, name) || this;
  86792. _this.name = name;
  86793. _this.url = url;
  86794. return _this;
  86795. }
  86796. /**
  86797. * Execute the current task
  86798. * @param scene defines the scene where you want your assets to be loaded
  86799. * @param onSuccess is a callback called when the task is successfully executed
  86800. * @param onError is a callback called if an error occurs
  86801. */
  86802. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  86803. var _this = this;
  86804. var img = new Image();
  86805. BABYLON.Tools.SetCorsBehavior(this.url, img);
  86806. img.onload = function () {
  86807. _this.image = img;
  86808. onSuccess();
  86809. };
  86810. img.onerror = function (err) {
  86811. onError("Error loading image", err);
  86812. };
  86813. img.src = this.url;
  86814. };
  86815. return ImageAssetTask;
  86816. }(AbstractAssetTask));
  86817. BABYLON.ImageAssetTask = ImageAssetTask;
  86818. /**
  86819. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  86820. */
  86821. var TextureAssetTask = /** @class */ (function (_super) {
  86822. __extends(TextureAssetTask, _super);
  86823. /**
  86824. * Creates a new TextureAssetTask object
  86825. * @param name defines the name of the task
  86826. * @param url defines the location of the file to load
  86827. * @param noMipmap defines if mipmap should not be generated (default is false)
  86828. * @param invertY defines if texture must be inverted on Y axis (default is false)
  86829. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  86830. */
  86831. function TextureAssetTask(
  86832. /**
  86833. * Defines the name of the task
  86834. */
  86835. name,
  86836. /**
  86837. * Defines the location of the file to load
  86838. */
  86839. url,
  86840. /**
  86841. * Defines if mipmap should not be generated (default is false)
  86842. */
  86843. noMipmap,
  86844. /**
  86845. * Defines if texture must be inverted on Y axis (default is false)
  86846. */
  86847. invertY,
  86848. /**
  86849. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  86850. */
  86851. samplingMode) {
  86852. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  86853. var _this = _super.call(this, name) || this;
  86854. _this.name = name;
  86855. _this.url = url;
  86856. _this.noMipmap = noMipmap;
  86857. _this.invertY = invertY;
  86858. _this.samplingMode = samplingMode;
  86859. return _this;
  86860. }
  86861. /**
  86862. * Execute the current task
  86863. * @param scene defines the scene where you want your assets to be loaded
  86864. * @param onSuccess is a callback called when the task is successfully executed
  86865. * @param onError is a callback called if an error occurs
  86866. */
  86867. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  86868. var onload = function () {
  86869. onSuccess();
  86870. };
  86871. var onerror = function (message, exception) {
  86872. onError(message, exception);
  86873. };
  86874. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  86875. };
  86876. return TextureAssetTask;
  86877. }(AbstractAssetTask));
  86878. BABYLON.TextureAssetTask = TextureAssetTask;
  86879. /**
  86880. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  86881. */
  86882. var CubeTextureAssetTask = /** @class */ (function (_super) {
  86883. __extends(CubeTextureAssetTask, _super);
  86884. /**
  86885. * Creates a new CubeTextureAssetTask
  86886. * @param name defines the name of the task
  86887. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  86888. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  86889. * @param noMipmap defines if mipmaps should not be generated (default is false)
  86890. * @param files defines the explicit list of files (undefined by default)
  86891. */
  86892. function CubeTextureAssetTask(
  86893. /**
  86894. * Defines the name of the task
  86895. */
  86896. name,
  86897. /**
  86898. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  86899. */
  86900. url,
  86901. /**
  86902. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  86903. */
  86904. extensions,
  86905. /**
  86906. * Defines if mipmaps should not be generated (default is false)
  86907. */
  86908. noMipmap,
  86909. /**
  86910. * Defines the explicit list of files (undefined by default)
  86911. */
  86912. files) {
  86913. var _this = _super.call(this, name) || this;
  86914. _this.name = name;
  86915. _this.url = url;
  86916. _this.extensions = extensions;
  86917. _this.noMipmap = noMipmap;
  86918. _this.files = files;
  86919. return _this;
  86920. }
  86921. /**
  86922. * Execute the current task
  86923. * @param scene defines the scene where you want your assets to be loaded
  86924. * @param onSuccess is a callback called when the task is successfully executed
  86925. * @param onError is a callback called if an error occurs
  86926. */
  86927. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  86928. var onload = function () {
  86929. onSuccess();
  86930. };
  86931. var onerror = function (message, exception) {
  86932. onError(message, exception);
  86933. };
  86934. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  86935. };
  86936. return CubeTextureAssetTask;
  86937. }(AbstractAssetTask));
  86938. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  86939. /**
  86940. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  86941. */
  86942. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  86943. __extends(HDRCubeTextureAssetTask, _super);
  86944. /**
  86945. * Creates a new HDRCubeTextureAssetTask object
  86946. * @param name defines the name of the task
  86947. * @param url defines the location of the file to load
  86948. * @param size defines the desired size (the more it increases the longer the generation will be) If the size is omitted this implies you are using a preprocessed cubemap.
  86949. * @param noMipmap defines if mipmaps should not be generated (default is false)
  86950. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  86951. * @param useInGammaSpace specifies if the texture will be use in gamma or linear space (the PBR material requires those texture in linear space, but the standard material would require them in Gamma space) (default is false)
  86952. * @param usePMREMGenerator specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  86953. */
  86954. function HDRCubeTextureAssetTask(
  86955. /**
  86956. * Defines the name of the task
  86957. */
  86958. name,
  86959. /**
  86960. * Defines the location of the file to load
  86961. */
  86962. url,
  86963. /**
  86964. * Defines the desired size (the more it increases the longer the generation will be) If the size is omitted this implies you are using a preprocessed cubemap.
  86965. */
  86966. size,
  86967. /**
  86968. * Defines if mipmaps should not be generated (default is false)
  86969. */
  86970. noMipmap,
  86971. /**
  86972. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  86973. */
  86974. generateHarmonics,
  86975. /**
  86976. * Specifies if the texture will be use in gamma or linear space (the PBR material requires those texture in linear space, but the standard material would require them in Gamma space) (default is false)
  86977. */
  86978. useInGammaSpace,
  86979. /**
  86980. * Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  86981. */
  86982. usePMREMGenerator) {
  86983. if (noMipmap === void 0) { noMipmap = false; }
  86984. if (generateHarmonics === void 0) { generateHarmonics = true; }
  86985. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  86986. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  86987. var _this = _super.call(this, name) || this;
  86988. _this.name = name;
  86989. _this.url = url;
  86990. _this.size = size;
  86991. _this.noMipmap = noMipmap;
  86992. _this.generateHarmonics = generateHarmonics;
  86993. _this.useInGammaSpace = useInGammaSpace;
  86994. _this.usePMREMGenerator = usePMREMGenerator;
  86995. return _this;
  86996. }
  86997. /**
  86998. * Execute the current task
  86999. * @param scene defines the scene where you want your assets to be loaded
  87000. * @param onSuccess is a callback called when the task is successfully executed
  87001. * @param onError is a callback called if an error occurs
  87002. */
  87003. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  87004. var onload = function () {
  87005. onSuccess();
  87006. };
  87007. var onerror = function (message, exception) {
  87008. onError(message, exception);
  87009. };
  87010. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.useInGammaSpace, this.usePMREMGenerator, onload, onerror);
  87011. };
  87012. return HDRCubeTextureAssetTask;
  87013. }(AbstractAssetTask));
  87014. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  87015. /**
  87016. * This class can be used to easily import assets into a scene
  87017. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  87018. */
  87019. var AssetsManager = /** @class */ (function () {
  87020. /**
  87021. * Creates a new AssetsManager
  87022. * @param scene defines the scene to work on
  87023. */
  87024. function AssetsManager(scene) {
  87025. this._isLoading = false;
  87026. this._tasks = new Array();
  87027. this._waitingTasksCount = 0;
  87028. this._totalTasksCount = 0;
  87029. /**
  87030. * Observable called when all tasks are processed
  87031. */
  87032. this.onTaskSuccessObservable = new BABYLON.Observable();
  87033. /**
  87034. * Observable called when a task had an error
  87035. */
  87036. this.onTaskErrorObservable = new BABYLON.Observable();
  87037. /**
  87038. * Observable called when a task is successful
  87039. */
  87040. this.onTasksDoneObservable = new BABYLON.Observable();
  87041. /**
  87042. * Observable called when a task is done (whatever the result is)
  87043. */
  87044. this.onProgressObservable = new BABYLON.Observable();
  87045. /**
  87046. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  87047. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  87048. */
  87049. this.useDefaultLoadingScreen = true;
  87050. this._scene = scene;
  87051. }
  87052. /**
  87053. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  87054. * @param taskName defines the name of the new task
  87055. * @param meshesNames defines the name of meshes to load
  87056. * @param rootUrl defines the root url to use to locate files
  87057. * @param sceneFilename defines the filename of the scene file
  87058. * @returns a new {BABYLON.MeshAssetTask} object
  87059. */
  87060. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  87061. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  87062. this._tasks.push(task);
  87063. return task;
  87064. };
  87065. /**
  87066. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  87067. * @param taskName defines the name of the new task
  87068. * @param url defines the url of the file to load
  87069. * @returns a new {BABYLON.TextFileAssetTask} object
  87070. */
  87071. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  87072. var task = new TextFileAssetTask(taskName, url);
  87073. this._tasks.push(task);
  87074. return task;
  87075. };
  87076. /**
  87077. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  87078. * @param taskName defines the name of the new task
  87079. * @param url defines the url of the file to load
  87080. * @returns a new {BABYLON.BinaryFileAssetTask} object
  87081. */
  87082. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  87083. var task = new BinaryFileAssetTask(taskName, url);
  87084. this._tasks.push(task);
  87085. return task;
  87086. };
  87087. /**
  87088. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  87089. * @param taskName defines the name of the new task
  87090. * @param url defines the url of the file to load
  87091. * @returns a new {BABYLON.ImageAssetTask} object
  87092. */
  87093. AssetsManager.prototype.addImageTask = function (taskName, url) {
  87094. var task = new ImageAssetTask(taskName, url);
  87095. this._tasks.push(task);
  87096. return task;
  87097. };
  87098. /**
  87099. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  87100. * @param taskName defines the name of the new task
  87101. * @param url defines the url of the file to load
  87102. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  87103. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  87104. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  87105. * @returns a new {BABYLON.TextureAssetTask} object
  87106. */
  87107. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  87108. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  87109. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  87110. this._tasks.push(task);
  87111. return task;
  87112. };
  87113. /**
  87114. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  87115. * @param taskName defines the name of the new task
  87116. * @param url defines the url of the file to load
  87117. * @param extensions defines the extension to use to load the cube map (can be null)
  87118. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  87119. * @param files defines the list of files to load (can be null)
  87120. * @returns a new {BABYLON.CubeTextureAssetTask} object
  87121. */
  87122. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  87123. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  87124. this._tasks.push(task);
  87125. return task;
  87126. };
  87127. /**
  87128. *
  87129. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  87130. * @param taskName defines the name of the new task
  87131. * @param url defines the url of the file to load
  87132. * @param size defines the size you want for the cubemap (can be null)
  87133. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  87134. * @param generateHarmonics defines if you want to automatically generate (true by default)
  87135. * @param useInGammaSpace defines if the texture must be considered in gamma space (false by default)
  87136. * @param usePMREMGenerator is a reserved parameter and must be set to false or ignored
  87137. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  87138. */
  87139. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  87140. if (noMipmap === void 0) { noMipmap = false; }
  87141. if (generateHarmonics === void 0) { generateHarmonics = true; }
  87142. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  87143. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  87144. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator);
  87145. this._tasks.push(task);
  87146. return task;
  87147. };
  87148. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  87149. var _this = this;
  87150. this._waitingTasksCount--;
  87151. try {
  87152. if (task.taskState === AssetTaskState.DONE) {
  87153. // Let's remove successfull tasks
  87154. BABYLON.Tools.SetImmediate(function () {
  87155. var index = _this._tasks.indexOf(task);
  87156. if (index > -1) {
  87157. _this._tasks.splice(index, 1);
  87158. }
  87159. });
  87160. }
  87161. if (this.onProgress) {
  87162. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  87163. }
  87164. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  87165. }
  87166. catch (e) {
  87167. BABYLON.Tools.Error("Error running progress callbacks.");
  87168. console.log(e);
  87169. }
  87170. if (this._waitingTasksCount === 0) {
  87171. try {
  87172. if (this.onFinish) {
  87173. this.onFinish(this._tasks);
  87174. }
  87175. this.onTasksDoneObservable.notifyObservers(this._tasks);
  87176. }
  87177. catch (e) {
  87178. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  87179. console.log(e);
  87180. }
  87181. this._isLoading = false;
  87182. this._scene.getEngine().hideLoadingUI();
  87183. }
  87184. };
  87185. AssetsManager.prototype._runTask = function (task) {
  87186. var _this = this;
  87187. var done = function () {
  87188. try {
  87189. if (_this.onTaskSuccess) {
  87190. _this.onTaskSuccess(task);
  87191. }
  87192. _this.onTaskSuccessObservable.notifyObservers(task);
  87193. _this._decreaseWaitingTasksCount(task);
  87194. }
  87195. catch (e) {
  87196. error("Error executing task success callbacks", e);
  87197. }
  87198. };
  87199. var error = function (message, exception) {
  87200. task._setErrorObject(message, exception);
  87201. if (_this.onTaskError) {
  87202. _this.onTaskError(task);
  87203. }
  87204. _this.onTaskErrorObservable.notifyObservers(task);
  87205. _this._decreaseWaitingTasksCount(task);
  87206. };
  87207. task.run(this._scene, done, error);
  87208. };
  87209. /**
  87210. * Reset the {BABYLON.AssetsManager} and remove all tasks
  87211. * @return the current instance of the {BABYLON.AssetsManager}
  87212. */
  87213. AssetsManager.prototype.reset = function () {
  87214. this._isLoading = false;
  87215. this._tasks = new Array();
  87216. return this;
  87217. };
  87218. /**
  87219. * Start the loading process
  87220. * @return the current instance of the {BABYLON.AssetsManager}
  87221. */
  87222. AssetsManager.prototype.load = function () {
  87223. if (this._isLoading) {
  87224. return this;
  87225. }
  87226. this._isLoading = true;
  87227. this._waitingTasksCount = this._tasks.length;
  87228. this._totalTasksCount = this._tasks.length;
  87229. if (this._waitingTasksCount === 0) {
  87230. this._isLoading = false;
  87231. if (this.onFinish) {
  87232. this.onFinish(this._tasks);
  87233. }
  87234. this.onTasksDoneObservable.notifyObservers(this._tasks);
  87235. return this;
  87236. }
  87237. if (this.useDefaultLoadingScreen) {
  87238. this._scene.getEngine().displayLoadingUI();
  87239. }
  87240. for (var index = 0; index < this._tasks.length; index++) {
  87241. var task = this._tasks[index];
  87242. this._runTask(task);
  87243. }
  87244. return this;
  87245. };
  87246. return AssetsManager;
  87247. }());
  87248. BABYLON.AssetsManager = AssetsManager;
  87249. })(BABYLON || (BABYLON = {}));
  87250. //# sourceMappingURL=babylon.assetsManager.js.map
  87251. var BABYLON;
  87252. (function (BABYLON) {
  87253. var serializedGeometries = [];
  87254. var serializeGeometry = function (geometry, serializationGeometries) {
  87255. if (serializedGeometries[geometry.id]) {
  87256. return;
  87257. }
  87258. if (geometry.doNotSerialize) {
  87259. return;
  87260. }
  87261. if (geometry instanceof BABYLON.BoxGeometry) {
  87262. serializationGeometries.boxes.push(geometry.serialize());
  87263. }
  87264. else if (geometry instanceof BABYLON.SphereGeometry) {
  87265. serializationGeometries.spheres.push(geometry.serialize());
  87266. }
  87267. else if (geometry instanceof BABYLON.CylinderGeometry) {
  87268. serializationGeometries.cylinders.push(geometry.serialize());
  87269. }
  87270. else if (geometry instanceof BABYLON.TorusGeometry) {
  87271. serializationGeometries.toruses.push(geometry.serialize());
  87272. }
  87273. else if (geometry instanceof BABYLON.GroundGeometry) {
  87274. serializationGeometries.grounds.push(geometry.serialize());
  87275. }
  87276. else if (geometry instanceof BABYLON.Plane) {
  87277. serializationGeometries.planes.push(geometry.serialize());
  87278. }
  87279. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  87280. serializationGeometries.torusKnots.push(geometry.serialize());
  87281. }
  87282. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  87283. throw new Error("Unknown primitive type");
  87284. }
  87285. else {
  87286. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  87287. }
  87288. serializedGeometries[geometry.id] = true;
  87289. };
  87290. var serializeMesh = function (mesh, serializationScene) {
  87291. var serializationObject = {};
  87292. // Geometry
  87293. var geometry = mesh._geometry;
  87294. if (geometry) {
  87295. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  87296. // Geometry was in the memory but not added to the scene, nevertheless it's better to serialize to be able to reload the mesh with its geometry
  87297. serializeGeometry(geometry, serializationScene.geometries);
  87298. }
  87299. }
  87300. // Custom
  87301. if (mesh.serialize) {
  87302. mesh.serialize(serializationObject);
  87303. }
  87304. return serializationObject;
  87305. };
  87306. var finalizeSingleMesh = function (mesh, serializationObject) {
  87307. //only works if the mesh is already loaded
  87308. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  87309. //serialize material
  87310. if (mesh.material) {
  87311. if (mesh.material instanceof BABYLON.StandardMaterial) {
  87312. serializationObject.materials = serializationObject.materials || [];
  87313. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  87314. serializationObject.materials.push(mesh.material.serialize());
  87315. }
  87316. }
  87317. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  87318. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  87319. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  87320. serializationObject.multiMaterials.push(mesh.material.serialize());
  87321. }
  87322. }
  87323. }
  87324. //serialize geometry
  87325. var geometry = mesh._geometry;
  87326. if (geometry) {
  87327. if (!serializationObject.geometries) {
  87328. serializationObject.geometries = {};
  87329. serializationObject.geometries.boxes = [];
  87330. serializationObject.geometries.spheres = [];
  87331. serializationObject.geometries.cylinders = [];
  87332. serializationObject.geometries.toruses = [];
  87333. serializationObject.geometries.grounds = [];
  87334. serializationObject.geometries.planes = [];
  87335. serializationObject.geometries.torusKnots = [];
  87336. serializationObject.geometries.vertexData = [];
  87337. }
  87338. serializeGeometry(geometry, serializationObject.geometries);
  87339. }
  87340. // Skeletons
  87341. if (mesh.skeleton) {
  87342. serializationObject.skeletons = serializationObject.skeletons || [];
  87343. serializationObject.skeletons.push(mesh.skeleton.serialize());
  87344. }
  87345. //serialize the actual mesh
  87346. serializationObject.meshes = serializationObject.meshes || [];
  87347. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  87348. }
  87349. };
  87350. var SceneSerializer = /** @class */ (function () {
  87351. function SceneSerializer() {
  87352. }
  87353. SceneSerializer.ClearCache = function () {
  87354. serializedGeometries = [];
  87355. };
  87356. SceneSerializer.Serialize = function (scene) {
  87357. var serializationObject = {};
  87358. SceneSerializer.ClearCache();
  87359. // Scene
  87360. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  87361. serializationObject.autoClear = scene.autoClear;
  87362. serializationObject.clearColor = scene.clearColor.asArray();
  87363. serializationObject.ambientColor = scene.ambientColor.asArray();
  87364. serializationObject.gravity = scene.gravity.asArray();
  87365. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  87366. serializationObject.workerCollisions = scene.workerCollisions;
  87367. // Fog
  87368. if (scene.fogMode && scene.fogMode !== 0) {
  87369. serializationObject.fogMode = scene.fogMode;
  87370. serializationObject.fogColor = scene.fogColor.asArray();
  87371. serializationObject.fogStart = scene.fogStart;
  87372. serializationObject.fogEnd = scene.fogEnd;
  87373. serializationObject.fogDensity = scene.fogDensity;
  87374. }
  87375. //Physics
  87376. if (scene.isPhysicsEnabled()) {
  87377. var physicEngine = scene.getPhysicsEngine();
  87378. if (physicEngine) {
  87379. serializationObject.physicsEnabled = true;
  87380. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  87381. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  87382. }
  87383. }
  87384. // Metadata
  87385. if (scene.metadata) {
  87386. serializationObject.metadata = scene.metadata;
  87387. }
  87388. // Morph targets
  87389. serializationObject.morphTargetManagers = [];
  87390. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  87391. var abstractMesh = _a[_i];
  87392. var manager = abstractMesh.morphTargetManager;
  87393. if (manager) {
  87394. serializationObject.morphTargetManagers.push(manager.serialize());
  87395. }
  87396. }
  87397. // Lights
  87398. serializationObject.lights = [];
  87399. var index;
  87400. var light;
  87401. for (index = 0; index < scene.lights.length; index++) {
  87402. light = scene.lights[index];
  87403. if (!light.doNotSerialize) {
  87404. serializationObject.lights.push(light.serialize());
  87405. }
  87406. }
  87407. // Cameras
  87408. serializationObject.cameras = [];
  87409. for (index = 0; index < scene.cameras.length; index++) {
  87410. var camera = scene.cameras[index];
  87411. if (!camera.doNotSerialize) {
  87412. serializationObject.cameras.push(camera.serialize());
  87413. }
  87414. }
  87415. if (scene.activeCamera) {
  87416. serializationObject.activeCameraID = scene.activeCamera.id;
  87417. }
  87418. // Animations
  87419. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  87420. // Materials
  87421. serializationObject.materials = [];
  87422. serializationObject.multiMaterials = [];
  87423. var material;
  87424. for (index = 0; index < scene.materials.length; index++) {
  87425. material = scene.materials[index];
  87426. if (!material.doNotSerialize) {
  87427. serializationObject.materials.push(material.serialize());
  87428. }
  87429. }
  87430. // MultiMaterials
  87431. serializationObject.multiMaterials = [];
  87432. for (index = 0; index < scene.multiMaterials.length; index++) {
  87433. var multiMaterial = scene.multiMaterials[index];
  87434. serializationObject.multiMaterials.push(multiMaterial.serialize());
  87435. }
  87436. // Environment texture
  87437. if (scene.environmentTexture) {
  87438. serializationObject.environmentTexture = scene.environmentTexture.name;
  87439. }
  87440. // Skeletons
  87441. serializationObject.skeletons = [];
  87442. for (index = 0; index < scene.skeletons.length; index++) {
  87443. var skeleton = scene.skeletons[index];
  87444. if (!skeleton.doNotSerialize) {
  87445. serializationObject.skeletons.push(skeleton.serialize());
  87446. }
  87447. }
  87448. // Transform nodes
  87449. serializationObject.transformNodes = [];
  87450. for (index = 0; index < scene.transformNodes.length; index++) {
  87451. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  87452. }
  87453. // Geometries
  87454. serializationObject.geometries = {};
  87455. serializationObject.geometries.boxes = [];
  87456. serializationObject.geometries.spheres = [];
  87457. serializationObject.geometries.cylinders = [];
  87458. serializationObject.geometries.toruses = [];
  87459. serializationObject.geometries.grounds = [];
  87460. serializationObject.geometries.planes = [];
  87461. serializationObject.geometries.torusKnots = [];
  87462. serializationObject.geometries.vertexData = [];
  87463. serializedGeometries = [];
  87464. var geometries = scene.getGeometries();
  87465. for (index = 0; index < geometries.length; index++) {
  87466. var geometry = geometries[index];
  87467. if (geometry.isReady()) {
  87468. serializeGeometry(geometry, serializationObject.geometries);
  87469. }
  87470. }
  87471. // Meshes
  87472. serializationObject.meshes = [];
  87473. for (index = 0; index < scene.meshes.length; index++) {
  87474. var abstractMesh = scene.meshes[index];
  87475. if (abstractMesh instanceof BABYLON.Mesh) {
  87476. var mesh = abstractMesh;
  87477. if (!mesh.doNotSerialize) {
  87478. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  87479. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  87480. }
  87481. }
  87482. }
  87483. }
  87484. // Particles Systems
  87485. serializationObject.particleSystems = [];
  87486. for (index = 0; index < scene.particleSystems.length; index++) {
  87487. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  87488. }
  87489. // Lens flares
  87490. serializationObject.lensFlareSystems = [];
  87491. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  87492. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  87493. }
  87494. // Shadows
  87495. serializationObject.shadowGenerators = [];
  87496. for (index = 0; index < scene.lights.length; index++) {
  87497. light = scene.lights[index];
  87498. var shadowGenerator = light.getShadowGenerator();
  87499. if (shadowGenerator) {
  87500. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  87501. }
  87502. }
  87503. // Action Manager
  87504. if (scene.actionManager) {
  87505. serializationObject.actions = scene.actionManager.serialize("scene");
  87506. }
  87507. // Audio
  87508. serializationObject.sounds = [];
  87509. for (index = 0; index < scene.soundTracks.length; index++) {
  87510. var soundtrack = scene.soundTracks[index];
  87511. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  87512. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  87513. }
  87514. }
  87515. return serializationObject;
  87516. };
  87517. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  87518. if (withParents === void 0) { withParents = false; }
  87519. if (withChildren === void 0) { withChildren = false; }
  87520. var serializationObject = {};
  87521. SceneSerializer.ClearCache();
  87522. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  87523. if (withParents || withChildren) {
  87524. //deliberate for loop! not for each, appended should be processed as well.
  87525. for (var i = 0; i < toSerialize.length; ++i) {
  87526. if (withChildren) {
  87527. toSerialize[i].getDescendants().forEach(function (node) {
  87528. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  87529. toSerialize.push(node);
  87530. }
  87531. });
  87532. }
  87533. //make sure the array doesn't contain the object already
  87534. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  87535. toSerialize.push(toSerialize[i].parent);
  87536. }
  87537. }
  87538. }
  87539. toSerialize.forEach(function (mesh) {
  87540. finalizeSingleMesh(mesh, serializationObject);
  87541. });
  87542. return serializationObject;
  87543. };
  87544. return SceneSerializer;
  87545. }());
  87546. BABYLON.SceneSerializer = SceneSerializer;
  87547. })(BABYLON || (BABYLON = {}));
  87548. //# sourceMappingURL=babylon.sceneSerializer.js.map
  87549. var BABYLON;
  87550. (function (BABYLON) {
  87551. var ReflectionProbe = /** @class */ (function () {
  87552. function ReflectionProbe(name, size, scene, generateMipMaps) {
  87553. if (generateMipMaps === void 0) { generateMipMaps = true; }
  87554. var _this = this;
  87555. this.name = name;
  87556. this._viewMatrix = BABYLON.Matrix.Identity();
  87557. this._target = BABYLON.Vector3.Zero();
  87558. this._add = BABYLON.Vector3.Zero();
  87559. this._invertYAxis = false;
  87560. this.position = BABYLON.Vector3.Zero();
  87561. this._scene = scene;
  87562. this._scene.reflectionProbes.push(this);
  87563. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  87564. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  87565. switch (faceIndex) {
  87566. case 0:
  87567. _this._add.copyFromFloats(1, 0, 0);
  87568. break;
  87569. case 1:
  87570. _this._add.copyFromFloats(-1, 0, 0);
  87571. break;
  87572. case 2:
  87573. _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
  87574. break;
  87575. case 3:
  87576. _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
  87577. break;
  87578. case 4:
  87579. _this._add.copyFromFloats(0, 0, 1);
  87580. break;
  87581. case 5:
  87582. _this._add.copyFromFloats(0, 0, -1);
  87583. break;
  87584. }
  87585. if (_this._attachedMesh) {
  87586. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  87587. }
  87588. _this.position.addToRef(_this._add, _this._target);
  87589. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  87590. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  87591. scene._forcedViewPosition = _this.position;
  87592. });
  87593. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  87594. scene._forcedViewPosition = null;
  87595. scene.updateTransformMatrix(true);
  87596. });
  87597. if (scene.activeCamera) {
  87598. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  87599. }
  87600. }
  87601. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  87602. get: function () {
  87603. return this._renderTargetTexture.samples;
  87604. },
  87605. set: function (value) {
  87606. this._renderTargetTexture.samples = value;
  87607. },
  87608. enumerable: true,
  87609. configurable: true
  87610. });
  87611. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  87612. get: function () {
  87613. return this._renderTargetTexture.refreshRate;
  87614. },
  87615. set: function (value) {
  87616. this._renderTargetTexture.refreshRate = value;
  87617. },
  87618. enumerable: true,
  87619. configurable: true
  87620. });
  87621. ReflectionProbe.prototype.getScene = function () {
  87622. return this._scene;
  87623. };
  87624. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  87625. get: function () {
  87626. return this._renderTargetTexture;
  87627. },
  87628. enumerable: true,
  87629. configurable: true
  87630. });
  87631. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  87632. get: function () {
  87633. return this._renderTargetTexture.renderList;
  87634. },
  87635. enumerable: true,
  87636. configurable: true
  87637. });
  87638. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  87639. this._attachedMesh = mesh;
  87640. };
  87641. /**
  87642. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  87643. *
  87644. * @param renderingGroupId The rendering group id corresponding to its index
  87645. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  87646. */
  87647. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  87648. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  87649. };
  87650. ReflectionProbe.prototype.dispose = function () {
  87651. var index = this._scene.reflectionProbes.indexOf(this);
  87652. if (index !== -1) {
  87653. // Remove from the scene if found
  87654. this._scene.reflectionProbes.splice(index, 1);
  87655. }
  87656. if (this._renderTargetTexture) {
  87657. this._renderTargetTexture.dispose();
  87658. this._renderTargetTexture = null;
  87659. }
  87660. };
  87661. return ReflectionProbe;
  87662. }());
  87663. BABYLON.ReflectionProbe = ReflectionProbe;
  87664. })(BABYLON || (BABYLON = {}));
  87665. //# sourceMappingURL=babylon.reflectionProbe.js.map
  87666. var BABYLON;
  87667. (function (BABYLON) {
  87668. var Layer = /** @class */ (function () {
  87669. function Layer(name, imgUrl, scene, isBackground, color) {
  87670. this.name = name;
  87671. this.scale = new BABYLON.Vector2(1, 1);
  87672. this.offset = new BABYLON.Vector2(0, 0);
  87673. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  87674. this.layerMask = 0x0FFFFFFF;
  87675. this._vertexBuffers = {};
  87676. // Events
  87677. /**
  87678. * An event triggered when the layer is disposed.
  87679. * @type {BABYLON.Observable}
  87680. */
  87681. this.onDisposeObservable = new BABYLON.Observable();
  87682. /**
  87683. * An event triggered before rendering the scene
  87684. * @type {BABYLON.Observable}
  87685. */
  87686. this.onBeforeRenderObservable = new BABYLON.Observable();
  87687. /**
  87688. * An event triggered after rendering the scene
  87689. * @type {BABYLON.Observable}
  87690. */
  87691. this.onAfterRenderObservable = new BABYLON.Observable();
  87692. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  87693. this.isBackground = isBackground === undefined ? true : isBackground;
  87694. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  87695. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  87696. this._scene.layers.push(this);
  87697. var engine = this._scene.getEngine();
  87698. // VBO
  87699. var vertices = [];
  87700. vertices.push(1, 1);
  87701. vertices.push(-1, 1);
  87702. vertices.push(-1, -1);
  87703. vertices.push(1, -1);
  87704. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  87705. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  87706. this._createIndexBuffer();
  87707. // Effects
  87708. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  87709. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  87710. }
  87711. Object.defineProperty(Layer.prototype, "onDispose", {
  87712. set: function (callback) {
  87713. if (this._onDisposeObserver) {
  87714. this.onDisposeObservable.remove(this._onDisposeObserver);
  87715. }
  87716. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  87717. },
  87718. enumerable: true,
  87719. configurable: true
  87720. });
  87721. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  87722. set: function (callback) {
  87723. if (this._onBeforeRenderObserver) {
  87724. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  87725. }
  87726. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  87727. },
  87728. enumerable: true,
  87729. configurable: true
  87730. });
  87731. Object.defineProperty(Layer.prototype, "onAfterRender", {
  87732. set: function (callback) {
  87733. if (this._onAfterRenderObserver) {
  87734. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  87735. }
  87736. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  87737. },
  87738. enumerable: true,
  87739. configurable: true
  87740. });
  87741. Layer.prototype._createIndexBuffer = function () {
  87742. var engine = this._scene.getEngine();
  87743. // Indices
  87744. var indices = [];
  87745. indices.push(0);
  87746. indices.push(1);
  87747. indices.push(2);
  87748. indices.push(0);
  87749. indices.push(2);
  87750. indices.push(3);
  87751. this._indexBuffer = engine.createIndexBuffer(indices);
  87752. };
  87753. Layer.prototype._rebuild = function () {
  87754. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  87755. if (vb) {
  87756. vb._rebuild();
  87757. }
  87758. this._createIndexBuffer();
  87759. };
  87760. Layer.prototype.render = function () {
  87761. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  87762. // Check
  87763. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  87764. return;
  87765. var engine = this._scene.getEngine();
  87766. this.onBeforeRenderObservable.notifyObservers(this);
  87767. // Render
  87768. engine.enableEffect(currentEffect);
  87769. engine.setState(false);
  87770. // Texture
  87771. currentEffect.setTexture("textureSampler", this.texture);
  87772. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  87773. // Color
  87774. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  87775. // Scale / offset
  87776. currentEffect.setVector2("offset", this.offset);
  87777. currentEffect.setVector2("scale", this.scale);
  87778. // VBOs
  87779. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  87780. // Draw order
  87781. if (!this.alphaTest) {
  87782. engine.setAlphaMode(this.alphaBlendingMode);
  87783. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  87784. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  87785. }
  87786. else {
  87787. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  87788. }
  87789. this.onAfterRenderObservable.notifyObservers(this);
  87790. };
  87791. Layer.prototype.dispose = function () {
  87792. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  87793. if (vertexBuffer) {
  87794. vertexBuffer.dispose();
  87795. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  87796. }
  87797. if (this._indexBuffer) {
  87798. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  87799. this._indexBuffer = null;
  87800. }
  87801. if (this.texture) {
  87802. this.texture.dispose();
  87803. this.texture = null;
  87804. }
  87805. // Remove from scene
  87806. var index = this._scene.layers.indexOf(this);
  87807. this._scene.layers.splice(index, 1);
  87808. // Callback
  87809. this.onDisposeObservable.notifyObservers(this);
  87810. this.onDisposeObservable.clear();
  87811. this.onAfterRenderObservable.clear();
  87812. this.onBeforeRenderObservable.clear();
  87813. };
  87814. return Layer;
  87815. }());
  87816. BABYLON.Layer = Layer;
  87817. })(BABYLON || (BABYLON = {}));
  87818. //# sourceMappingURL=babylon.layer.js.map
  87819. var BABYLON;
  87820. (function (BABYLON) {
  87821. var TextureTools = /** @class */ (function () {
  87822. function TextureTools() {
  87823. }
  87824. /**
  87825. * Uses the GPU to create a copy texture rescaled at a given size
  87826. * @param texture Texture to copy from
  87827. * @param width Desired width
  87828. * @param height Desired height
  87829. * @return Generated texture
  87830. */
  87831. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  87832. if (useBilinearMode === void 0) { useBilinearMode = true; }
  87833. var scene = texture.getScene();
  87834. var engine = scene.getEngine();
  87835. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  87836. rtt.wrapU = texture.wrapU;
  87837. rtt.wrapV = texture.wrapV;
  87838. rtt.uOffset = texture.uOffset;
  87839. rtt.vOffset = texture.vOffset;
  87840. rtt.uScale = texture.uScale;
  87841. rtt.vScale = texture.vScale;
  87842. rtt.uAng = texture.uAng;
  87843. rtt.vAng = texture.vAng;
  87844. rtt.wAng = texture.wAng;
  87845. rtt.coordinatesIndex = texture.coordinatesIndex;
  87846. rtt.level = texture.level;
  87847. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  87848. rtt._texture.isReady = false;
  87849. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  87850. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  87851. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  87852. passPostProcess.getEffect().executeWhenCompiled(function () {
  87853. passPostProcess.onApply = function (effect) {
  87854. effect.setTexture("textureSampler", texture);
  87855. };
  87856. var internalTexture = rtt.getInternalTexture();
  87857. if (internalTexture) {
  87858. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  87859. engine.unBindFramebuffer(internalTexture);
  87860. rtt.disposeFramebufferObjects();
  87861. passPostProcess.dispose();
  87862. internalTexture.isReady = true;
  87863. }
  87864. });
  87865. return rtt;
  87866. };
  87867. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  87868. if (!scene._environmentBRDFTexture) {
  87869. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  87870. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  87871. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  87872. scene._environmentBRDFTexture = texture;
  87873. }
  87874. return scene._environmentBRDFTexture;
  87875. };
  87876. TextureTools._environmentBRDFBase64Texture = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAQAAAAEACAYAAABccqhmAAAgAElEQVR4Xu19Z7PtTHbW1g3jMMbGmGDAZAMm5xxMLDAU0WSKWOQcCoqccw6eGdtgk4yNbZxnvvAL+Af8Af6AsQl+06ako9X36dXPSi3pnPu+cz/cOntL3S1pq5+w1mrpLs/eud9fvn27rf9evPPwFz+v22S7fGZ/n7/70G79J5/Xv/qzbLP+Pnvvoc/6Tz7jX/15/c62LfeH7fofbpfP3l/ct36Wf+u4+D37+XYb++G26LPsr/zFttnPuh37bm1bt0f7MvtlnOx4uv0H4fty8UUsz77rfn/57u32cgXvDv72eQf0tl0+G38b0Nf9K4Dl704MEfA16KsE8Gw9JgD+DQE8EA0DT2b7GwK4GHnF4a8iguXZt9/vL5/dbisJbEq/uwD5vIK/fbbAv4N9U/8nJIDNCazKvBLBGwdwu62OhajxmQSAx6gqNp5HCg9wPan2nwSNjhLD8ux/3u8vP3y7vbwDAYjtR8AzFyDqLu1Q+YEINnew23rPCYiKb+q/K7o4AVT4tg0t/h4ydJZfkQASQ/d5b9fZ/Z1ENmuPn/cwYCYEELBguKC3nRkCnE0AFOwOKCOAR/sH/L4hgFMpbSWP5dn/uN9ffs7t9mJ5cAHoBLTyszBAFJ/F/xIKdASw5wgaEWDMLySxAk4svf6L+4QAGPiJCziNAPb4f3UZ2dh/m+z7BK4SAPYrxf5FB6ABPgCUAfANAZwKyscc7IEA/vv9/uLzbreXzx9cQCMACAl00m8jAlF7ov6SCMQ8gJsMFFBnCECSg5H6TxJAU3vPAbwhgFfz9AABeOEDBcIbB3AqPzwQwH+731/8sNvt5Ydut5e3B2C/fG9P+jESgGz/RgxG9r9VAwTUUh0goQDafUz+DYnAnSha5l99Z1l/yQVswAZSGIAugNd/9xBgCw9E8aECkHUB22QPHIAVDlQdQAMWAibhBgZAasAVHUAI8Cqg96Tm0bj3VBS9jwd7IIBvuN9ffMHt9vLTbreXy+32QlwAhgMIeuNzKwOqCoB2Aa00KHE+EsIeDuj4H2N+Hf/TfAC6A4nhgQCQDDwiaKDXiq9KgBEJNPArAtCk0AEd2mpAizW3/lYIoANpBPg3BPA+hjs/9eXZV+0E8Bm32wsJA9aEoBCAuAABPiEAC/yDC4gSgRgKRHkAlgsI6v7iEFqJEMgBwb4BGkEfEEDnDlReoAP/SQRgOYIB+IYDMEE/SQBbXoLNr0jhq4qOZc0PHBSf5oKW519xvz//kbfby8+83V68ABfwniIBgwgQ/HoRUMv8w5qAoQqgk4DWQiCw+63eD8k/XAPQgK5s/5a5xzAAqgR6wY9k+ZEMtCOoJABb230hEHMFWQdgAl0Ap/+uc6tKBrrP/n0AuwfiNwTwNKguHHV5/qX3+/M1B/Ddb7cXax7g2e324vaQB3hhkMAW92tHoFb96cVAbimwkgQ0Vv7R+D8iACfuxzKfLvnNlAAjAsBwwP2MwLQAD9sbYJME0AFcg5uBPSAA0x0AobhtcDKDA0j3KYDhk7Hp8uKj9/vzH3C7vfget9uLT9nDgDUZuOYCLBJA8MNKPyGGIftPrL+4gy3eh5p/lwRUYYAs9Fn7tM/E9lvJwCH2DxJ/mPTr4nyyLiDtBgTAGCrgNuPzNuETgN+suEEAFhng9lkCoICMLH7V0isCeEMCxylrefkl9/uzz90J4NNUGLDmAnYXINUBrf5dCCAuQCcCvYVAYPk3G++VAveVfkIAFRLolgbr2F9ifP33pAqAV/fHRF4HcAS7AKlAAEIYFNwITOszs/wMsB6II4BXFZ0QwBsSOEYCDwTw2TsBfPrt9uLlqzCgcwFABI0EVCiANl8Uvq0JWNsi2JPZ/0YKsOiHxftsW4v51ZqAaBWgZf91PsBL/jFHwEqBR1cCiuJ3gAfCmCEA3cf8rmz8AMZHIoA3JDBPAsuHVgL4jNvt+UoCH34ggK0asIYBGArsAB7AD+reQgCl+GwZ8LaNlP3MEEDaSg4ACMGr/+ulwV4JsAEfLH42/vdKgWElAJ4QpBl+LAlKErHwt+oGMgTA2ngE4IUIOH3dGr/hAKT/m/UBdSJYPuVL7vflU26352sScCWAD+0EsCcDVxewKjfmAzAsENVn4EfgdySgnYB81yEAgL4RA8T8mTUASAAYBgylQAkL8K/+zL6rsl8qF6ArAeS7WRGoAB8Sf7isN/VZqTs6jQ5wXlweWfyqpQ8I4I0TmCCAT/3I/b48u92ef9bt9nwNAdZE4FoOFALYXcAGegkDMByAzzQEgJh+cAIs/legH0IA5QTCPADE+7ISkD0TgA/8sBIgLQfOgF/F9kPcr+J8fIYguyCILQRKgV4DNviOzoKqeJS0u4AA3pBAjQSWT//I/b5OmC0MWB3ASgBrGLA+IryvDNxCgRXo+wKhjgwk8bcTwUACsJ09ANRVAALwCxmEoFcrAUsuAJ4M1E8BDuHABAHomJ8RgACrZfQLyT9dBWi2OOEG9NJd/TDQ8HAQuBE97ZhjGKy6o+imnU+4gDckkCeB5cMfud/v6zr9Dz84gOdCAM/3JwQhF9CAD25gBWWz/8wNgMpj3K9Lfy0foMMBVffXyT4r+cceC9bvCcDFP0311QrATPkvWgosYQFLAuoqQEcQuw3v2si25F+M1RkZXLUU+CgBmCBOEsCbvECOBJbP+Oj9fv+u2+3Zp91uz9cy4Kfebs/3ROD6iPD2b10YJCXB+0PyrgsHdtBuRACfBeTN+uM+suJPSEDbfh3/oxPoHgwiC3/06j8Eutj69sAQqj++I0CUfvIpwCEvYCT90O4Pn1XsT5Ve1/+dcp9FBh3woqXBSEJkvjHHEOUPqJPAjUUCeOMGfCJYPvOj9/t7//d2e7YmAlcS2B3A8xcPYcBm/7ULEDIQew+5gS0EIEA31R8Uf6gAoBsgKwBd9ddvBBJAs6XARgLQXQ2o7T8+IETe+9eRACg7rhCMVgCiE8D4O9wOCb2ubOht1/vYd2ubzLlgKbBHEDSnAMfL6durVm8qBPwXWz7rY/f7/X/fbsvL2+3Zqv4QAjzfw4COAMAJbEC3wC8koBJ9lAhgxZ+4hi3Oh/f8dU8EqtV/JhHgWn9cC4CJQZXZp6GAk/1nawMkrrcqAiwPIIA2FwOB2oaAF5UkcX+GADBs0I5gsNbBQqCorJcFJjqWKvhNMjky0Aek7/LZH7vf3/vO2215vruAD91uz/dSYCOAPQzYkoD7vw34sFIQw4LNymNSUKk8Wv0hCYhkoJ74Q6BboO9eDKoWAHXvBiCvAdPZf4nt3QqA924AbfXV8t8uN4Bt2We029WkoErWpSoCSm11TM8AOYA5uRS4RAITIQDDavaYHxCcm5exfM7H7vd3v2N9McDt9uxDD//WKsAG/ue32/M1DEACuO3g1jkBsf57fqCL/7UbIISAio85AAG0VQEYiIC9DJTYfy/+Dx8HlpeDRK8G90IBHQbgWgD2WT8LoOJ7NyeA5JEkAwwxmuqzur5X6y+sBEwDMggrqoBNH7c68Puk/fI9Vwfwvx4e6H724oEA1iSg5AAaAewlweeyLmAnAHQCTfU1CTAH4GyTMt+QDMRFQFEYQB71lXUAOjHYlvTqh4N2xe5yASoh2PpaJUGDBDrLr9cGIDlY1l+vDlQOAQHckYMiA68KMFsGtOy65RCGsMIDT+QqJoD3yUwCy/f+6P3+7koAt50AXrwigM0FrIuEoBrwHMMAUhmQUKAlAwHo7VmAPURo9h/r//ozLv1V7/5v6wGMV4B3rwYPXEBqIZAQwp4TYDE+LQlqtQfw6my/LgsyZaeLg7wVgmDnWQ5AA5ZWCDRx7ECzyn3udgFptFCIgTlyFRMEUCKgA+O/jl2Xz/3o/f7Otz88QvpszQOsLmAPARoBSDVgud02AthdwPZ5BSxUBVr8L3kAVHrvs076KSLQi3/M9QCJ7H/G/rf4n8X41XIgcwHecuBMDgAe+BHA6uQgqnvbF5DB5hwUQM3vQgIWkKOVftH+gAC6cz0RXZ9MjmD5fh/ZCWCd1CsB7CSwhgArAUgIIC5AQoDOCewJwab+CH79WR4C0mQAZT4hEQS9DgfEztNkoEECDfi6FAhZflb6Q1XXqwHDEECpvZX4a0qP1l7bfAS98cQfzQUo9a4mASMC0CsIm6JGK/2i/QkCuFK9PxmIYPm8nQDu795uy3K7LTvwVyJAB7ARwJoAVLkA7QIkJ9A5AQS95Ad2YmgvAJWwQFcBpB38pUuB9wVKbAWgCXwV86Mz2ICKTwUWFgOxMEBicr0eoBwCGBUADfxsDsAiA+zflNay31ZcfnAdAAXgDGkcdAcfZCJYfuCX3O9vf/vtthHAmgcQF7ATwOoAtn9IACsRSDkQ/wqIIUGoXYEQQ/sL5IDJP539776DwodVAGlr5QBgP8sDdApP3gSUXQa8/rZsRaBeHmy+HwDyCI1MUNlZzX9iJSBO9igJGJYCo4RdIqMfJQ4Ztq8C7FXjHuSnQ92XH/yvdwJ4Z68ErOXAlQRW0O9/JRG42v9GBHsuAImAqv+uzDo30C3yAfVHoHeg9xyAp/7wlp+WFCSWv1sOTBb+0EoAZP5DImBrApAUMFHolQG19c+EAkbpjyUEdQ6gm/QEsCzZFxKDlWNwprJVWfBm/1WAvWrcQ0ie7Lz80H91v7/9v263+9sPI2zrAZAEdvXvXMBKBJIIFDcgyUAEvHICg/o7wA/Bvyt35wCc2F9Cg03RvRyAA34N8hD0xsIfXP7bQgDMFSgyYO8GsF4N/hQ5ALak1yUGRQDZZJ5VWXgKEsie8yQuH63b8vn/8oEA3lsJYJ2EQgD73xX4z9bs/74gaHMBQgA7+DsXAJWBBniHCLTtNx2AUnkG/LYNiUCpvX7wp6sIOHF/lwgkNf8UGagwYMgLMBdgLQCyVgOyciCGCs5nz/Jr8EXOQOcQZEbrfjjTU8qaCBseMyx4vxPB8iP+RU8A24Kg9R8Qgaj/av8lDBgcwApQ+QdVgW0bKr3+jsk//AztzBKgtv4K+Kj08rl7JFgt9BnCAIsQcD2AsQAolQj0CAGAqhOFCK5u3cA+84dyIJLCPm6buAgoBa5qDoDF6wzUkZ13iSDKKwTamSKZSf29cuzJUwq7LV/wz18RwH2Nl9dKABLArv6bC5B/+9OBGxmsIIR1AQ3w2gk4RECTfwBulgC0rP96/FYJUOv9SzkAB/xuKTBY/qsTgZ0LILF/s/RW9v81ywEwhbeAwUIH6hRwGp+wEOhqoF49fojqQoPlR/+z+/3t77jd3n3rdru999CzEYAQAYJfXACEAqL8W5lQgA5uoJUK9zxBB3ii9ALiYT2AjvuN72wFILP+XdlP8gLKFeg6f5QM3AC+VlMMZ9ABGuN+VePHWL6tHVD23or3tQPo2iWfBRgShDp0ELcBjmIAbwTWqEzIJvLM6kEDEFcD9erxCzg3my4/9p/e7299x+323lu32+oAtjwAhgE7Cazqv7mAvRLQcgG7A9B5AAwHus87CWBYsIKFfe+eCSBgt2J+7QBQ+VsogOU/9fIPBvLhASEF8AHwlhPQ2wVYFhmo/Wby74QyYLcmQAEbbbue2FcnAb28QTmHQKBwNVCvHv8IESw//h/f7299pyIA7QIE/LsTeIbqL59hPUADvHIBG8jBIWgn0L4rsKMj2Noomz8QgZELsCoAAnh0Caj8lup7ib9tX+ZBoKgUmFkWTGJ8S/UHZa/kAHT+QGaeoeQmMUC/CoAzVYAjYDvSNwPCq8fPnINus/zEfwQE8O7tdt8dwGZjIQQQ9Y9cwAB+RQIC4I4MdvvdLL+O//E7LgLykn6q3Efjf6X8bOUfkoNYcQZ8z/KzBUBYCqT/YQgjBuOBHxPs7JHh7JoAy/IzWz+xEtBKBEYg8fIGw+SeQQQ+CzHZP+oWXWPU/8z9y0/+h/f729/5kAN4791X/6/cpl4SCsDfLRQwHEBLCmJFYH92vssNgBPo7D8qv4CekIHpAjKgx1iffGbKb5UAQwdguIAtz2KsEWj7vIQggNON91lYoIFN2mznYKj9UBmwQgXLLcDstRTdBchEFWAWcLP9MgC9cuzM8aXN8lP//v3+9v/uCUDyAM0FIBFADqAjAsgFiAvYwK3/MfAL8InSd/Yfy37Qpyv3OSTgxf8C5vZXPfF3aB2AA3hJGg5LghMOgCUBo8SgEAyC3Irvh5xAwhW0cT1iQBKYWds/QQLdeVUQcrEjeGoiWH7633sggHfWJOAaAkglYL/wLQyQf3tYsCp9CwmgFIgOgIJ/JwMdBuB3cQTDX4z9wR2whN+WE9idh67761p/F/8bpb8O/OotQCsJDhZfji0qT9p0LsCI83X9H8E9KH8iCSiTrQO29bwAAbvlCipPAw4T/oRKQAVElbaMJ472t7jnqnEjrlt+1t+539/6P4oAxLquawIkF7Bb/40M9hAAHcD2GVzABmBYKSgxfyMGAbROCipl1w6gs/8ZF0Cy/UIOOr7vHAIu9iHP/2v77yX9ROUt29+AHVUCnDJgtvSn8wXsnQGzIUAW3F27qFS4z2CrD07wCogqbR8LtGecUwR4vX/5OX/7FQFsOYC9FCiToBGAEAH83ZwA5AM06BspiPKrNQIt/kcg69iffBegNqVXb/wdQgIMC0DltUuQ+L+Bmz0OrNTdK/91+4JVf15SEPMCYRkwEfc3stBxurMS0AoTMKRocaV8cKw6jpcFsdUn2/8qRT8buGeP55HC8vP+5v3+1v99cADvvfNQBZB4dO24Kv5GAntSUOz/+n1wAis4wAnoMAC/N9svSUKsBABgmwPAbQTwWzsW/2vAI6j14h+1CEjnBYZFQWSxj+sEVFyPjgBBrhf+aOtPY39vRaBVJlQ2vyOGIATQsb6etBguDMSQyAF4IMhUAmZANNNnUNSqBDvtzzif6HSWL/wbuwN4eycA4gDEBQgRYPzfSGC3/BYBdOCHxKBHBAJoAbdWfIz1I9XXsf5g9y0yAJB7iUDPCaC6e2EA2ngMGyIHwAgBldncf4ID0EDXVp1NYmbnrclOtyfDhiPOoCO4CEXB/rOBfOZ4yy/8a7sDAALY1gKAfWMEgOovoNdk0IArKr+7gwH02gWQ2L4t/sEEoLL2IQnoFX96HYC4CIz/jcSgAJSVAtu2RPZ/SPRBHkC7AkYEqceC2fqBfdKaCcHAAeAkpKVBCANcElBVgBQRTC4HngHOTJ+rQo2jhEbP6xf/VU4AmBza7L+EAZgLgGSgxP8dGQDwmQOQbS2xp6oEWAnQn1seIEMCJO4fsv8Q2w/JQU0IJMvPiCCT/NPuQP/noJ0rAFBa23VSr1N/vQhIgxzzB9odMMIAkGvFZPF6JkyIlJeFFl6IcRYYX0ciOOOcll/6l+/3t/7fngPYy4BSCmyT0SGAlgvY4/+BAET10fZjUhAWCg2AV8nBEPQ6D6DJgSUAoQ/G+Dr+T9l/pfg0HxAs/e3WBUhbsihIgHKkHGiGCQHYO/UHomDgdd0BcRkZlYtyAFlgZNtlzqkSJcwc1xr/6FjLL/tLPQG8t+YA3tuXBKPiqISgAB//bjZdkoNE/Rs5EAIYXIAKCwYHYJADlvhalp8RgS4PogNwFN8jgo1A2LoALxRw1gA09TbCAjckQHBZlQEFwEoS0Iv1S3mAYFGPlwOIJn+0v+ocPohEsHzRX9gJYM0BvPvwTyoB2gGsP6iEAowANsBJWAAVgRYeAPCb/WdkAKEAttNJwRbzM+UPQI8K36k9Kf3RagBTe2vhj3o8uAFXLxUGxTdXBrK1AIltTZ2JzUe7Lp/Ralvxvrb5kcWP9nv2fwBzIRF4FRFkx/XcwRljHCGm5Vf++fv9re+63d4xCABVRhOAJoOtRCguQKoCmghwv7L/mBPQwB/KfMQhCEF0ym8RAUkIToUAxrP/gxOwSoDGmn9WCjTzASw3kHQA5poA7Q4g3n+MEMAChiadiopXwHZV26usvB43e/7Lr/pznADakmBdDcB8AFj+5ggcF4AhgAlwwyUM6m+pPgF8U3BS6jOdAAkJ3HUAO5C7ZKBT99/IVDsGhwyY3e8qNfhCERXDa5BrlW/ftaoqe265Ar0U+PIQQCUzqwqYBYfnSK4AcuW8sjmHaMzl1/zZnQDeud3eXRcCrfH/ngNYbyxzAKL8nQNAMiC5gI0gBNz42XIBAnAkBACwqDyWByPlp2BPWP7WD0Crs/5ewq+1JaBnWX8rEajbDiVAlbNpwHRyAJ4D6EqECQcQWfxo/0wI4E3wcPJnUbSLXqH5A26qHaD9kb7ssKaj+nV/ZiSALRG4rwhsJLBfUKt/k3yAJMGwEtCFBGD/PTIY4n6d8ANyaEk/Q/nPUv8h+WeRgXYCVgIwSwbK3osKi4PonEGUC2C2Pngc2LL73Xanlj9bBTg7BIgAFe2vuoxZS14B7wy/DCT8xX/qfn/rrYccwLtrElA7AJkgkrDSJUHJfO/Z/wZ4Kx8g4IXyYKfm0i9QfkoSJK5HghALr51Ce2Jwv0ad9BvAj1WCidKfZf1x3UDnvPQ90HYf7o1WfSQMGbOpU1D3H6oCynpjPE7VfSccpoalMEHNdAxFKkDLgDzTRo5ZaXukz1E34f1Gy2/8kzEB6MUlsjCoCwWMEAAdgOcGTECrnECn+JYTgPyABn0U82vwt7hfJft0rK9DAlHooTSolH94GxBUAnTSL/reAbz6UBADt344SDkIJBIT5E62HgnEAwgFmjq3ChFkAJUFd7Zd9fwsdZ89nnX85Tf/8Z0A1hwAOgDJAxBbuU1usboYCoiCKvWX+L/lAUDlNUG0bD8Bt7dviP9Vf0v9LbV3XQCz/3qbZf2d0h8D+JAPYDb/RAfArL1l92W7Z/OjEICpOZvkw7bES0EisET7M0RxRNkzx78qJGj37rf+MUUA+zoAnQjs1gTAhJNyFy4X7kBtkYHKB0ifDMgrLiADfJMESGa/Cwe0/a+CHsmA5QQ8N6ByAzJZh1IhEobOAegsvwaVDhEKDkCre0cielYbau4SQfIZggyIM0DMtMkc6ywnMHMsduzlt/+R+/2tt2+3d8QBiAtQSUBaEVDxPyYB22cEuiYDQgJtLUFk7539ke1vgAeAR05gC3ekbAclwuaEjEVA3XoAAnLpT6sBCuStrUrIpqsBHhkwcBOVTecFJAteCAFSyk/GzapwBOJofwV0mbEQkNX2p/X9HX9IEcB7eyLw3q8IlPgSbV/LBThEIMreQJkhAeYOIsDrsELV8VmIgHX9ITGo1L+BnxGB5wQY6IvKLzZZCKD7nsj8m+sADjoAVHk9ga19tF1CzSk5GO8T9MCUAdpZbSqEUW17lpNYfucfvN/fBgfwLlQBcEnwdkA9cdGiCjCgGrCpZhACDMSA6wL28dewgKl6GzuI963EXwtf1Nr/wQ0YMb+bCJwAPgKc5gPIPeiImeUC4B5J2zbZnGXBQjI4Mdk2HFNPYqv9MNlJCJByAzPPEezIiUAe7a8ANjPWGYpePc52Db/799/vb7/zKgQQAnhvDwH0cwFWLqBluwkRYJ7AqgoMTiHjApTqR9ZfbLxbCbCUX1wOKQGiO8ASn7XdKgMimL2SoG4nkxGVnqk+OoeBDHR4AN87EmCWnlULBGiBuiNJMFC5RJB8HsACRgYwZ7WpEEY2pNEuYOoYv/f37Q7g3dvtnT3+39YC6BBAv3IK1wVA9p8SAYC5gRDBqz53QDasvag/dQboGMCy0zBA7e/CgoTyszX/VeA35QeH1YGc2Hwr2YchGn5mJNGVd8FdoEOIHEBo9VkeQc3cqFJgEkPhxSBHwoIMCVTAlx1vlggq4y+/7/fe72+tDuDdV2XARgD7isDtd95BpZWjKRUov4Acwa6BT5OEsEjICg1aBUAl8DpwA2kgQeCYbHsjL0zygfKbll9XC5xk3zYGgM1yA0IKERGgI2PJQJ20M13CAQfgWv1kEjBj+Yc2zlqAGdWPgBPtrwI2O16FXMrn8Ad+z04AaxVgTwDiasAtBNgnrK4E6HBgSApichCBBHkBCnQNbmb1iTPoSEXlDXCfTv6x0EAA2OUDtCPA70bMT6sAXjVAlf4sIhieC8BYXy0CYk5gIPKCA8CJGzoAI5QYJqoRzx8NAZ6KCLLgzra7igSWP/i79hzA6gCAAMQFrBMNSUCrFypUm+x78k/cQRffY45AqatOGDJy0CDHkh5dDERielFhWvrTIYHO+icy/jK+qe6sCkCAH70erLsXylXMWv5GFowQrLyACISU6HZ0W+RALX0Qz2ug4NgYUWScRNQ+q6IZ8GbaVMCdHS99jX/4dwIBCAmsoNd5AHAB1sRDArByAV1YgLkBnfRDF6AtPbP4LNY32lkOgMX/tPynSKFzC466Y2JP+mT+mk8BOiVAVP2MA9COgH4nQGcgHxyCAe5uMicqARTcJ+QBIlB5+6O+V4E7c9wMCSx/9HfkCEDyAMPDJiQZ2AABqtZUVwG7s+ZWMlCDO/F9iPFZso9l/IkDaMRgxPqe4g8JQa30yg14pdaM7TddgWHxXcUPVgLqvnqyWw6AqrlT0jPV33AekYJb4IlAdfX+6LwR0BVi8Yhg+WO//X5/e68AyLMAawlwCAEwF2BkpTfgqwlu5QU6G45KrdYNsNi9qwAQMgjBnyEDI77XYGcxfjXut1wAhlfSptsGoNHJPab6XkLwTAeAk1MIidp+mJlRJYCqPxCABwizr0aUDl3I/ogEMsDMjJEZp0oYjECWP/HbSA4ACEDWAbA8gJ6MjADWbYP6i5LqvyRROBBABHgjXEAV14k963s7d0koOkm/s+J+FiaERADqbjkAHKNNrsRCoE7lmYsQ0HjlPm+dgMzKRLmQkkgyBJhR/SPWPwPyTJuriWD5U78FHMB7eyJQ5QDaYiBhXL0mgGWumRNQAO/KbieTASMOL8bvVgUSq2/lAvAaOvDiwiEjs6/BThdZ6bUBJNvfuQN0Z+pzVzI09nXqrT3UMRMAACAASURBVJcKg+J6xKAnLao7Tvruc6ZcyBS6EDpUXUIEvgyAz2oTnQuqe+aYzT386d98v69rALZ1AEIAazVgz/4zBzC8aorlAdS2rkIgC4e8v2TxkOsGMLeA45I6vgZ7ygFg4g8JQhOdl+FPZv+ZnRey0CQhE4PtH1TfCBmkXQd+S+1ZXkCTiQZq0gG4sb6qMHSAKFYQHpsIMoDMtKla/syYy5/9Tb0DWGP/7R8QgOUA2NtnzEw3LhRS6hjlA9CK6/gfS4XU5rOk427p9bg02cfATtS9CwGcSsB6/taTf9Zvx0ItvQ2JgH7WgEYyMMA+5AwmHMBMDsAjAhrPTz5M9H4mggy4M65g+XO/YSeAXf1lLYAsBca/24D7MwKdakBIYOUBxKYyJ0BDAeIOTOW2QI75AgVkXNVH7b+VBFTgDisAQda/gd5LrCrlZpa/WXJrEVBk+cGxNWAkqwDMQWiFNq2/zNKgDOi6A2NFICULRAV8rrSN7HgEzmh/NH4G2MZlDi8qXf78Fz8QgNj/thjIcADtvw9HNcgQwGxIwPIGLHTQVj8BfszWmzkAlZsQwFrlPbcCYOUCjBwKKwl6pUBRWyFhukxY7LmO7414X8f61BVY4YLY9iDBhy6BTX6LPJCoPHtcAXelbQRUD+gZEojGZyCvjrv8hV/fOwArBGBLgnFpcGdJYUJ0gNknxLDNCwm8xKEV6xtqPwt4DWpm92kIQICN7bSNF2Xv/pLfUgNd5wxoCEAA34GbqL0VAmhSuMIBuIqv8wGJRUQWmCzAfNIQwV/8tff7O+9BEhBKgEMiUIUAXjLQinMbAAAcCIruFWMVgBPFX28iLhW2Yvzu+JCo06A21wAQm69XRVJwk+RpaiEQCxeQKEDlaWhgtEWQWEqvt7vhwoQDKAFfjR+5hytdgjf20X1HLH/kIpa//GtUCLATgE4CogOQz628IwzslKx0gosuG1bWnuUGotJhyzUYYUIjBSsnoJKVXZnPCAeYo3EBH1UDDIA38CniiBR/CA1I1r5VEQBUg/1XVt8jjG7iWZUD5WEz5UIK8sRagIhYquQQgfqI/a/aeBYKZMOD5a/86r0MCGsApAqQcQDbgTQBMNuqJ70GE/nuOgMSGjDFj7ZZhNABnxBTIxon459Vfa9yYpUEEfRU5RXounEUkJEgGJlEYNb9O2IQ16hsO07y9nk2ETjzJKG4JIKUSlgQKqyDzgzQM22ic/AcxPLXflXSAew30no8eDsJvBGWyhmJsKojQOAOi3R0yRFtPcvuqxo/tf7qeryYv2T/mZqT0IARgfzmG9Eg6erP8Jvr+4Tk4Sk6IwnWfgA/IxsCPhmfKWuk3ugcqENIgLwC+hl1j4Ac7c+CPDNOd4/++q/ccwCRA1iFHkqAtBrA3ICh/J46Yp7AjM+DHIK27t1aA0YIbKGPIisrw59NAOqSH/0NEKyMCBS4qwnAtNpnk4JGnN8pfKYKoIgiA2R2DEYglW1XE8FZQI6AHu1vv8nf+BUPBNDKgFYOgDkAsHdmQhAnkhP74kNDg72OwgMP0CRuN90GW+CTdCwWoVluQKv3EAYQ1cZjuOpv9JXJNyT49KIgliMwlByVu7kJUFwvPBjcQuaxYSuUOBAGZMjGIxEP1BEQn3z/3/oi4gA0CQD4uxAACMBLCKLNjFSPJd3Q7rtJOWu1oZNcHMgmE+8H5T3P3Xj7OlCzCgEeN+sEVDs8Rpu4Ol9ggd1ScuYWkAQIsDv1lrYqB+BZ/2FfsBqQAe3sbZG6Xwn2aGzr3Ja//cuJA8CnAXfr314SajgBkwBwAs6EAwmwWWFChThY0s8iI297B3DDPYRtCLi3Psb2AdRAHrKvqb9BCEyNtaKXS4OkoqAnomXjKUEo9e/GSjqAs0HvAS8C5WzfaNwKES1/95cZDmAlAbIacPudIRcgi4H0oqBuUirgU6WDSVtJsHnJw8gtZNyGWeJLEJNn61vZzYjzo/3dQ0Ea1DgmUXMWAqTAbil9UOaLynttQj+iAzibCCLQRfstUM+ShJiqqP/y937p7gDuex5gBz5bByD23woDMA9ACeCAG8jkCLTis+8ZUhjCAisZOKvwySw/OoWONFWMrmv4ZsWAqX+wrXMGbLkwnMvgIowEIWuHTsV1CTKz978WeViA88IKDzRnA/Ts8TyCcUng7/+SngC2twFZJLBPljIB4IQ1wgA9waPM+rCfJApN9Tae1beOGZ1LO06CEKj7UbF9A7CVB7AShIa9R3Uf1gOwhF9V6S1iEEQFDqFN3my14IJEYNYRTANNERd+PZMMIsXXp7H8g198v68VgHf2uP9dBX5xAtvbgaUUqEqCg/1HKweAlx9vsLeGIlqxchWojCyqY1RCgXK5jxGHofIsD9B+V92nSAgIxCEkgLEGBU8mAaO4PgoVmEJbOQQG1CzIs+08Msg6kAwRzJBOlgiWf/SLRgewksCq8l0YAKBveQAgBGb/t4vDhJQmAwf4a9dQeZPWnJbiHMfgOYeNlAKlx3BFOxs3L6B+LySS8EUg6rzwuEgQ3luBGugDqx/lCzyCGPbtCBBi05M9Io2OFB4hEXgmGLMgzZDEjIvYruUf/0I7BGgkAJWAbY46SUArGThMyAIZVADH2ppEkiCBir2n5xmpu5ME1I5pUH+LYEnFICKEDpiFEADPSSu0JhQX/MphTBFBIYnI3MRjgLviLs48H9OR/JNf4IcAK9bxPwoV9TerAXgj4T0BOJk9MhAQDZOfACUCNgIy0zbTJpPZpyGAQwTiKug7AYkr0L+N991Vf00gpGyHINbK3yZVMQQwVT2xEMh1BEZ/Nvk1EKsKmgXyGeOeTQQdEf/TL3wggNX2b/H//jqwLRGo1gC0HMCeD9AlQPw+WDqZJEZIoCdaNY6OgOmFAVq5u7ae3Y9AHam7sd8kApUsZHaekclAvrv86eoBcwkZkFvrA1hf1wU4Cu4Btu1T/c8G/hWgrxDEmSFDc0D//OdDCEAqADoPIMnA7a8wrv6LpSEFfJlkoQtAdfKShEmAWlUDN7xgOYYE6DPuBY+Lv0W0HRXdK/cN2X6l0jqcsICubbx2AVeFAK7Sy+zV1YDiasAjgH6MvqZth+vXH6sksfyLn/eKAFaw6yoA5gEE9FYScDsZZfsR8CwhSJNb2Tq5UVLsQO0lE5Pk4bqRiBDU/oEcHFVn9X1T4dFZ6TKhYfWZcltqbm6HsZm6D07QKuGRcqQGgEUKSF5N2QySYPutbZkw4SmJwCIIJIXIYSz/8uf2BEDXAWAosN/w7gUhAHwhge7GY2wGBKFtf5oMGKgcl1Cx/wKwKKQY2hWB3oHbqver7ab6J8t/2L9VbaR6sM8auk4gArlRNbBchQnSaBw5RyV7lRCAgSYCerS/otRZwqiMmSECc7x/9XNUDkCvAyB5AAwDtrlBQgG8KegCOsvolQgrgPKcQKTQSReBhOCquBP3a8LTToXF/vpY8ls2J6AdBFH/rNJfov4YDoL6UzVP5gDc8MBJBFbBnwHrWW08EEcqrvhw+5oNBZZ//bMLBCDqb7kAcAJtUQeyOuQDcGIPnzFeJQClSbJqngBULW3xIzKpkBYe3wGxkISn/u5zASwccLbh5NHhht43ELsFcGeFXwfmA1UAdBsZ9YxU/ej+zDkwJ+RtO5Mkmhh9yc+637cKwJ79lxyAlP/kKcC1IqBzAJgL0K4AQwC0m7hgyAsBrAVEaL0HJU6SQKeiyT6dWictOwsTsqW+9ttosAax/pA3AKJBEqEhQLX+T+J2PG9GEIxEPPC6ag/SNzhOtm/fZo3JABYpfLT/KBFU+leUvxHNR37mSAAC/lYBUDkA76EgIYWOAHASKnXHm4/hwaB8pIxIV8oFFpxlziNws/0diSgF91bwuQQmE7QQ+2fUvwO+pf7KkXRA9db6W6QB1+KCHu1qMgTQE70DoTOG24/Y5qMuIEMOFYBXQ4FM++WjP2MnAFUClGTg5gCEAMhy4M4F7JNou/eZ0qBWELD7qO6D0uNkZXmEwKqb4HXI4wzAa8ejLTYSjb5mfXz8jgCvlP86YrhC/ZH4lfpSFU4SgAfMo88TZFxAlRgyY1aI4Iy2zQF87KfbBLCVAAP199YCaBJAV9AlnAxX0NqwnIBSrHSSziAPa/VeJt/ACMp0AY6l1+CNvofqb6h6NikoJMMUHN2apayZNt3YxRwAPa6Tb2iTXj4cVP2MwkdkUQFz5njsGt1tX/rTHghArwHY7P++DBhdwDanYCWgzgPIfh2TtfUB+6QcJhcBedfGUXoGwAaOyXhdKy4rC1rxPAtlymqfjP0x5h6ArVSdARJdiQa6BWC8t3h8RhQ616AnY+cEigRQdREWUZ1NDBnFz4I5Y+OroMf2y5f9VE4ACH50AS4B7OD28gDtxyEVgW6yOIQwWGlg/Uz8bQLXcBoa/AM56Dq8FcMbCTyx/o3ISF3fsvaMWPRv7JLEPht08nC4TyTDb5UNI1VnwO3coaHQFPBKxa0QwAO/G1LAucwA+2oHkDkny2Vs27/8pygCANUXF9D+h2CdC1CA334rcQf7Z7yxsp8qiFpBOKhPQAiW6jIlN9UdzllAKQBjdtxT9eF8HJLQ5xNae6Lska1nSu+pfyMjb3GOlxwEYrHANwA6sO/abdBxyRiPAf4ZoGf6WOA9y0Es/+YnAwHs4JfsP4v/JSEoTgD/is1veYFZEsB+xAp7gDEX0yRU2asQaHX2wD8QjEEsCDKt0pZqM2LpSqaiiNpteCW7mQSgukc4UTWxsH0Z8EaKT/erRGIW/E/pAo6AOdt35+Pxvwf/t0gA8BKQFfzZMiDmAYakoJ4oUB2gE4UtHDLiYQSa9bnsDEhJj4HfdBYHF/V4Vn8gvh3sh9Rfk60ot7c9Uf+Xc80AkDnCNGng+RrnzCa/RS6Z8zXBJDv0ORnf9bHY96Pbov7LV/ykMQfQrQMgVQABvP67//60BKgXA7UTU9Z/mDgk+TeAndjrBtpCBcEF9Wz23on7j1p9TW74mzaH4jgC/Vtri20uDdakzvIDbTL0y1I9Gx+V8CJHgNeTBfIMEXhjz5LDU5HB8pU/ccwByBOAXQ6AxP9sQVBL5EJGF8uByPYDCehJE1UGAuB7JKD3MadA22iFx9DCiPPpeZAFOZWyH46Jk2cDPiZFRX1IvI7XrMdg2fsOvCRsYGMM25QadgC8KAeQIg5BblAajOL26v5Z4DPrb6m95wKWf/cTxhwAPgJskQAu/aUhAIB5+22J9aelQa0uOuFFQoRBCY2Soc4PNBDBMQVAGJ50amqVI8kYOH4F3FTZsyU9EvuLMs4q/NBP3SNT1Y2FPQyQcs0RYYT7JxYTZQgiAmoE/Ki/8E80DgO+RQYe8Nvx/v2P3wng9updALgAyEoEYrY/ejS4katyBegG2OfOEqpSX7s4K0QohgVUpSft+5VgR7BFsb/nEkxScByD/s31pB2IIOMSIETRE9YLF0wiOGMtwcUu4EoyyIAe79uyEsDwIhAsBSrrT6sAuyJ0i4KU6p9CAkpl9boBNuHT7iCw9vThJBJfe8erKrt2IZZjoWSIcTkLCTwVt6oC6nojwLKYvuoWIsUf1DsZRljn7m3PAPcMBY/GqIK8YU/IHTYs/+HHKQLYAd+tBCQkMIQA7L0AQAxo8bbjI1MXPiOIqMJNOgIEly4HmvsUIaUA7oQ0tD/LuBsAzTqC7XosUnAy/MwBZADtKTl1fjhB2aT19j9RCHAGOWTGyII/Gyos//HHAgEo5c8kAbv4X6m+lRDEmy73EtViSEA5pcFOIVTSMHIEAgTLVuvVceXVeFWwO3F+ByIW5zuxv1ZRRqL6d2TK64E1Y/9dIiDWfVB3veqPEcEThAARcDNgPKtNdC6Dw/lPP+Z+fxcWAOHbgM2FQKDsQ/wP+7TSo+qzsiAqk1apLmGoVUor4kTpcCCDALzZen1EQpbNp+QEjgNdiZWxN8t4pCKQUXeLOChZOFacEoFxTmzsYRIjEZwQAnjjRwCL7Hu0PxofLnVc1IM7gzxGE96vWgkAHwUWF8AWAuGDQOyhIAQ/KwPu+9t5KmVvJwXtMHSgE9BQfU0g7oMy2g4byb9ZMFtkwUCMhNDtJ2VDDVoNLBoSEBLpQBYB18kPpElkv9HM1XRzwFB85gzw2BaArX4uoRRAFYG7up+RQYYgKm5i+aof/RACiPK39wAAEbB3ArSq3v4Bl//qpcAa8Nt3QhAM7N0FE7DTSWc4goEUAAwm8Ky1CNYCG69syWr/BJBWLkArvWflL1H/iDwE2I6dH0hKJkeyYtCRFYCThSdZYLuEwo6hCGwGlE9FBsNx//OP2gkAwwBJBBoVgK4SsE8KyQWwuJ8RAoIdCQJvpMXqVnlQA3z4TpRdjsHA1IEo6hss7JFzQQDQYwaE0AHAUmMrSWgAmJKomuRH7D8DmOVWGMAjgHb7T8oBeORR2XcFOcyMyfps2776C/ocwPr7df8rkEMC23xS/0uQLgVm3IBOAHYni1ldneHVcSMJKdbJEYYOQU7BDR+M8VMZeQZUY1tHVNYxlQJnQgJNKNbk9tzGAFovx0CWDXurDkPF1+MVcgBZhzDbbgaoVWdQsftNaIHcNwLQIYCQgCh9SwaC2jfgQ/lPg92qAnQnokIB6gCUcrlVAqNsZqqco+xMtTM2/FTwVxyBofAsvGGgNe25UxqskgxV+ETIkCaCAgFEzkLmqdXuqZ1ARBam6gMAl6/5kSoEUPYfwa/fBNSeBQBi2MZW7wRox8skBgnYTUfgKLeA11O4KDk3gJ0pWzI00BOYxuhOeU9fhwXWqdg/Io7MfuJKKNhBfRrAJisAFJgH1wF4oPYAF4HxyP6oLwN6xhls/f7Lj7jf5dHf9hdeBNoRgJH5L4UB+2TSpBDmBADsCG5U9izYq+Sg25uKqqsJhnJ64JdrcC13Mfan14tAdDL76MhM0qmOFdh2fRxGJBZQoycKI7BkQZ5tFx0v2h+BPw30BrhXH7bweCOA/eWf+kUgFvjxKcChGqAAbuYADCLQ4N5O14j9I/DjftcGe1UDpn7Ogh2LhCrHfyzw098Hwews/aVkkMzkD8qd7JciggNJQItUjoC0CuAjxMLOMzz3r/3h4ADgLcDM+ktOwKwC4HJg9ZmV/RoXWaGBUv1TiYABO8ofWLHwRDLPBd8JCn8quLMWPeMkiPozK5/dNpBCkAPIgnwWiLP9QqAqBc8of6rN1/3wh4VA8gRg9AxARwI7iFgJUCcAKwlBFg50lQIdDoCbMC1rpYKQrBygW+kUMcjkR+CsxvHus/sReCPQRvsR0A74rPCBnXtK6ZVTsdzgYwK+ovaVthE5zCi/8MnydZ+vQgC1AIiFARveINHnJQMbNlHlAbDbiTj7NBmUiYCoNqsiDBNUT+YjoHaSh3Lz3BDBcivedkaSjvqa8X2ypBe+QEQBVl9vBHrmCCi4H7EKcJban00GFcJYvv6H9UlA+i4AXAuAZT/1WWf/LdXv8G6VAQkxlMHPMsJFJ3CJylugstTaU2FPdT3wZpQ9UZ4LiYvU/TswJ1xDRsWZ88v0a0oIFjtDNt7YEQCPEEc0dnX/AwGQ2P9oDkDCAvld9XdP9dEV4I3tbpaenMZ3V2lIn0yCSlv0wyTh1Nkz9p6ppxVGoFU2VV/UOqn+6NKiMbtzdQgmcgRv1P/hJlXdw/C7/dcfajsAifeFDESU27MB+wa5jzoUaOB3LD4SA4v9NVF4LgAnd3ehgeozAHugHianEx6wCR+FG2YeA294whVQYtjvWQRUMw9BlDIkG7b6j4VmVrusOp9s/y0ncJX6R+POAD4kiI0A4L8BQ+Uf3gfg2H/2MBBTfdP+C7vAzdaPAFfIwLSERHVoIoqUBjNKm3EDGVIwx8kAOFLuaL86hkkkxcU/jDgrSh8CUhG9B6iMzc+0iUB7xO6H4EWszLqBb/ghJARgTwKytwI7OYAhBHBcQDYckOtlTmFYABIA3XILbCEJ3QaE1ampsRItHTbsF+mqqpUryCzZzYA/QzJJN+ICPLFqLwPCI/F/aXy5N4YjiRT6akB7BGmd2/INP/ghBGjJPwL+1QnIfGf2X8CuQ4GGEZXoO9UFEOdwhAxYDiCtXE79ngKh2t7LFWTAHwAbSTEKEby2kaqznEHUJ6XmCUJJjaPUdFbFK4CvtI2IprJ/+caVAHQSkD0ObL0MxCgJbnNNqb7+XlX+KATYLlwdky4NZVaRxY/ZcMGLZwNHkCaXCPwZ1bbOBZXNyS0wkJruSKmll1w9CsrHdACzZOBdYwWwYj7CcAhcijf+8o0/KHYAkgzs/u4Trqm+/g7gKYUDRNG7F4jKhTlAbz+SbgNjdz+g0S5yA0wFO5AQAnHVzwOoZ/vPAn8yMeclKSMlPwOspm1nhO2oeRZEM+0qgH8q9d/O8ZtWAig4AMGQuRDIWQ48JAUBkO3eRcDWuQSi+pETQOBSdpxQ/kjJI7IYljkrVXaBlajpZxbqeGrOQEDzGqA8OoywfvdqHP5+IICznEKFSDJOYhjvm35g0QEkFwIh2Bm4w3AgcAJ6MrV5R+y9BpcmCFQl+oOz8MByE0qNu/EK4UDkJBihWHF7Bvz4m5jAJct+I8Wn+6+I1a8YE0k4+OwBtaLwlbYZwIfjrQQwrP4jK/82+6+2y8q/IQmolR2SiNvvqFUc3x/A9jOwESfAgB6BnxGJFR6E9tWbhJ499ey9FUbIhDT6ejadAjwKMbSVtkgxY7kvAOuZjwFn1fvq0CACeAhucGPycejzzT9gdABYERheCLqDUQhh+0qeC2iYNcBvWf4wMWgQhE7+CdHoC04TAlFy0zkY6+41udAJkyANar8JKVIHEBFEspYfOZLIxofkmSEOr82B+H9WvWcIoALaStuILNj+bdtKAF4JUKu+uQpQx/5AFKj6NBwQeiLOYCCxKEegCELb++GHcCoCA2taYHXU0IrtXTJhjsd5kKcDpziDBEEgQZkkg+MBWVigiYjA/T3gZofjGI4kC+azwTszXgTaqwlgHX/5ls97tRRYVL2tADRCgUH1yYKgDofE4nc4VqDG/EGbE0ZiziMIF/yGYlCHYJEKKzviJLaOEWTbQ5CQpN9AAhcoP5JWGaBA8lmyKYHZI+FgldwMeLNhgncNlX0RWczufyAAWQqcjP2tCgACV+Z+t0RYAUmIpAOxEdtHTmDbTybBsHaAnIMmiuHmatcBk9m8iexcEgrqVgP2c6cxvFL+LMii2HkYJ5Er8H6TaeL4ANj/CKSPofiIowcH8P23COBGnwHQhOBVALxHg1l4kCED0mbIEVjqTIhk+4GT26dJIXAF0yGBQR4U6MR5ZNsNTkIRS0mVsa8ir+o4LnF4ZKvPYXKV3xWK/1o4gG/9/ioJKC8E9dyAAXaM75sDANDp+N8LA7p3CyjF1Y5B3xxKEsZ6AVo5SIDYZHMvGRUlqqLseLCSbzunpBVGMsy6hTA0icAWXf9sIjC45irZyPzKuJUjIH4KxR8cwLd+v50A1PMAmOzTnwXTYvkld7Bth5uM+9uBo3yAodKR8uP4HUEQ5dFtGYEM25QCDwQQqVAEzAgcQdx/JvipC4jICX50Cpxk/wzoorCkAsrM8WbHM0WCEGXU9qr9y0oAWwiglH8LCYz1/w3wqvznqr5BDhqsUwuEqg5BkUwHdgOI2yGsx02tHIHcaGd/pMQIbArMRF7hCGAwFMqAxWwTEdys+sO9zJzfjBuoKPVVba8lgGISsFsApElivyE45wdXADdNhwUdlkm8nnYCCeWXY+l439tecgvG5OxuZqSMjnPoJnwWYJETYUoenWOkaBP9M2C2yDML8my72fg/Am2FLKKxZvZvfb7t+77KAWxOwEj8NXUHp7DNb3QBCvwSAnSCq0MAQhiitugOcCzcbsX71qrAri9OXEY21nMGHUu9GnG4oQVncMg2Z8FPSDEFNMcVHemf6ssIidw3a6wsyM9oVwXhUQLwznkQMVIKbQRAV/45RKDJoAHcIQMhiwjUQwjQscer3hYh0BWBxhhCNCzej/ZZx9FuIsolHLbMFUWfAXIUviAY2ecKOUVjMTIoXH8EmAwhRSA/Cuoj/c255pHot33uQw6A5QFku5cLQGAjMSDmLCcw4BImixUaCDCZkntuwGtPCcABCx6nHBJkVDg7qSuvwEoAcQDIBPi9MTIAKyt59rcKyGWWHCr9IvJ4kv2NAII8gIC1Wwqs1wUAoi0yEABrx82UP+sGziCFDsgkHLDyBN1N80gjqCLg+CkQJOPqdn4BUOhEniENVJtE/2x8TduRa/IAmT1WBMSzxomO8yj7P/65r1YCotIPn0m8j28BFpVvwGdkoCRf2/gOd1k3MNgImIEEyBZZYEKJugVrHYEoi3EsTSzu5HEIZCCFyuQPnMIl4If7kgVMtt0hUkOCMj5XgVex7VM2XU3IlEAQxyPDdP0//n3GlYAh+FWs370OXBbbqWSfblNxAlbbsuUPyMLLBeA9YLafTZruB8+AO2vps+32650Flqem4b4T1d881oyreWICqJLL1e2XjQDkjUDkmX+d5WffEVeWE0CBNJU/qfq6f0eQBdVv/Qw1tdyCBWzGsDJGqBIZgiCAzjqK0kQ6A1hnjOGBNUEwIUmd5AAqxyndB0PFw7nkOAY9R5ePf+9XSUBGBAJudAVt234Ttn37xi4ESGyTE0rnAIBtBqwfAD/+Zl68r8nGdA3RykEsy2TtfJYkKsfWk+wM4GavJwnA2fj/CDCPgqzSPwoLov1HSOUVAeBKwGgtgJH80+AfbL8OC9A66Od0gFy0UiuCa+Sjt0cKboYQRGmHsR0w4vmGE0GRltk+AapuIlTbG9dcDh8mxpkCauL6wt/eUcojfY8AUiv0Wd+tc3ogAA/8xsKfDuykTVP2/YO1GlCLNnUCiii0Cpu7LUfgjUf2WTG/JgXLORwFtbkE2VLQRNKPTgiHjNKASBw7PZZ2J0Vnc+Q4ugsk6gAAG0BJREFUVVKKQH/muZxKCp/4Xv3DQGLn0fI3sEerAPVTghAaaFyllgcDi1Asq43t6yzwI2IIKgHiOFKWjZyjZ3XZBMuAOJqYbTJVwwuDfIb/l8FR2cy5VX6Ts0HmZdunz90i7eClJZnjZdoMv1EjAMcFbLiYAT+x8TpX0DCeAHPXxAA5XTug7YiW7on9NPYPwgLtEEKiSNjcTg2y4YSehCeBv+xUZid98ne5khCmwHaQDGeOGfVZVgKwqgAiiBH4U2XAfTCco1qxNcAZxiOAm+J/kSvwEoYU4Anl325ath0hr5BYNPDYq9Sr4LzY+reJfBZZVa/vhPYRGGf2Z/p4bZZPfM++CmCFAF4YIETR/upnApw3AqUJAQ4ShQPD/ovA3wjdANDwwxvKZbVjN45uSwI427eqnIywpsbIKOT7iAAy4Ix+p5kxMn2kzSsCCKoA+AiwJoOOAJTtF8vPSAK3NSFLhAJdPwLuTKiwHc8jhsx+1YaGBSRxJdeadQgWETBVTJNG0mVEE3TbXww9yg6lmPzL/gapawNSitpXgIdcF40783tlzmUd94EAEiVAuc8m+HWOoCH61fxAy19R/mplAElHicqrryeD3wM1fVkpm1gBkOgxHEV0gZA4VnpiFlQ5MzHNNoXjpM+9APBozKuI59BvpgAwJgE/B0KA6CWgrP7vZP4bWcBJZJYEI1FYQuzlAtw8gTFg2jXs12I+diz7gQA9tu/2GaRkOQvrfYapiZgNR6znyMn1zQCkpG7GOZfG0PenQAAZIM6cS2bcq9osnxAC0C6AgH14+Ie9EIQQwoY5FRo0HAbbKY5In3Yf2QtHEGVWiGEAVhHow1cHPHgeJnAZqAIll3GrSUdKBkdyBmQF41WTsxv3LMK6mAAe5bdwSKt6/AcCMEIAmevrbz88A7Dv1CofVQQ66w9ftAJrMdSuAHD46ucIiEGDeRDcKCwgB43KgZYa47l4biIav0QyybjfOufhWGcRiQHK7nivKQFUATcQ+Ylgnhl7+cT3sEOARgDO038dATjZ/w74AKTM9q05AScjBY8YEHRVy4/Kr4mEKZXbRnaSa/IAvR3HISk3CZkkr3AMOPeM3c2SiTtWAfyzgDyz3+xYZ/6e6XPoCMBZ9tuAboB8cALKIbT5x54H2CeVBrkGOHUFHjFQNlBJ6wnVZ+AWgogA3Fg6cVymuJ1zME/kYQdT0CwgXTUpEFdmUodtCgQQjrVf2NXtMuNn2lTu18x4rxyACgO8sp+n+ts+A+Rs+a+0Z1jFfXS/ASLLGQxjJEAYlgpn1FwdN0UazloDD6wR4aQVH4GTPP+ZCUkn/MmhxtWgsu7H7O9x5fkun/hsFQKw5B+AGsGfjfc9UrDIYjukmmjatlv4taoAFduvyccFWYJIvOSdFvIo7s8Avps0ScBaE606VoVUdFvL9byO4Inc2PvhnEcC2CfL+mf7p+P//ar1dgTsEA7AmJ1gFrZ36k36tXEjV8CshFwT3tEsqBPt2rDQNqX68GNl2kfEUQGmpcQR+VSOkQJIQf2vUMorxkxdd1R+hbl6aLzmAMhCnuEZAKPmrxW+EYAFcGtpsLM9dATgUrSiMvLQbSruYArQCaKIAJxyCjgxnGN6hGLuyy55npicFuEcJZSjAD7aPwvOK46TGfPBAej4nz3959T8B8VXYMR5aK4HIACOLD8DLZvzlp2nZiAB1G1+J9pVbD8jrdR6Awts5PymQL+Pf6j6EBCCNVHN/7iV/lgq6XkWCcn1k2NmwX2UxLLHyQBeLkPGXD7x3cccQGbdP1P9UPmt5CAAqiMLOVvD8re2XkjggHXASALUWfAzl4BzKLT0wblk+kdt0vuNc6lMbBPkhtU9tMpRgfUogGaApfmi8lsdPd9S/44ASLyPQEelZwlATQqIPU/56ctB1MtEGI61slP1NybvU4LfELBXmxMZfzZGxnGkQY8HgB9rxkVM9XkK0imqfYUYqgRYAnHBEelxXzkAJwcg4EOFz9p+5hSasBPlZuGCMgIPIkwmiN50RjWg+22zDsFxHRnwR21cEKtzjADvTUx0OzMgjsY2VbEI/iq4ps+L3JiKslfPszJ2pS2exwMBZHMA+8Re709HAGxxELTtnACgWZNIa5ew/APY9c0xngno+qlBXHxfDP7tBlaOwSZjsn+GFLZJciAMOUQYRQI4dKxHBvWVJDAz9vKJz4rXAYjidiHA/sPRtQDWE4LGOwIt1e+2KxvgEsD7DPyotNPqXwQNO84ApIkxI3IJwXryMcPjnUAAVeCd1f6MaxsJgNX9WXjgKbzlCIwyX7vn3jJhpZCUAGBjRBCKTzjukoraOlfbp04iooTk04mFic4I6QiwvQkvp+XlL44cewYkZwF0uDZ1D2Ztu76VR8ZZPv5ZDxpOwwDr+X9P4ZV9b66B2HodRmgXnHEGrc8Tgz98B4GF4wJp0Bud7B+BqDu9fcxMn6hNaT+5llL/IsnNkMNMn9eZUDYC0M/5I2jXzxqowzaw9l1bZzsCl1p9I1zQJCHkhffeVH+HJBgA9HwysZYE4TA/Z/sZziECi+clPAXOKg62y5xLFHJMjZFU2ciVnA30GRJ4jD7Lxz/zVQ5AwFVa/rt3osAv5gIQ3A+25OFuenbefV6AlBLZeBb4U/hMNSLQC8gonPyzx7Xq7gapyObwfKJx4SfIOJmzjveYQM78VlW7PktU2eseCSCI9wegW5Y/SQwakDpksPYLM1juofVTQHFxE71NKGkJQmyGDTyt9qsFGeCYo8N5ZcfJtnMnsvo9smNm2mWBUHU50bFnjvvYY67H6wiAvvLLyQPgk3xWqKCFRZSdAbdti5KBilws8YrcAd70cgxfJYtAYQPI97uPEog62DbxCmNGE7UKJjx2duwz2kVjXLl/hiAihzEz5isCCFYByhzRCj0A37H92xjE1neuwtmP/V1nQBYKWfMbQ40MCKvtD5EMO6ErgBqMGQGBnWa6z37sdPujoUYUipy4f9a+R0A/c9zl277bXgXYRQABjsDUIK0Anym7DiW0m2CCaS0ZHsggafuzYO6GSwCQNkn0CwnojDESYUwFjDjcTL9osVHZTTwigCMgvu77txCAEkCy7s9IAcHI3IIGNoJwIAV0ppmwYD+4xgn9HoCpAuIQl0aDsF9nH0J6KDWo2v5DKk86zxy/QjCZtq9Tm+hcrtq/EUCn9M4LQIYwYL+x5mpABUgK8H0jgmH47IC/U38Sl1fBnwV+GryzuYILwd+GTl5ENPmyzNONkzx2xg7PklP2ujLtHqtNdJxov3YljQBEibW1t7Y34CVW/Wngt3vv9MXxB4sPd5w5CBY+6PESTvihCUzU7JzF68uCwzrnSnKudCx1MZmJUxo/itWTP+bMeWX7PEW7s46ZGSdq00IA+uYfou4DkEG9vX2W7Weqz8gBccjcAQNPRfnNuUjcCQPB6a7BZIMqBI32SfBVjhZNtm6sxPFL48HglX5XtM2OeWa7zFhWm+VbP6NPAgrYXOX3VH8fwFT9qEqg+rvq76izRxQZfEVlQXcOJ4nDBdgZY6TZKoZ6ZpLFo4iq8JZHj1Htf1X7K8bNjDnTZiCAyPLPxvs4LnUEiaW/HaifCPyReEXEkSGfM22/nO82OaKTTyP4QMOLQo/M5NdnfXWf6viZ9pk263Vm2m0hwOoAUK3NxUCBsrvEkFH9YI1AN3+zFYHki0M6UBog8bCDYcth0SUHOgW3pwxyAPiJ9wvMjp6Z7Gzsx+pXPU62/RntGgFYyt/IQVnS9au3DwHL6vc6RIjWASDIBntvOMvsSkAPwBZuuu0HQBuNUwUFPd+LwZ+diFc4kPSxyQ/52H2rx6u0z7bV7ZZvkRyAEddr694BP3IFmXyAE/NHlt8iAv2fjXju1wJ/Cvhq4AzOzDZO58y4mXxClUxObX/4IvqzyU547xqOjnGkf7VvpX2p7bd8eCIJKIpLXAFTfq322jl0feCOee00qC2HYIHfUt408GFgb26n5v0JawVmiOVUgHuDpX6E+GwqEzseLRcnXz3OzDVV+3jtl5UAEKAIOhO40WO+mZifOA5KBEG7DuCJhUADIcDkZPPUJIQDil21/dP4KXYsNs9g46HNgYGrkz1/UucRwHrMo+c527/abwwBdgLoSIAou1bjSNU98jD/81Ct/t7/IyAuRPocAH9F9be2pEM0x+l+tTEag03u11H55Zy2yTZzURUUH2xbBVDmcEfGfOy+yzfrEMBaCrzfTAbsiBwyYcGg/oSEAOu9sKi2oe2fUP3WJQnacN4XbH84lp6VB9xJZoKn25RPPD3yaQ2PAC5zEkfHP9I/03cjAAbgAegHFv9YBMEsPyqsPgcNbNaWgb+bh4QsNLHgjWV9Q4IxZoZFIubxghmWcRWZSVrgj/xwb8Df/VYZMEY/7hVjPBAAgIIqvKHGkfJ3Y0UEsl99+L4AaQcoxLmm593Z4Gfz2pvrw76kg5giBXIiV+EwHDdsEE336/efAaiZszzzuEfHWr7508k7ARXIEMjMGZhKnnkpKGnDxhu2ESWfAX8K0Jn/ZwBmgjn3E7Y/i5uIWDITM3uszFgdYV01cPVEgvZHwXP0dK46fmXc5Zs+nZcBN8BFqn10v7H8V5NMZ7kTVYHBoicBTMkgqaqhC3AaRHiJ9m8TccJZeBM4dUw2wIHrjABVmdjkJ2nDV8eJzuus/VeelzX2RgCDwnuLghxV74CbedQ3Uy5MvBQkUn53P7odreIJUFnzvdueGKdq+b3xLwF2NqE/zRxnweiDNc6VpLD+Uo0AGnjBWg92f6dVur2yNFhA59h4nEfb5+T6fw2MCPxU9ZV8mG3UXKNzn1yjnqIRZtz9RXIpinaIplkiCgd+08D9Bc4ihuUbMQRQkzXrDBAv4UNBcllR+IDK/Ejgb5MZZnVEIJ7V9J4M9EAdEUI7ZqZhVrkzZJawFslTegPvR/gFMiSxEYBW2PX7oPIROWTe+JsIHzoygS/6fDTwjiq/Bv8s8BmJAOfR2x6BxnMW1dDBIyxrTkbnt/VzGqX6PwIgjhxCX0MGXEeO9xh912t4IIAo5nfAj2o0kAaqeDLb341hHNcDf/QEoAvsI8lCA4nW5D/iAE5558ABxR/O/SDCD3a/DCuZ83q/E8HyDZ/mVAF2pCEoKcizdj5DJEIaVfAnlgJXwT/lApxS3wzoM2DLTNSK8mfHE+UvtS/A9apxM6fwlMeW81vJ5WrnsREAA/W2LQHsVMyfGKez/gr8Q1ignEXm8V8PzFXXYIHJUmY2mWbIwPq/EvWEzkzeTJuQNMgg2XEzIJwJb6rjHgp7zjrYI43D3MryX8EBWHZ+VvUtEmGAbseAGUSPWwT/2apvglntOAv0bRwDWRnAXdYmM/BkEvKpgZm8tEeC7nWH6QhgRvVdkColt9rKcT1ioC4gsP0V8LttjUnMwFkBvjXJhu2EFGcBEk3saL8cN5uHmD3PaMpnzzMax9v/GMc4cn5n9N0IANXXBWnmPQCi0Enwb8AO2mbAXwFw1fJXiKQBxLg7FYJAR8aGiyboZfvVwNFxMhN1ZoyZPplzie5hZYzXve3y9RICEBAOZJAEdQnQxpiuG3DWBWA//RnJhu5TdyskFTIDKwBPtU2qfwQGb3/Ut/utEo0TTUxczPSd6ZMF5pVjZ88hanfkHDcCiAC7HSAqFQJthi4icAlU8YMyImPtAcAOmLBtCHzCHikwR6GEvtMnVxQY6ZFD2vMt8TDTjFN5yj5Xgisa29t/BNSV4y5f/6nj04ADABNZfI8kqJor5XcVPwF+D7RybimSgF/PHDNQ5YhAPCC2vkl3EYF6VvlpP7VxZpJW+lTasntbAYLVduYcKse9evzoXJav+9RX6wBkMnUKfgH4U+VFDcTkcmANCAR/SBIF8M+CPOUUCDnijZwB9UyfDlSJmZpo0s3HTPtMm7McRMkNRcgK9s9e18HDDt03AugArx7qMfftQ0XKP+MmvD4U4HguhDi8PpV9mfUGTJFToJdrMGaGNWHO2u46iYCQjgAwC4RsuyxRZoA0c8xo3CvGjI7p3dvla4kD2Dqom06JIOsOEs8A4A9jOZCzwV9yBKpxBtSZNt01JY5h3cwzicA7p84VZGZech1AFhjZdjPneYTIop+iet7ReGed60YAFuBc9T8R/IPiF2N+Rh6RWtM+xEmIw/EmlEckacA6KnsGuL0JaO5LJv2ykztqF+2fBXV23LNApcc5cnyPCM4Yd/kv6ACyoM62q7wSTD+BaDiQlAuYLBNSIBeAGRGBSQbkTlZAf0bb4dySbqQ62TOTNtPGDVkIarJjnkkCR45Z/V1nHMPa5xUBwEQ/TfnhF3DHJC8TYa7gKPhLqg8Hi4Bd3W9ZbDZhzgB3ZYx2bs7szUzsqM3R/Y/pBqJzPZM0HgP4eD0bAaTi/WxeoBDvD6SQIAzG/K1bslJgEUF3o48+XUhi32EiFev8WYKYAjzOPBCDSFkicHj7o75Zlc+MQy4vurS2vzp+9ryvtveZ81i+5lPGMiBT3zRJ7J3Tig9UHvVxHYC6SxmQm22csVwC2q8lcgTbGGRWHQF4tq83KbYxjNkegWAW6NG4mUk84wYyx50Zt3K+FgFUzu2o+9gIIALeVeBHuxmdQxb8VeAP48IAEZCn9zvHsCZQFuDZdvQ4CeWPJudTE0F0fjNOoDLmEQKoHmfmWjRhLF8dOQA1KVygFpKDrwP4B7IwgDkNdOYIDJBlgXt2O7wPenJEE3IG7DN9qhM9Ou8rx5slgMo5zzoT5hY2AjBBfTL48cfZhs6+OhzOvANtArBpR5AA5mEiIHc5GjPrCLLEcIXyW5O3uj07sTNgybTJgjU7Vna8KtEebe/1X/6z5QAmwT+AnL1g9CD4hTzcsMAiDba9mPCLQEv3G2RlTfoMoDNtvEnZ+quBZlR6Buwzx7lCvTMAz7SZIYDsuFlyZCrvnddGAIMDCMDfgbxCFIkKgUcg2q6m1X3/VWj7yTUD7Ec1iSHhLrJEcAT0dLIVKxHRRKwSQQSAq/dH15PdX2030z76LRj4oz7LV2kHQJRqIAgB1GOD31DRChF0bR3lM8GcKO91fYvuwmJr73y8yeQSRlL5zwL1rOJHk/jo/oxyR8e4GtDZ41fPoyeAQhKvVBk4Q/kD8FdIYLvhCTLxQozIAWzDBwCLQB3tj87BnQwTyl8hgkrbzKSNAHD1/gxJZNtkrhfVPLo2rfyV9hsBlMH8RMpfBjn8MpbyZ8asEEEbT/1GFZWOgB/tD13EBcpfBfwVbiCa+FfvrwA7OpfKWLNksZ7D8p8+lFwI9AS2H1U0A1Rp47YlwLTaTwF/7xSB9Oj+I+pfeX15SCYGyWYm5etGAhlQPmabqxwFjrsRgAaO+f0k5ccTcI+dBGuaHJLjReByCSNQ16PAj/qHgIUBKqrN2h7tH6ncFQQRgSoCeLQ/Gj+65gxxasufPSZrt/zHrAN4jcCfBjyG4RPPCZQdgAOuCLgeqUSEFIIeZt0VQD46pjeBryCBCMRX788CNjqPCplYx9wIIHQAB8GfVvwT3gNAgTQBflflme0l7qJCIDMgzwCvtQmcSZpECi82rTiECBTVsWbHi/pl9kdtzgT20bGW/xA5gNcc/K4bOAh8D8DdD3/kPygplhVLoL9Q+TPnESlUFdTV9rPOIgLw0f1HQRv9rjpE8I63EYDpAF5D8LuAP2j5o7GpSkMn/UNXvlfaZtxCa3Oh8lcAWWk7C9yzjpEFmAes2X3ZY2dIKNNm+feWA3hC8FeASNuS9QxZNbeOTfur38i6edkxI2BnVFc7kyPWPnO8yvhntI0m9WOSwBGQRy7g6P4skWwEMDiASfDjzTFdxX5m3f4CYCNyyCzwicZIkQUBv6fiFYWvtDVB9cjKnyWLqrqfBehZsM4CcbZfFrjR+BFRynGWf6cdwCT4GahSJBCAPwJrtx++6GOnQK3icVO5T3p+oAL0qG13fYScvImVAW/p+CoIzYxfPb8qkUSAuIIgZseMzjWzP9NmPb+NABpYXgPwlwAPE02vZjwT8BHJsMn7ZG6AzLoMAM9qU7H5Z6j7GWNkVLd6nCwAFVe2r5HCn7V/+crVAVSeAUALbyjhrPJ7LsIC9NaHKN4lDsBQVtMpOI7CIyg2ebxjzKr/DOgzfSok8NhtI2CeCfQjID3SN7pG3L985cvEOgAE/ZFXfSceCio7AMO1uIShriflFhySqQL2DMKgx0yofwbAnnupALYCpsx5PUaY8H4ILSoAjxzG8hUvi88C7Ee3VB5PjrZJuA02BgVp4EBSwM7E/cn1BBVV90A2tQ86RQCOCCuz/ygRZAF/lETOBLSnypXz9Igssy8igIp7WP7tTgAhcCfVuyOBE8DfLq4A/shVuERhAGsKpBeFBNH/gmRNqogoov2PRQJHj/MYJDBDDkeAPHs8fcxGAJaiVwHMwLZtS4Df7Kst+8HKgQX44fj7hizYz24XKbH8rmjzItAe3R+dU9WmZ53AB5UEZoE8228ggH+TdQAFADMgpQhGAZ0SAlHkSOGj/VZ4MRNCZPvMtuv6JQgqA9gqKWTBmAV3tl32uGcpvgWy6vZZpT8L5CgQlAA85a2qtwZ6RflDB5AEfwT4aL+21Fb7LIhn+kfAzfzHIhVgR22j8zmq/BVQZc61SgKV41fH9n6bWXI4q9/y5SoJiAMfBb9Xm7ccwXB8cQVE7QayIW8groI0s5KwOmYEHm9Cm/suUP+MEp/V5oiaV8B6VdsZEphR9Jk+FXLYCMAE0oTtb2OpCZoBq+kAjLFMsgDP4x33TOsfugohMnJuEUEM56lmRaSIV+/PnP8RwGfHrxzjyrZnksPlBPBlRhlwxrpnwW8CnWXJC0RymBCS5b4zwV5Wf+hwBNhH+lqW9rHdwVF1P9r/dQZ6ljiWlQC0SjIbPLRRilYFv0cC7Yc9WOrLAFWf94y9n+ljnZurdie8YnzquMS9PAUJHAVshqCs63oMsFeuzzvPaB8eZ/lS7QCU4jJVNckgUGurH1XuiVJfilSYFTdUtUIgR0nA67/tU7OjouBll2GEKVnQZ4EWXUPFps8es3KM15EEskoPt3T7KP02AojUO0UCk+CnoCWAzII7Au2w3yG8o6COzoUBioKCnKPrFBjJqRlQcQLVY2WJIjNuBaCvIwlUVX0G0NVjdATwMXEAAYBdEnhC8Ecgc/efGPNH5xFNdhOQRdt/ptpHCh3tj675CFE8JTFUjv2UriFz7GUlgOp/DNKRwUHwdxPfUeMjDoCCq5BfOOoEZvpr2x+BLavolXEyAM6obnTMzHEqoMuc09HxKv2rbTPAVYZO/ydUbXfkKP4/BnecprBuissAAAAASUVORK5CYII=";
  87877. return TextureTools;
  87878. }());
  87879. BABYLON.TextureTools = TextureTools;
  87880. })(BABYLON || (BABYLON = {}));
  87881. //# sourceMappingURL=babylon.textureTools.js.map
  87882. var BABYLON;
  87883. (function (BABYLON) {
  87884. var FramingBehavior = /** @class */ (function () {
  87885. function FramingBehavior() {
  87886. this._mode = FramingBehavior.FitFrustumSidesMode;
  87887. this._radiusScale = 1.0;
  87888. this._positionScale = 0.5;
  87889. this._defaultElevation = 0.3;
  87890. this._elevationReturnTime = 1500;
  87891. this._elevationReturnWaitTime = 1000;
  87892. this._zoomStopsAnimation = false;
  87893. this._framingTime = 1500;
  87894. this._isPointerDown = false;
  87895. this._lastInteractionTime = -Infinity;
  87896. // Framing control
  87897. this._animatables = new Array();
  87898. this._betaIsAnimating = false;
  87899. }
  87900. Object.defineProperty(FramingBehavior.prototype, "name", {
  87901. get: function () {
  87902. return "Framing";
  87903. },
  87904. enumerable: true,
  87905. configurable: true
  87906. });
  87907. Object.defineProperty(FramingBehavior.prototype, "mode", {
  87908. /**
  87909. * Gets current mode used by the behavior.
  87910. */
  87911. get: function () {
  87912. return this._mode;
  87913. },
  87914. /**
  87915. * Sets the current mode used by the behavior
  87916. */
  87917. set: function (mode) {
  87918. this._mode = mode;
  87919. },
  87920. enumerable: true,
  87921. configurable: true
  87922. });
  87923. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  87924. /**
  87925. * Gets the scale applied to the radius
  87926. */
  87927. get: function () {
  87928. return this._radiusScale;
  87929. },
  87930. /**
  87931. * Sets the scale applied to the radius (1 by default)
  87932. */
  87933. set: function (radius) {
  87934. this._radiusScale = radius;
  87935. },
  87936. enumerable: true,
  87937. configurable: true
  87938. });
  87939. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  87940. /**
  87941. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  87942. */
  87943. get: function () {
  87944. return this._positionScale;
  87945. },
  87946. /**
  87947. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  87948. */
  87949. set: function (scale) {
  87950. this._positionScale = scale;
  87951. },
  87952. enumerable: true,
  87953. configurable: true
  87954. });
  87955. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  87956. /**
  87957. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  87958. * behaviour is triggered, in radians.
  87959. */
  87960. get: function () {
  87961. return this._defaultElevation;
  87962. },
  87963. /**
  87964. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  87965. * behaviour is triggered, in radians.
  87966. */
  87967. set: function (elevation) {
  87968. this._defaultElevation = elevation;
  87969. },
  87970. enumerable: true,
  87971. configurable: true
  87972. });
  87973. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  87974. /**
  87975. * Gets the time (in milliseconds) taken to return to the default beta position.
  87976. * Negative value indicates camera should not return to default.
  87977. */
  87978. get: function () {
  87979. return this._elevationReturnTime;
  87980. },
  87981. /**
  87982. * Sets the time (in milliseconds) taken to return to the default beta position.
  87983. * Negative value indicates camera should not return to default.
  87984. */
  87985. set: function (speed) {
  87986. this._elevationReturnTime = speed;
  87987. },
  87988. enumerable: true,
  87989. configurable: true
  87990. });
  87991. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  87992. /**
  87993. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  87994. */
  87995. get: function () {
  87996. return this._elevationReturnWaitTime;
  87997. },
  87998. /**
  87999. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  88000. */
  88001. set: function (time) {
  88002. this._elevationReturnWaitTime = time;
  88003. },
  88004. enumerable: true,
  88005. configurable: true
  88006. });
  88007. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  88008. /**
  88009. * Gets the flag that indicates if user zooming should stop animation.
  88010. */
  88011. get: function () {
  88012. return this._zoomStopsAnimation;
  88013. },
  88014. /**
  88015. * Sets the flag that indicates if user zooming should stop animation.
  88016. */
  88017. set: function (flag) {
  88018. this._zoomStopsAnimation = flag;
  88019. },
  88020. enumerable: true,
  88021. configurable: true
  88022. });
  88023. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  88024. /**
  88025. * Gets the transition time when framing the mesh, in milliseconds
  88026. */
  88027. get: function () {
  88028. return this._framingTime;
  88029. },
  88030. /**
  88031. * Sets the transition time when framing the mesh, in milliseconds
  88032. */
  88033. set: function (time) {
  88034. this._framingTime = time;
  88035. },
  88036. enumerable: true,
  88037. configurable: true
  88038. });
  88039. FramingBehavior.prototype.init = function () {
  88040. // Do notihng
  88041. };
  88042. FramingBehavior.prototype.attach = function (camera) {
  88043. var _this = this;
  88044. this._attachedCamera = camera;
  88045. var scene = this._attachedCamera.getScene();
  88046. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  88047. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  88048. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  88049. _this._isPointerDown = true;
  88050. return;
  88051. }
  88052. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  88053. _this._isPointerDown = false;
  88054. }
  88055. });
  88056. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  88057. if (mesh) {
  88058. _this.zoomOnMesh(mesh);
  88059. }
  88060. });
  88061. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  88062. // Stop the animation if there is user interaction and the animation should stop for this interaction
  88063. _this._applyUserInteraction();
  88064. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  88065. // back to the default position after a given timeout
  88066. _this._maintainCameraAboveGround();
  88067. });
  88068. };
  88069. FramingBehavior.prototype.detach = function () {
  88070. if (!this._attachedCamera) {
  88071. return;
  88072. }
  88073. var scene = this._attachedCamera.getScene();
  88074. if (this._onPrePointerObservableObserver) {
  88075. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  88076. }
  88077. if (this._onAfterCheckInputsObserver) {
  88078. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  88079. }
  88080. if (this._onMeshTargetChangedObserver) {
  88081. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  88082. }
  88083. this._attachedCamera = null;
  88084. };
  88085. /**
  88086. * Targets the given mesh and updates zoom level accordingly.
  88087. * @param mesh The mesh to target.
  88088. * @param radius Optional. If a cached radius position already exists, overrides default.
  88089. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  88090. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  88091. * @param onAnimationEnd Callback triggered at the end of the framing animation
  88092. */
  88093. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  88094. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  88095. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  88096. mesh.computeWorldMatrix(true);
  88097. var boundingBox = mesh.getBoundingInfo().boundingBox;
  88098. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  88099. };
  88100. /**
  88101. * Targets the given mesh with its children and updates zoom level accordingly.
  88102. * @param mesh The mesh to target.
  88103. * @param radius Optional. If a cached radius position already exists, overrides default.
  88104. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  88105. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  88106. * @param onAnimationEnd Callback triggered at the end of the framing animation
  88107. */
  88108. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  88109. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  88110. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  88111. mesh.computeWorldMatrix(true);
  88112. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  88113. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  88114. };
  88115. /**
  88116. * Targets the given meshes with their children and updates zoom level accordingly.
  88117. * @param meshes The mesh to target.
  88118. * @param radius Optional. If a cached radius position already exists, overrides default.
  88119. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  88120. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  88121. * @param onAnimationEnd Callback triggered at the end of the framing animation
  88122. */
  88123. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  88124. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  88125. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  88126. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  88127. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  88128. for (var i = 0; i < meshes.length; i++) {
  88129. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  88130. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  88131. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  88132. }
  88133. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  88134. };
  88135. /**
  88136. * Targets the given mesh and updates zoom level accordingly.
  88137. * @param mesh The mesh to target.
  88138. * @param radius Optional. If a cached radius position already exists, overrides default.
  88139. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  88140. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  88141. * @param onAnimationEnd Callback triggered at the end of the framing animation
  88142. */
  88143. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  88144. var _this = this;
  88145. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  88146. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  88147. var zoomTarget;
  88148. if (!this._attachedCamera) {
  88149. return;
  88150. }
  88151. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  88152. var bottom = minimumWorld.y;
  88153. var top = maximumWorld.y;
  88154. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  88155. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  88156. if (focusOnOriginXZ) {
  88157. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  88158. }
  88159. else {
  88160. var centerWorld = minimumWorld.add(radiusWorld);
  88161. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  88162. }
  88163. if (!this._vectorTransition) {
  88164. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  88165. }
  88166. this._betaIsAnimating = true;
  88167. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  88168. if (animatable) {
  88169. this._animatables.push(animatable);
  88170. }
  88171. // sets the radius and lower radius bounds
  88172. // Small delta ensures camera is not always at lower zoom limit.
  88173. var radius = 0;
  88174. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  88175. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  88176. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  88177. radius = position;
  88178. }
  88179. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  88180. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  88181. if (this._attachedCamera.lowerRadiusLimit === null) {
  88182. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  88183. }
  88184. }
  88185. // Set sensibilities
  88186. var extend = maximumWorld.subtract(minimumWorld).length();
  88187. this._attachedCamera.panningSensibility = 5000 / extend;
  88188. this._attachedCamera.wheelPrecision = 100 / radius;
  88189. // transition to new radius
  88190. if (!this._radiusTransition) {
  88191. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  88192. }
  88193. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  88194. _this.stopAllAnimations();
  88195. if (onAnimationEnd) {
  88196. onAnimationEnd();
  88197. }
  88198. if (_this._attachedCamera) {
  88199. _this._attachedCamera.storeState();
  88200. }
  88201. });
  88202. if (animatable) {
  88203. this._animatables.push(animatable);
  88204. }
  88205. };
  88206. /**
  88207. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  88208. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  88209. * frustum width.
  88210. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  88211. * to fully enclose the mesh in the viewing frustum.
  88212. */
  88213. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  88214. var size = maximumWorld.subtract(minimumWorld);
  88215. var boxVectorGlobalDiagonal = size.length();
  88216. var frustumSlope = this._getFrustumSlope();
  88217. // Formula for setting distance
  88218. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  88219. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  88220. // Horizon distance
  88221. var radius = radiusWithoutFraming * this._radiusScale;
  88222. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  88223. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  88224. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  88225. var camera = this._attachedCamera;
  88226. if (!camera) {
  88227. return 0;
  88228. }
  88229. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  88230. // Don't exceed the requested limit
  88231. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  88232. }
  88233. // Don't exceed the upper radius limit
  88234. if (camera.upperRadiusLimit) {
  88235. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  88236. }
  88237. return distance;
  88238. };
  88239. /**
  88240. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  88241. * is automatically returned to its default position (expected to be above ground plane).
  88242. */
  88243. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  88244. var _this = this;
  88245. if (this._elevationReturnTime < 0) {
  88246. return;
  88247. }
  88248. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  88249. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  88250. var limitBeta = Math.PI * 0.5;
  88251. // Bring the camera back up if below the ground plane
  88252. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  88253. this._betaIsAnimating = true;
  88254. //Transition to new position
  88255. this.stopAllAnimations();
  88256. if (!this._betaTransition) {
  88257. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  88258. }
  88259. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  88260. _this._clearAnimationLocks();
  88261. _this.stopAllAnimations();
  88262. });
  88263. if (animatabe) {
  88264. this._animatables.push(animatabe);
  88265. }
  88266. }
  88267. };
  88268. /**
  88269. * Returns the frustum slope based on the canvas ratio and camera FOV
  88270. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  88271. */
  88272. FramingBehavior.prototype._getFrustumSlope = function () {
  88273. // Calculate the viewport ratio
  88274. // Aspect Ratio is Height/Width.
  88275. var camera = this._attachedCamera;
  88276. if (!camera) {
  88277. return BABYLON.Vector2.Zero();
  88278. }
  88279. var engine = camera.getScene().getEngine();
  88280. var aspectRatio = engine.getAspectRatio(camera);
  88281. // Camera FOV is the vertical field of view (top-bottom) in radians.
  88282. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  88283. var frustumSlopeY = Math.tan(camera.fov / 2);
  88284. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  88285. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  88286. // along the forward vector.
  88287. var frustumSlopeX = frustumSlopeY * aspectRatio;
  88288. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  88289. };
  88290. /**
  88291. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  88292. */
  88293. FramingBehavior.prototype._clearAnimationLocks = function () {
  88294. this._betaIsAnimating = false;
  88295. };
  88296. /**
  88297. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  88298. */
  88299. FramingBehavior.prototype._applyUserInteraction = function () {
  88300. if (this.isUserIsMoving) {
  88301. this._lastInteractionTime = BABYLON.Tools.Now;
  88302. this.stopAllAnimations();
  88303. this._clearAnimationLocks();
  88304. }
  88305. };
  88306. /**
  88307. * Stops and removes all animations that have been applied to the camera
  88308. */
  88309. FramingBehavior.prototype.stopAllAnimations = function () {
  88310. if (this._attachedCamera) {
  88311. this._attachedCamera.animations = [];
  88312. }
  88313. while (this._animatables.length) {
  88314. if (this._animatables[0]) {
  88315. this._animatables[0].onAnimationEnd = null;
  88316. this._animatables[0].stop();
  88317. }
  88318. this._animatables.shift();
  88319. }
  88320. };
  88321. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  88322. /**
  88323. * Gets a value indicating if the user is moving the camera
  88324. */
  88325. get: function () {
  88326. if (!this._attachedCamera) {
  88327. return false;
  88328. }
  88329. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  88330. this._attachedCamera.inertialBetaOffset !== 0 ||
  88331. this._attachedCamera.inertialRadiusOffset !== 0 ||
  88332. this._attachedCamera.inertialPanningX !== 0 ||
  88333. this._attachedCamera.inertialPanningY !== 0 ||
  88334. this._isPointerDown;
  88335. },
  88336. enumerable: true,
  88337. configurable: true
  88338. });
  88339. /**
  88340. * The easing function used by animations
  88341. */
  88342. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  88343. /**
  88344. * The easing mode used by animations
  88345. */
  88346. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  88347. // Statics
  88348. /**
  88349. * The camera can move all the way towards the mesh.
  88350. */
  88351. FramingBehavior.IgnoreBoundsSizeMode = 0;
  88352. /**
  88353. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  88354. */
  88355. FramingBehavior.FitFrustumSidesMode = 1;
  88356. return FramingBehavior;
  88357. }());
  88358. BABYLON.FramingBehavior = FramingBehavior;
  88359. })(BABYLON || (BABYLON = {}));
  88360. //# sourceMappingURL=babylon.framingBehavior.js.map
  88361. var BABYLON;
  88362. (function (BABYLON) {
  88363. /**
  88364. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  88365. */
  88366. var BouncingBehavior = /** @class */ (function () {
  88367. function BouncingBehavior() {
  88368. /**
  88369. * The duration of the animation, in milliseconds
  88370. */
  88371. this.transitionDuration = 450;
  88372. /**
  88373. * Length of the distance animated by the transition when lower radius is reached
  88374. */
  88375. this.lowerRadiusTransitionRange = 2;
  88376. /**
  88377. * Length of the distance animated by the transition when upper radius is reached
  88378. */
  88379. this.upperRadiusTransitionRange = -2;
  88380. this._autoTransitionRange = false;
  88381. // Animations
  88382. this._radiusIsAnimating = false;
  88383. this._radiusBounceTransition = null;
  88384. this._animatables = new Array();
  88385. }
  88386. Object.defineProperty(BouncingBehavior.prototype, "name", {
  88387. get: function () {
  88388. return "Bouncing";
  88389. },
  88390. enumerable: true,
  88391. configurable: true
  88392. });
  88393. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  88394. /**
  88395. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  88396. */
  88397. get: function () {
  88398. return this._autoTransitionRange;
  88399. },
  88400. /**
  88401. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  88402. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  88403. */
  88404. set: function (value) {
  88405. var _this = this;
  88406. if (this._autoTransitionRange === value) {
  88407. return;
  88408. }
  88409. this._autoTransitionRange = value;
  88410. var camera = this._attachedCamera;
  88411. if (!camera) {
  88412. return;
  88413. }
  88414. if (value) {
  88415. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  88416. if (!mesh) {
  88417. return;
  88418. }
  88419. mesh.computeWorldMatrix(true);
  88420. var diagonal = mesh.getBoundingInfo().diagonalLength;
  88421. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  88422. _this.upperRadiusTransitionRange = diagonal * 0.05;
  88423. });
  88424. }
  88425. else if (this._onMeshTargetChangedObserver) {
  88426. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  88427. }
  88428. },
  88429. enumerable: true,
  88430. configurable: true
  88431. });
  88432. BouncingBehavior.prototype.init = function () {
  88433. // Do notihng
  88434. };
  88435. BouncingBehavior.prototype.attach = function (camera) {
  88436. var _this = this;
  88437. this._attachedCamera = camera;
  88438. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  88439. if (!_this._attachedCamera) {
  88440. return;
  88441. }
  88442. // Add the bounce animation to the lower radius limit
  88443. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  88444. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  88445. }
  88446. // Add the bounce animation to the upper radius limit
  88447. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  88448. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  88449. }
  88450. });
  88451. };
  88452. BouncingBehavior.prototype.detach = function () {
  88453. if (!this._attachedCamera) {
  88454. return;
  88455. }
  88456. if (this._onAfterCheckInputsObserver) {
  88457. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  88458. }
  88459. if (this._onMeshTargetChangedObserver) {
  88460. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  88461. }
  88462. this._attachedCamera = null;
  88463. };
  88464. /**
  88465. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  88466. * @param radiusLimit The limit to check against.
  88467. * @return Bool to indicate if at limit.
  88468. */
  88469. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  88470. if (!this._attachedCamera) {
  88471. return false;
  88472. }
  88473. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  88474. return true;
  88475. }
  88476. return false;
  88477. };
  88478. /**
  88479. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  88480. * @param radiusDelta The delta by which to animate to. Can be negative.
  88481. */
  88482. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  88483. var _this = this;
  88484. if (!this._attachedCamera) {
  88485. return;
  88486. }
  88487. if (!this._radiusBounceTransition) {
  88488. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  88489. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  88490. }
  88491. // Prevent zoom until bounce has completed
  88492. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  88493. this._attachedCamera.wheelPrecision = Infinity;
  88494. this._attachedCamera.inertialRadiusOffset = 0;
  88495. // Animate to the radius limit
  88496. this.stopAllAnimations();
  88497. this._radiusIsAnimating = true;
  88498. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  88499. if (animatable) {
  88500. this._animatables.push(animatable);
  88501. }
  88502. };
  88503. /**
  88504. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  88505. */
  88506. BouncingBehavior.prototype._clearAnimationLocks = function () {
  88507. this._radiusIsAnimating = false;
  88508. if (this._attachedCamera) {
  88509. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  88510. }
  88511. };
  88512. /**
  88513. * Stops and removes all animations that have been applied to the camera
  88514. */
  88515. BouncingBehavior.prototype.stopAllAnimations = function () {
  88516. if (this._attachedCamera) {
  88517. this._attachedCamera.animations = [];
  88518. }
  88519. while (this._animatables.length) {
  88520. this._animatables[0].onAnimationEnd = null;
  88521. this._animatables[0].stop();
  88522. this._animatables.shift();
  88523. }
  88524. };
  88525. /**
  88526. * The easing function used by animations
  88527. */
  88528. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  88529. /**
  88530. * The easing mode used by animations
  88531. */
  88532. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  88533. return BouncingBehavior;
  88534. }());
  88535. BABYLON.BouncingBehavior = BouncingBehavior;
  88536. })(BABYLON || (BABYLON = {}));
  88537. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  88538. var BABYLON;
  88539. (function (BABYLON) {
  88540. var AutoRotationBehavior = /** @class */ (function () {
  88541. function AutoRotationBehavior() {
  88542. this._zoomStopsAnimation = false;
  88543. this._idleRotationSpeed = 0.05;
  88544. this._idleRotationWaitTime = 2000;
  88545. this._idleRotationSpinupTime = 2000;
  88546. this._isPointerDown = false;
  88547. this._lastFrameTime = null;
  88548. this._lastInteractionTime = -Infinity;
  88549. this._cameraRotationSpeed = 0;
  88550. this._lastFrameRadius = 0;
  88551. }
  88552. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  88553. get: function () {
  88554. return "AutoRotation";
  88555. },
  88556. enumerable: true,
  88557. configurable: true
  88558. });
  88559. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  88560. /**
  88561. * Gets the flag that indicates if user zooming should stop animation.
  88562. */
  88563. get: function () {
  88564. return this._zoomStopsAnimation;
  88565. },
  88566. /**
  88567. * Sets the flag that indicates if user zooming should stop animation.
  88568. */
  88569. set: function (flag) {
  88570. this._zoomStopsAnimation = flag;
  88571. },
  88572. enumerable: true,
  88573. configurable: true
  88574. });
  88575. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  88576. /**
  88577. * Gets the default speed at which the camera rotates around the model.
  88578. */
  88579. get: function () {
  88580. return this._idleRotationSpeed;
  88581. },
  88582. /**
  88583. * Sets the default speed at which the camera rotates around the model.
  88584. */
  88585. set: function (speed) {
  88586. this._idleRotationSpeed = speed;
  88587. },
  88588. enumerable: true,
  88589. configurable: true
  88590. });
  88591. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  88592. /**
  88593. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  88594. */
  88595. get: function () {
  88596. return this._idleRotationWaitTime;
  88597. },
  88598. /**
  88599. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  88600. */
  88601. set: function (time) {
  88602. this._idleRotationWaitTime = time;
  88603. },
  88604. enumerable: true,
  88605. configurable: true
  88606. });
  88607. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  88608. /**
  88609. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  88610. */
  88611. get: function () {
  88612. return this._idleRotationSpinupTime;
  88613. },
  88614. /**
  88615. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  88616. */
  88617. set: function (time) {
  88618. this._idleRotationSpinupTime = time;
  88619. },
  88620. enumerable: true,
  88621. configurable: true
  88622. });
  88623. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  88624. /**
  88625. * Gets a value indicating if the camera is currently rotating because of this behavior
  88626. */
  88627. get: function () {
  88628. return Math.abs(this._cameraRotationSpeed) > 0;
  88629. },
  88630. enumerable: true,
  88631. configurable: true
  88632. });
  88633. AutoRotationBehavior.prototype.init = function () {
  88634. // Do notihng
  88635. };
  88636. AutoRotationBehavior.prototype.attach = function (camera) {
  88637. var _this = this;
  88638. this._attachedCamera = camera;
  88639. var scene = this._attachedCamera.getScene();
  88640. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  88641. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  88642. _this._isPointerDown = true;
  88643. return;
  88644. }
  88645. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  88646. _this._isPointerDown = false;
  88647. }
  88648. });
  88649. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  88650. var now = BABYLON.Tools.Now;
  88651. var dt = 0;
  88652. if (_this._lastFrameTime != null) {
  88653. dt = now - _this._lastFrameTime;
  88654. }
  88655. _this._lastFrameTime = now;
  88656. // Stop the animation if there is user interaction and the animation should stop for this interaction
  88657. _this._applyUserInteraction();
  88658. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  88659. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  88660. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  88661. // Step camera rotation by rotation speed
  88662. if (_this._attachedCamera) {
  88663. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  88664. }
  88665. });
  88666. };
  88667. AutoRotationBehavior.prototype.detach = function () {
  88668. if (!this._attachedCamera) {
  88669. return;
  88670. }
  88671. var scene = this._attachedCamera.getScene();
  88672. if (this._onPrePointerObservableObserver) {
  88673. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  88674. }
  88675. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  88676. this._attachedCamera = null;
  88677. };
  88678. /**
  88679. * Returns true if user is scrolling.
  88680. * @return true if user is scrolling.
  88681. */
  88682. AutoRotationBehavior.prototype._userIsZooming = function () {
  88683. if (!this._attachedCamera) {
  88684. return false;
  88685. }
  88686. return this._attachedCamera.inertialRadiusOffset !== 0;
  88687. };
  88688. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  88689. if (!this._attachedCamera) {
  88690. return false;
  88691. }
  88692. var zoomHasHitLimit = false;
  88693. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  88694. zoomHasHitLimit = true;
  88695. }
  88696. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  88697. this._lastFrameRadius = this._attachedCamera.radius;
  88698. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  88699. };
  88700. /**
  88701. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  88702. */
  88703. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  88704. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  88705. this._lastInteractionTime = BABYLON.Tools.Now;
  88706. }
  88707. };
  88708. // Tools
  88709. AutoRotationBehavior.prototype._userIsMoving = function () {
  88710. if (!this._attachedCamera) {
  88711. return false;
  88712. }
  88713. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  88714. this._attachedCamera.inertialBetaOffset !== 0 ||
  88715. this._attachedCamera.inertialRadiusOffset !== 0 ||
  88716. this._attachedCamera.inertialPanningX !== 0 ||
  88717. this._attachedCamera.inertialPanningY !== 0 ||
  88718. this._isPointerDown;
  88719. };
  88720. return AutoRotationBehavior;
  88721. }());
  88722. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  88723. })(BABYLON || (BABYLON = {}));
  88724. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  88725. var BABYLON;
  88726. (function (BABYLON) {
  88727. var NullEngineOptions = /** @class */ (function () {
  88728. function NullEngineOptions() {
  88729. this.renderWidth = 512;
  88730. this.renderHeight = 256;
  88731. this.textureSize = 512;
  88732. this.deterministicLockstep = false;
  88733. this.lockstepMaxSteps = 4;
  88734. }
  88735. return NullEngineOptions;
  88736. }());
  88737. BABYLON.NullEngineOptions = NullEngineOptions;
  88738. /**
  88739. * The null engine class provides support for headless version of babylon.js.
  88740. * This can be used in server side scenario or for testing purposes
  88741. */
  88742. var NullEngine = /** @class */ (function (_super) {
  88743. __extends(NullEngine, _super);
  88744. function NullEngine(options) {
  88745. if (options === void 0) { options = new NullEngineOptions(); }
  88746. var _this = _super.call(this, null) || this;
  88747. if (options.deterministicLockstep === undefined) {
  88748. options.deterministicLockstep = false;
  88749. }
  88750. if (options.lockstepMaxSteps === undefined) {
  88751. options.lockstepMaxSteps = 4;
  88752. }
  88753. _this._options = options;
  88754. // Init caps
  88755. // We consider we are on a webgl1 capable device
  88756. _this._caps = new BABYLON.EngineCapabilities();
  88757. _this._caps.maxTexturesImageUnits = 16;
  88758. _this._caps.maxVertexTextureImageUnits = 16;
  88759. _this._caps.maxTextureSize = 512;
  88760. _this._caps.maxCubemapTextureSize = 512;
  88761. _this._caps.maxRenderTextureSize = 512;
  88762. _this._caps.maxVertexAttribs = 16;
  88763. _this._caps.maxVaryingVectors = 16;
  88764. _this._caps.maxFragmentUniformVectors = 16;
  88765. _this._caps.maxVertexUniformVectors = 16;
  88766. // Extensions
  88767. _this._caps.standardDerivatives = false;
  88768. _this._caps.astc = null;
  88769. _this._caps.s3tc = null;
  88770. _this._caps.pvrtc = null;
  88771. _this._caps.etc1 = null;
  88772. _this._caps.etc2 = null;
  88773. _this._caps.textureAnisotropicFilterExtension = null;
  88774. _this._caps.maxAnisotropy = 0;
  88775. _this._caps.uintIndices = false;
  88776. _this._caps.fragmentDepthSupported = false;
  88777. _this._caps.highPrecisionShaderSupported = true;
  88778. _this._caps.colorBufferFloat = false;
  88779. _this._caps.textureFloat = false;
  88780. _this._caps.textureFloatLinearFiltering = false;
  88781. _this._caps.textureFloatRender = false;
  88782. _this._caps.textureHalfFloat = false;
  88783. _this._caps.textureHalfFloatLinearFiltering = false;
  88784. _this._caps.textureHalfFloatRender = false;
  88785. _this._caps.textureLOD = false;
  88786. _this._caps.drawBuffersExtension = false;
  88787. _this._caps.depthTextureExtension = false;
  88788. _this._caps.vertexArrayObject = false;
  88789. _this._caps.instancedArrays = false;
  88790. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  88791. // Wrappers
  88792. if (typeof URL === "undefined") {
  88793. URL = {
  88794. createObjectURL: function () { },
  88795. revokeObjectURL: function () { }
  88796. };
  88797. }
  88798. if (typeof Blob === "undefined") {
  88799. Blob = function () { };
  88800. }
  88801. return _this;
  88802. }
  88803. NullEngine.prototype.isDeterministicLockStep = function () {
  88804. return this._options.deterministicLockstep;
  88805. };
  88806. NullEngine.prototype.getLockstepMaxSteps = function () {
  88807. return this._options.lockstepMaxSteps;
  88808. };
  88809. NullEngine.prototype.getHardwareScalingLevel = function () {
  88810. return 1.0;
  88811. };
  88812. NullEngine.prototype.createVertexBuffer = function (vertices) {
  88813. return {
  88814. capacity: 0,
  88815. references: 1,
  88816. is32Bits: false
  88817. };
  88818. };
  88819. NullEngine.prototype.createIndexBuffer = function (indices) {
  88820. return {
  88821. capacity: 0,
  88822. references: 1,
  88823. is32Bits: false
  88824. };
  88825. };
  88826. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  88827. if (stencil === void 0) { stencil = false; }
  88828. };
  88829. NullEngine.prototype.getRenderWidth = function (useScreen) {
  88830. if (useScreen === void 0) { useScreen = false; }
  88831. if (!useScreen && this._currentRenderTarget) {
  88832. return this._currentRenderTarget.width;
  88833. }
  88834. return this._options.renderWidth;
  88835. };
  88836. NullEngine.prototype.getRenderHeight = function (useScreen) {
  88837. if (useScreen === void 0) { useScreen = false; }
  88838. if (!useScreen && this._currentRenderTarget) {
  88839. return this._currentRenderTarget.height;
  88840. }
  88841. return this._options.renderHeight;
  88842. };
  88843. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  88844. this._cachedViewport = viewport;
  88845. };
  88846. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  88847. return {
  88848. transformFeedback: null,
  88849. __SPECTOR_rebuildProgram: null
  88850. };
  88851. };
  88852. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  88853. return [];
  88854. };
  88855. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  88856. return [];
  88857. };
  88858. NullEngine.prototype.bindSamplers = function (effect) {
  88859. this._currentEffect = null;
  88860. };
  88861. NullEngine.prototype.enableEffect = function (effect) {
  88862. this._currentEffect = effect;
  88863. if (effect.onBind) {
  88864. effect.onBind(effect);
  88865. }
  88866. effect.onBindObservable.notifyObservers(effect);
  88867. };
  88868. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  88869. if (zOffset === void 0) { zOffset = 0; }
  88870. if (reverseSide === void 0) { reverseSide = false; }
  88871. };
  88872. NullEngine.prototype.setIntArray = function (uniform, array) {
  88873. };
  88874. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  88875. };
  88876. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  88877. };
  88878. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  88879. };
  88880. NullEngine.prototype.setFloatArray = function (uniform, array) {
  88881. };
  88882. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  88883. };
  88884. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  88885. };
  88886. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  88887. };
  88888. NullEngine.prototype.setArray = function (uniform, array) {
  88889. };
  88890. NullEngine.prototype.setArray2 = function (uniform, array) {
  88891. };
  88892. NullEngine.prototype.setArray3 = function (uniform, array) {
  88893. };
  88894. NullEngine.prototype.setArray4 = function (uniform, array) {
  88895. };
  88896. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  88897. };
  88898. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  88899. };
  88900. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  88901. };
  88902. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  88903. };
  88904. NullEngine.prototype.setFloat = function (uniform, value) {
  88905. };
  88906. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  88907. };
  88908. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  88909. };
  88910. NullEngine.prototype.setBool = function (uniform, bool) {
  88911. };
  88912. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  88913. };
  88914. NullEngine.prototype.setColor3 = function (uniform, color3) {
  88915. };
  88916. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  88917. };
  88918. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  88919. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  88920. if (this._alphaMode === mode) {
  88921. return;
  88922. }
  88923. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  88924. if (!noDepthWriteChange) {
  88925. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  88926. }
  88927. this._alphaMode = mode;
  88928. };
  88929. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  88930. };
  88931. NullEngine.prototype.wipeCaches = function (bruteForce) {
  88932. if (this.preventCacheWipeBetweenFrames) {
  88933. return;
  88934. }
  88935. this.resetTextureCache();
  88936. this._currentEffect = null;
  88937. if (bruteForce) {
  88938. this._currentProgram = null;
  88939. this._stencilState.reset();
  88940. this._depthCullingState.reset();
  88941. this._alphaState.reset();
  88942. }
  88943. this._cachedVertexBuffers = null;
  88944. this._cachedIndexBuffer = null;
  88945. this._cachedEffectForVertexBuffers = null;
  88946. };
  88947. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  88948. };
  88949. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  88950. };
  88951. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  88952. };
  88953. NullEngine.prototype._createTexture = function () {
  88954. return {};
  88955. };
  88956. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  88957. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  88958. if (onLoad === void 0) { onLoad = null; }
  88959. if (onError === void 0) { onError = null; }
  88960. if (buffer === void 0) { buffer = null; }
  88961. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  88962. var url = String(urlArg);
  88963. texture.url = url;
  88964. texture.generateMipMaps = !noMipmap;
  88965. texture.samplingMode = samplingMode;
  88966. texture.invertY = invertY;
  88967. texture.baseWidth = this._options.textureSize;
  88968. texture.baseHeight = this._options.textureSize;
  88969. texture.width = this._options.textureSize;
  88970. texture.height = this._options.textureSize;
  88971. if (format) {
  88972. texture.format = format;
  88973. }
  88974. texture.isReady = true;
  88975. if (onLoad) {
  88976. onLoad();
  88977. }
  88978. return texture;
  88979. };
  88980. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  88981. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  88982. if (options !== undefined && typeof options === "object") {
  88983. fullOptions.generateMipMaps = options.generateMipMaps;
  88984. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  88985. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  88986. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  88987. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  88988. }
  88989. else {
  88990. fullOptions.generateMipMaps = options;
  88991. fullOptions.generateDepthBuffer = true;
  88992. fullOptions.generateStencilBuffer = false;
  88993. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  88994. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  88995. }
  88996. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  88997. var width = size.width || size;
  88998. var height = size.height || size;
  88999. texture._depthStencilBuffer = {};
  89000. texture._framebuffer = {};
  89001. texture.baseWidth = width;
  89002. texture.baseHeight = height;
  89003. texture.width = width;
  89004. texture.height = height;
  89005. texture.isReady = true;
  89006. texture.samples = 1;
  89007. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  89008. texture.samplingMode = fullOptions.samplingMode;
  89009. texture.type = fullOptions.type;
  89010. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  89011. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  89012. return texture;
  89013. };
  89014. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  89015. texture.samplingMode = samplingMode;
  89016. };
  89017. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  89018. if (this._currentRenderTarget) {
  89019. this.unBindFramebuffer(this._currentRenderTarget);
  89020. }
  89021. this._currentRenderTarget = texture;
  89022. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  89023. if (this._cachedViewport && !forceFullscreenViewport) {
  89024. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  89025. }
  89026. };
  89027. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  89028. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  89029. this._currentRenderTarget = null;
  89030. if (onBeforeUnbind) {
  89031. if (texture._MSAAFramebuffer) {
  89032. this._currentFramebuffer = texture._framebuffer;
  89033. }
  89034. onBeforeUnbind();
  89035. }
  89036. this._currentFramebuffer = null;
  89037. };
  89038. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  89039. var vbo = {
  89040. capacity: 1,
  89041. references: 1,
  89042. is32Bits: false
  89043. };
  89044. return vbo;
  89045. };
  89046. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  89047. if (offset === void 0) { offset = 0; }
  89048. };
  89049. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  89050. };
  89051. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  89052. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  89053. this._boundTexturesCache[this._activeChannel] = texture;
  89054. }
  89055. };
  89056. NullEngine.prototype._bindTexture = function (channel, texture) {
  89057. if (channel < 0) {
  89058. return;
  89059. }
  89060. this._bindTextureDirectly(0, texture);
  89061. };
  89062. NullEngine.prototype._releaseBuffer = function (buffer) {
  89063. buffer.references--;
  89064. if (buffer.references === 0) {
  89065. return true;
  89066. }
  89067. return false;
  89068. };
  89069. return NullEngine;
  89070. }(BABYLON.Engine));
  89071. BABYLON.NullEngine = NullEngine;
  89072. })(BABYLON || (BABYLON = {}));
  89073. //# sourceMappingURL=babylon.nullEngine.js.map
  89074. var BABYLON;
  89075. (function (BABYLON) {
  89076. /**
  89077. * This class can be used to get instrumentation data from a Babylon engine
  89078. */
  89079. var EngineInstrumentation = /** @class */ (function () {
  89080. function EngineInstrumentation(engine) {
  89081. this.engine = engine;
  89082. this._captureGPUFrameTime = false;
  89083. this._gpuFrameTime = new BABYLON.PerfCounter();
  89084. this._captureShaderCompilationTime = false;
  89085. this._shaderCompilationTime = new BABYLON.PerfCounter();
  89086. // Observers
  89087. this._onBeginFrameObserver = null;
  89088. this._onEndFrameObserver = null;
  89089. this._onBeforeShaderCompilationObserver = null;
  89090. this._onAfterShaderCompilationObserver = null;
  89091. }
  89092. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  89093. // Properties
  89094. /**
  89095. * Gets the perf counter used for GPU frame time
  89096. */
  89097. get: function () {
  89098. return this._gpuFrameTime;
  89099. },
  89100. enumerable: true,
  89101. configurable: true
  89102. });
  89103. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  89104. /**
  89105. * Gets the GPU frame time capture status
  89106. */
  89107. get: function () {
  89108. return this._captureGPUFrameTime;
  89109. },
  89110. /**
  89111. * Enable or disable the GPU frame time capture
  89112. */
  89113. set: function (value) {
  89114. var _this = this;
  89115. if (value === this._captureGPUFrameTime) {
  89116. return;
  89117. }
  89118. this._captureGPUFrameTime = value;
  89119. if (value) {
  89120. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  89121. if (!_this._gpuFrameTimeToken) {
  89122. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  89123. }
  89124. });
  89125. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  89126. if (!_this._gpuFrameTimeToken) {
  89127. return;
  89128. }
  89129. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  89130. if (time > -1) {
  89131. _this._gpuFrameTimeToken = null;
  89132. _this._gpuFrameTime.fetchNewFrame();
  89133. _this._gpuFrameTime.addCount(time, true);
  89134. }
  89135. });
  89136. }
  89137. else {
  89138. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  89139. this._onBeginFrameObserver = null;
  89140. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  89141. this._onEndFrameObserver = null;
  89142. }
  89143. },
  89144. enumerable: true,
  89145. configurable: true
  89146. });
  89147. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  89148. /**
  89149. * Gets the perf counter used for shader compilation time
  89150. */
  89151. get: function () {
  89152. return this._shaderCompilationTime;
  89153. },
  89154. enumerable: true,
  89155. configurable: true
  89156. });
  89157. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  89158. /**
  89159. * Gets the shader compilation time capture status
  89160. */
  89161. get: function () {
  89162. return this._captureShaderCompilationTime;
  89163. },
  89164. /**
  89165. * Enable or disable the shader compilation time capture
  89166. */
  89167. set: function (value) {
  89168. var _this = this;
  89169. if (value === this._captureShaderCompilationTime) {
  89170. return;
  89171. }
  89172. this._captureShaderCompilationTime = value;
  89173. if (value) {
  89174. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  89175. _this._shaderCompilationTime.fetchNewFrame();
  89176. _this._shaderCompilationTime.beginMonitoring();
  89177. });
  89178. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  89179. _this._shaderCompilationTime.endMonitoring();
  89180. });
  89181. }
  89182. else {
  89183. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  89184. this._onBeforeShaderCompilationObserver = null;
  89185. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  89186. this._onAfterShaderCompilationObserver = null;
  89187. }
  89188. },
  89189. enumerable: true,
  89190. configurable: true
  89191. });
  89192. EngineInstrumentation.prototype.dispose = function () {
  89193. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  89194. this._onBeginFrameObserver = null;
  89195. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  89196. this._onEndFrameObserver = null;
  89197. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  89198. this._onBeforeShaderCompilationObserver = null;
  89199. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  89200. this._onAfterShaderCompilationObserver = null;
  89201. this.engine = null;
  89202. };
  89203. return EngineInstrumentation;
  89204. }());
  89205. BABYLON.EngineInstrumentation = EngineInstrumentation;
  89206. })(BABYLON || (BABYLON = {}));
  89207. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  89208. var BABYLON;
  89209. (function (BABYLON) {
  89210. /**
  89211. * This class can be used to get instrumentation data from a Babylon engine
  89212. */
  89213. var SceneInstrumentation = /** @class */ (function () {
  89214. function SceneInstrumentation(scene) {
  89215. var _this = this;
  89216. this.scene = scene;
  89217. this._captureActiveMeshesEvaluationTime = false;
  89218. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  89219. this._captureRenderTargetsRenderTime = false;
  89220. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  89221. this._captureFrameTime = false;
  89222. this._frameTime = new BABYLON.PerfCounter();
  89223. this._captureRenderTime = false;
  89224. this._renderTime = new BABYLON.PerfCounter();
  89225. this._captureInterFrameTime = false;
  89226. this._interFrameTime = new BABYLON.PerfCounter();
  89227. this._captureParticlesRenderTime = false;
  89228. this._particlesRenderTime = new BABYLON.PerfCounter();
  89229. this._captureSpritesRenderTime = false;
  89230. this._spritesRenderTime = new BABYLON.PerfCounter();
  89231. this._capturePhysicsTime = false;
  89232. this._physicsTime = new BABYLON.PerfCounter();
  89233. this._captureAnimationsTime = false;
  89234. this._animationsTime = new BABYLON.PerfCounter();
  89235. // Observers
  89236. this._onBeforeActiveMeshesEvaluationObserver = null;
  89237. this._onAfterActiveMeshesEvaluationObserver = null;
  89238. this._onBeforeRenderTargetsRenderObserver = null;
  89239. this._onAfterRenderTargetsRenderObserver = null;
  89240. this._onAfterRenderObserver = null;
  89241. this._onBeforeDrawPhaseObserver = null;
  89242. this._onAfterDrawPhaseObserver = null;
  89243. this._onBeforeAnimationsObserver = null;
  89244. this._onBeforeParticlesRenderingObserver = null;
  89245. this._onAfterParticlesRenderingObserver = null;
  89246. this._onBeforeSpritesRenderingObserver = null;
  89247. this._onAfterSpritesRenderingObserver = null;
  89248. this._onBeforePhysicsObserver = null;
  89249. this._onAfterPhysicsObserver = null;
  89250. this._onAfterAnimationsObserver = null;
  89251. // Before render
  89252. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  89253. if (_this._captureActiveMeshesEvaluationTime) {
  89254. _this._activeMeshesEvaluationTime.fetchNewFrame();
  89255. }
  89256. if (_this._captureRenderTargetsRenderTime) {
  89257. _this._renderTargetsRenderTime.fetchNewFrame();
  89258. }
  89259. if (_this._captureFrameTime) {
  89260. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  89261. _this._frameTime.beginMonitoring();
  89262. }
  89263. if (_this._captureInterFrameTime) {
  89264. _this._interFrameTime.endMonitoring();
  89265. }
  89266. if (_this._captureParticlesRenderTime) {
  89267. _this._particlesRenderTime.fetchNewFrame();
  89268. }
  89269. if (_this._captureSpritesRenderTime) {
  89270. _this._spritesRenderTime.fetchNewFrame();
  89271. }
  89272. if (_this._captureAnimationsTime) {
  89273. _this._animationsTime.beginMonitoring();
  89274. }
  89275. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  89276. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  89277. });
  89278. // After render
  89279. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  89280. if (_this._captureFrameTime) {
  89281. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  89282. _this._frameTime.endMonitoring();
  89283. }
  89284. if (_this._captureRenderTime) {
  89285. _this._renderTime.endMonitoring(false);
  89286. }
  89287. if (_this._captureInterFrameTime) {
  89288. _this._interFrameTime.beginMonitoring();
  89289. }
  89290. });
  89291. }
  89292. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  89293. // Properties
  89294. /**
  89295. * Gets the perf counter used for active meshes evaluation time
  89296. */
  89297. get: function () {
  89298. return this._activeMeshesEvaluationTime;
  89299. },
  89300. enumerable: true,
  89301. configurable: true
  89302. });
  89303. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  89304. /**
  89305. * Gets the active meshes evaluation time capture status
  89306. */
  89307. get: function () {
  89308. return this._captureActiveMeshesEvaluationTime;
  89309. },
  89310. /**
  89311. * Enable or disable the active meshes evaluation time capture
  89312. */
  89313. set: function (value) {
  89314. var _this = this;
  89315. if (value === this._captureActiveMeshesEvaluationTime) {
  89316. return;
  89317. }
  89318. this._captureActiveMeshesEvaluationTime = value;
  89319. if (value) {
  89320. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  89321. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  89322. _this._activeMeshesEvaluationTime.beginMonitoring();
  89323. });
  89324. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  89325. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  89326. _this._activeMeshesEvaluationTime.endMonitoring();
  89327. });
  89328. }
  89329. else {
  89330. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  89331. this._onBeforeActiveMeshesEvaluationObserver = null;
  89332. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  89333. this._onAfterActiveMeshesEvaluationObserver = null;
  89334. }
  89335. },
  89336. enumerable: true,
  89337. configurable: true
  89338. });
  89339. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  89340. /**
  89341. * Gets the perf counter used for render targets render time
  89342. */
  89343. get: function () {
  89344. return this._renderTargetsRenderTime;
  89345. },
  89346. enumerable: true,
  89347. configurable: true
  89348. });
  89349. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  89350. /**
  89351. * Gets the render targets render time capture status
  89352. */
  89353. get: function () {
  89354. return this._captureRenderTargetsRenderTime;
  89355. },
  89356. /**
  89357. * Enable or disable the render targets render time capture
  89358. */
  89359. set: function (value) {
  89360. var _this = this;
  89361. if (value === this._captureRenderTargetsRenderTime) {
  89362. return;
  89363. }
  89364. this._captureRenderTargetsRenderTime = value;
  89365. if (value) {
  89366. this._onBeforeRenderTargetsRenderObserver = this.scene.OnBeforeRenderTargetsRenderObservable.add(function () {
  89367. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  89368. _this._renderTargetsRenderTime.beginMonitoring();
  89369. });
  89370. this._onAfterRenderTargetsRenderObserver = this.scene.OnAfterRenderTargetsRenderObservable.add(function () {
  89371. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  89372. _this._renderTargetsRenderTime.endMonitoring(false);
  89373. });
  89374. }
  89375. else {
  89376. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  89377. this._onBeforeRenderTargetsRenderObserver = null;
  89378. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  89379. this._onAfterRenderTargetsRenderObserver = null;
  89380. }
  89381. },
  89382. enumerable: true,
  89383. configurable: true
  89384. });
  89385. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  89386. /**
  89387. * Gets the perf counter used for particles render time
  89388. */
  89389. get: function () {
  89390. return this._particlesRenderTime;
  89391. },
  89392. enumerable: true,
  89393. configurable: true
  89394. });
  89395. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  89396. /**
  89397. * Gets the particles render time capture status
  89398. */
  89399. get: function () {
  89400. return this._captureParticlesRenderTime;
  89401. },
  89402. /**
  89403. * Enable or disable the particles render time capture
  89404. */
  89405. set: function (value) {
  89406. var _this = this;
  89407. if (value === this._captureParticlesRenderTime) {
  89408. return;
  89409. }
  89410. this._captureParticlesRenderTime = value;
  89411. if (value) {
  89412. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  89413. BABYLON.Tools.StartPerformanceCounter("Particles");
  89414. _this._particlesRenderTime.beginMonitoring();
  89415. });
  89416. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  89417. BABYLON.Tools.EndPerformanceCounter("Particles");
  89418. _this._particlesRenderTime.endMonitoring(false);
  89419. });
  89420. }
  89421. else {
  89422. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  89423. this._onBeforeParticlesRenderingObserver = null;
  89424. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  89425. this._onAfterParticlesRenderingObserver = null;
  89426. }
  89427. },
  89428. enumerable: true,
  89429. configurable: true
  89430. });
  89431. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  89432. /**
  89433. * Gets the perf counter used for sprites render time
  89434. */
  89435. get: function () {
  89436. return this._spritesRenderTime;
  89437. },
  89438. enumerable: true,
  89439. configurable: true
  89440. });
  89441. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  89442. /**
  89443. * Gets the sprites render time capture status
  89444. */
  89445. get: function () {
  89446. return this._captureSpritesRenderTime;
  89447. },
  89448. /**
  89449. * Enable or disable the sprites render time capture
  89450. */
  89451. set: function (value) {
  89452. var _this = this;
  89453. if (value === this._captureSpritesRenderTime) {
  89454. return;
  89455. }
  89456. this._captureSpritesRenderTime = value;
  89457. if (value) {
  89458. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  89459. BABYLON.Tools.StartPerformanceCounter("Sprites");
  89460. _this._spritesRenderTime.beginMonitoring();
  89461. });
  89462. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  89463. BABYLON.Tools.EndPerformanceCounter("Sprites");
  89464. _this._spritesRenderTime.endMonitoring(false);
  89465. });
  89466. }
  89467. else {
  89468. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  89469. this._onBeforeSpritesRenderingObserver = null;
  89470. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  89471. this._onAfterSpritesRenderingObserver = null;
  89472. }
  89473. },
  89474. enumerable: true,
  89475. configurable: true
  89476. });
  89477. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  89478. /**
  89479. * Gets the perf counter used for physics time
  89480. */
  89481. get: function () {
  89482. return this._physicsTime;
  89483. },
  89484. enumerable: true,
  89485. configurable: true
  89486. });
  89487. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  89488. /**
  89489. * Gets the physics time capture status
  89490. */
  89491. get: function () {
  89492. return this._capturePhysicsTime;
  89493. },
  89494. /**
  89495. * Enable or disable the physics time capture
  89496. */
  89497. set: function (value) {
  89498. var _this = this;
  89499. if (value === this._capturePhysicsTime) {
  89500. return;
  89501. }
  89502. this._capturePhysicsTime = value;
  89503. if (value) {
  89504. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  89505. BABYLON.Tools.StartPerformanceCounter("Physics");
  89506. _this._physicsTime.beginMonitoring();
  89507. });
  89508. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  89509. BABYLON.Tools.EndPerformanceCounter("Physics");
  89510. _this._physicsTime.endMonitoring();
  89511. });
  89512. }
  89513. else {
  89514. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  89515. this._onBeforePhysicsObserver = null;
  89516. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  89517. this._onAfterPhysicsObserver = null;
  89518. }
  89519. },
  89520. enumerable: true,
  89521. configurable: true
  89522. });
  89523. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  89524. /**
  89525. * Gets the perf counter used for animations time
  89526. */
  89527. get: function () {
  89528. return this._animationsTime;
  89529. },
  89530. enumerable: true,
  89531. configurable: true
  89532. });
  89533. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  89534. /**
  89535. * Gets the animations time capture status
  89536. */
  89537. get: function () {
  89538. return this._captureAnimationsTime;
  89539. },
  89540. /**
  89541. * Enable or disable the animations time capture
  89542. */
  89543. set: function (value) {
  89544. var _this = this;
  89545. if (value === this._captureAnimationsTime) {
  89546. return;
  89547. }
  89548. this._captureAnimationsTime = value;
  89549. if (value) {
  89550. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  89551. _this._animationsTime.endMonitoring();
  89552. });
  89553. }
  89554. else {
  89555. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  89556. this._onAfterAnimationsObserver = null;
  89557. }
  89558. },
  89559. enumerable: true,
  89560. configurable: true
  89561. });
  89562. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  89563. /**
  89564. * Gets the perf counter used for frame time capture
  89565. */
  89566. get: function () {
  89567. return this._frameTime;
  89568. },
  89569. enumerable: true,
  89570. configurable: true
  89571. });
  89572. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  89573. /**
  89574. * Gets the frame time capture status
  89575. */
  89576. get: function () {
  89577. return this._captureFrameTime;
  89578. },
  89579. /**
  89580. * Enable or disable the frame time capture
  89581. */
  89582. set: function (value) {
  89583. this._captureFrameTime = value;
  89584. },
  89585. enumerable: true,
  89586. configurable: true
  89587. });
  89588. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  89589. /**
  89590. * Gets the perf counter used for inter-frames time capture
  89591. */
  89592. get: function () {
  89593. return this._interFrameTime;
  89594. },
  89595. enumerable: true,
  89596. configurable: true
  89597. });
  89598. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  89599. /**
  89600. * Gets the inter-frames time capture status
  89601. */
  89602. get: function () {
  89603. return this._captureInterFrameTime;
  89604. },
  89605. /**
  89606. * Enable or disable the inter-frames time capture
  89607. */
  89608. set: function (value) {
  89609. this._captureInterFrameTime = value;
  89610. },
  89611. enumerable: true,
  89612. configurable: true
  89613. });
  89614. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  89615. /**
  89616. * Gets the perf counter used for render time capture
  89617. */
  89618. get: function () {
  89619. return this._renderTime;
  89620. },
  89621. enumerable: true,
  89622. configurable: true
  89623. });
  89624. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  89625. /**
  89626. * Gets the render time capture status
  89627. */
  89628. get: function () {
  89629. return this._captureRenderTime;
  89630. },
  89631. /**
  89632. * Enable or disable the render time capture
  89633. */
  89634. set: function (value) {
  89635. var _this = this;
  89636. if (value === this._captureRenderTime) {
  89637. return;
  89638. }
  89639. this._captureRenderTime = value;
  89640. if (value) {
  89641. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  89642. _this._renderTime.beginMonitoring();
  89643. BABYLON.Tools.StartPerformanceCounter("Main render");
  89644. });
  89645. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  89646. _this._renderTime.endMonitoring(false);
  89647. BABYLON.Tools.EndPerformanceCounter("Main render");
  89648. });
  89649. }
  89650. else {
  89651. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  89652. this._onBeforeDrawPhaseObserver = null;
  89653. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  89654. this._onAfterDrawPhaseObserver = null;
  89655. }
  89656. },
  89657. enumerable: true,
  89658. configurable: true
  89659. });
  89660. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  89661. /**
  89662. * Gets the perf counter used for draw calls
  89663. */
  89664. get: function () {
  89665. return this.scene.getEngine()._drawCalls;
  89666. },
  89667. enumerable: true,
  89668. configurable: true
  89669. });
  89670. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  89671. /**
  89672. * Gets the perf counter used for texture collisions
  89673. */
  89674. get: function () {
  89675. return this.scene.getEngine()._textureCollisions;
  89676. },
  89677. enumerable: true,
  89678. configurable: true
  89679. });
  89680. SceneInstrumentation.prototype.dispose = function () {
  89681. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  89682. this._onAfterRenderObserver = null;
  89683. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  89684. this._onBeforeActiveMeshesEvaluationObserver = null;
  89685. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  89686. this._onAfterActiveMeshesEvaluationObserver = null;
  89687. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  89688. this._onBeforeRenderTargetsRenderObserver = null;
  89689. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  89690. this._onAfterRenderTargetsRenderObserver = null;
  89691. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  89692. this._onBeforeAnimationsObserver = null;
  89693. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  89694. this._onBeforeParticlesRenderingObserver = null;
  89695. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  89696. this._onAfterParticlesRenderingObserver = null;
  89697. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  89698. this._onBeforeSpritesRenderingObserver = null;
  89699. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  89700. this._onAfterSpritesRenderingObserver = null;
  89701. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  89702. this._onBeforeDrawPhaseObserver = null;
  89703. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  89704. this._onAfterDrawPhaseObserver = null;
  89705. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  89706. this._onBeforePhysicsObserver = null;
  89707. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  89708. this._onAfterPhysicsObserver = null;
  89709. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  89710. this._onAfterAnimationsObserver = null;
  89711. this.scene = null;
  89712. };
  89713. return SceneInstrumentation;
  89714. }());
  89715. BABYLON.SceneInstrumentation = SceneInstrumentation;
  89716. })(BABYLON || (BABYLON = {}));
  89717. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  89718. var BABYLON;
  89719. (function (BABYLON) {
  89720. var _TimeToken = /** @class */ (function () {
  89721. function _TimeToken() {
  89722. this._timeElapsedQueryEnded = false;
  89723. }
  89724. return _TimeToken;
  89725. }());
  89726. BABYLON._TimeToken = _TimeToken;
  89727. })(BABYLON || (BABYLON = {}));
  89728. //# sourceMappingURL=babylon.timeToken.js.map
  89729. var BABYLON;
  89730. (function (BABYLON) {
  89731. /**
  89732. * Background material defines definition.
  89733. * @ignore Mainly internal Use
  89734. */
  89735. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  89736. __extends(BackgroundMaterialDefines, _super);
  89737. /**
  89738. * Constructor of the defines.
  89739. */
  89740. function BackgroundMaterialDefines() {
  89741. var _this = _super.call(this) || this;
  89742. /**
  89743. * True if the diffuse texture is in use.
  89744. */
  89745. _this.DIFFUSE = false;
  89746. /**
  89747. * The direct UV channel to use.
  89748. */
  89749. _this.DIFFUSEDIRECTUV = 0;
  89750. /**
  89751. * True if the diffuse texture is in gamma space.
  89752. */
  89753. _this.GAMMADIFFUSE = false;
  89754. /**
  89755. * True if the diffuse texture has opacity in the alpha channel.
  89756. */
  89757. _this.DIFFUSEHASALPHA = false;
  89758. /**
  89759. * True if you want the material to fade to transparent at grazing angle.
  89760. */
  89761. _this.OPACITYFRESNEL = false;
  89762. /**
  89763. * True if an extra blur needs to be added in the reflection.
  89764. */
  89765. _this.REFLECTIONBLUR = false;
  89766. /**
  89767. * True if you want the material to fade to reflection at grazing angle.
  89768. */
  89769. _this.REFLECTIONFRESNEL = false;
  89770. /**
  89771. * True if you want the material to falloff as far as you move away from the scene center.
  89772. */
  89773. _this.REFLECTIONFALLOFF = false;
  89774. /**
  89775. * False if the current Webgl implementation does not support the texture lod extension.
  89776. */
  89777. _this.TEXTURELODSUPPORT = false;
  89778. /**
  89779. * True to ensure the data are premultiplied.
  89780. */
  89781. _this.PREMULTIPLYALPHA = false;
  89782. /**
  89783. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  89784. */
  89785. _this.USERGBCOLOR = false;
  89786. /**
  89787. * True to add noise in order to reduce the banding effect.
  89788. */
  89789. _this.NOISE = false;
  89790. /**
  89791. * is the reflection texture in BGR color scheme?
  89792. * Mainly used to solve a bug in ios10 video tag
  89793. */
  89794. _this.REFLECTIONBGR = false;
  89795. _this.IMAGEPROCESSING = false;
  89796. _this.VIGNETTE = false;
  89797. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  89798. _this.VIGNETTEBLENDMODEOPAQUE = false;
  89799. _this.TONEMAPPING = false;
  89800. _this.CONTRAST = false;
  89801. _this.COLORCURVES = false;
  89802. _this.COLORGRADING = false;
  89803. _this.COLORGRADING3D = false;
  89804. _this.SAMPLER3DGREENDEPTH = false;
  89805. _this.SAMPLER3DBGRMAP = false;
  89806. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  89807. _this.EXPOSURE = false;
  89808. _this.GRAIN = false;
  89809. // Reflection.
  89810. _this.REFLECTION = false;
  89811. _this.REFLECTIONMAP_3D = false;
  89812. _this.REFLECTIONMAP_SPHERICAL = false;
  89813. _this.REFLECTIONMAP_PLANAR = false;
  89814. _this.REFLECTIONMAP_CUBIC = false;
  89815. _this.REFLECTIONMAP_PROJECTION = false;
  89816. _this.REFLECTIONMAP_SKYBOX = false;
  89817. _this.REFLECTIONMAP_EXPLICIT = false;
  89818. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  89819. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  89820. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  89821. _this.INVERTCUBICMAP = false;
  89822. _this.REFLECTIONMAP_OPPOSITEZ = false;
  89823. _this.LODINREFLECTIONALPHA = false;
  89824. _this.GAMMAREFLECTION = false;
  89825. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  89826. // Default BJS.
  89827. _this.MAINUV1 = false;
  89828. _this.MAINUV2 = false;
  89829. _this.UV1 = false;
  89830. _this.UV2 = false;
  89831. _this.CLIPPLANE = false;
  89832. _this.POINTSIZE = false;
  89833. _this.FOG = false;
  89834. _this.NORMAL = false;
  89835. _this.NUM_BONE_INFLUENCERS = 0;
  89836. _this.BonesPerMesh = 0;
  89837. _this.INSTANCES = false;
  89838. _this.SHADOWFLOAT = false;
  89839. _this.rebuild();
  89840. return _this;
  89841. }
  89842. return BackgroundMaterialDefines;
  89843. }(BABYLON.MaterialDefines));
  89844. /**
  89845. * Background material used to create an efficient environement around your scene.
  89846. */
  89847. var BackgroundMaterial = /** @class */ (function (_super) {
  89848. __extends(BackgroundMaterial, _super);
  89849. /**
  89850. * Instantiates a Background Material in the given scene
  89851. * @param name The friendly name of the material
  89852. * @param scene The scene to add the material to
  89853. */
  89854. function BackgroundMaterial(name, scene) {
  89855. var _this = _super.call(this, name, scene) || this;
  89856. /**
  89857. * Key light Color (multiply against the R channel of the environement texture)
  89858. */
  89859. _this.primaryColor = BABYLON.Color3.White();
  89860. /**
  89861. * Key light Level (allowing HDR output of the background)
  89862. */
  89863. _this.primaryLevel = 1;
  89864. /**
  89865. * Secondary light Color (multiply against the G channel of the environement texture)
  89866. */
  89867. _this.secondaryColor = BABYLON.Color3.Gray();
  89868. /**
  89869. * Secondary light Level (allowing HDR output of the background)
  89870. */
  89871. _this.secondaryLevel = 1;
  89872. /**
  89873. * Tertiary light Color (multiply against the B channel of the environement texture)
  89874. */
  89875. _this.tertiaryColor = BABYLON.Color3.Black();
  89876. /**
  89877. * Tertiary light Level (allowing HDR output of the background)
  89878. */
  89879. _this.tertiaryLevel = 1;
  89880. /**
  89881. * Reflection Texture used in the material.
  89882. * Should be author in a specific way for the best result (refer to the documentation).
  89883. */
  89884. _this.reflectionTexture = null;
  89885. /**
  89886. * Reflection Texture level of blur.
  89887. *
  89888. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  89889. * texture twice.
  89890. */
  89891. _this.reflectionBlur = 0;
  89892. /**
  89893. * Diffuse Texture used in the material.
  89894. * Should be author in a specific way for the best result (refer to the documentation).
  89895. */
  89896. _this.diffuseTexture = null;
  89897. _this._shadowLights = null;
  89898. /**
  89899. * Specify the list of lights casting shadow on the material.
  89900. * All scene shadow lights will be included if null.
  89901. */
  89902. _this.shadowLights = null;
  89903. /**
  89904. * For the lights having a blurred shadow generator, this can add a second blur pass in order to reach
  89905. * soft lighting on the background.
  89906. */
  89907. _this.shadowBlurScale = 1;
  89908. /**
  89909. * Helps adjusting the shadow to a softer level if required.
  89910. * 0 means black shadows and 1 means no shadows.
  89911. */
  89912. _this.shadowLevel = 0;
  89913. /**
  89914. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  89915. * It is usually zero but might be interesting to modify according to your setup.
  89916. */
  89917. _this.sceneCenter = BABYLON.Vector3.Zero();
  89918. /**
  89919. * This helps specifying that the material is falling off to the sky box at grazing angle.
  89920. * This helps ensuring a nice transition when the camera goes under the ground.
  89921. */
  89922. _this.opacityFresnel = true;
  89923. /**
  89924. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  89925. * This helps adding a mirror texture on the ground.
  89926. */
  89927. _this.reflectionFresnel = false;
  89928. /**
  89929. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  89930. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  89931. */
  89932. _this.reflectionFalloffDistance = 0.0;
  89933. /**
  89934. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  89935. */
  89936. _this.reflectionAmount = 1.0;
  89937. /**
  89938. * This specifies the weight of the reflection at grazing angle.
  89939. */
  89940. _this.reflectionReflectance0 = 0.05;
  89941. /**
  89942. * This specifies the weight of the reflection at a perpendicular point of view.
  89943. */
  89944. _this.reflectionReflectance90 = 0.5;
  89945. /**
  89946. * Helps to directly use the maps channels instead of their level.
  89947. */
  89948. _this.useRGBColor = true;
  89949. /**
  89950. * This helps reducing the banding effect that could occur on the background.
  89951. */
  89952. _this.enableNoise = false;
  89953. _this._fovMultiplier = 1.0;
  89954. /**
  89955. * Enable the FOV adjustment feature controlled by fovMultiplier.
  89956. * @type {boolean}
  89957. */
  89958. _this.useEquirectangularFOV = false;
  89959. _this._maxSimultaneousLights = 4;
  89960. /**
  89961. * Number of Simultaneous lights allowed on the material.
  89962. */
  89963. _this.maxSimultaneousLights = 4;
  89964. /**
  89965. * Keep track of the image processing observer to allow dispose and replace.
  89966. */
  89967. _this._imageProcessingObserver = null;
  89968. /**
  89969. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  89970. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  89971. */
  89972. _this.switchToBGR = false;
  89973. // Temp values kept as cache in the material.
  89974. _this._renderTargets = new BABYLON.SmartArray(16);
  89975. _this._reflectionControls = BABYLON.Vector4.Zero();
  89976. // Setup the default processing configuration to the scene.
  89977. _this._attachImageProcessingConfiguration(null);
  89978. _this.getRenderTargetTextures = function () {
  89979. _this._renderTargets.reset();
  89980. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  89981. _this._renderTargets.push(_this._diffuseTexture);
  89982. }
  89983. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  89984. _this._renderTargets.push(_this._reflectionTexture);
  89985. }
  89986. return _this._renderTargets;
  89987. };
  89988. return _this;
  89989. }
  89990. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  89991. /**
  89992. * Sets the reflection reflectance fresnel values according to the default standard
  89993. * empirically know to work well :-)
  89994. */
  89995. set: function (value) {
  89996. var reflectionWeight = value;
  89997. if (reflectionWeight < 0.5) {
  89998. reflectionWeight = reflectionWeight * 2.0;
  89999. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  90000. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  90001. }
  90002. else {
  90003. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  90004. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  90005. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  90006. }
  90007. },
  90008. enumerable: true,
  90009. configurable: true
  90010. });
  90011. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  90012. /**
  90013. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  90014. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  90015. * Recommended to be keep at 1.0 except for special cases.
  90016. */
  90017. get: function () {
  90018. return this._fovMultiplier;
  90019. },
  90020. set: function (value) {
  90021. if (isNaN(value)) {
  90022. value = 1.0;
  90023. }
  90024. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  90025. },
  90026. enumerable: true,
  90027. configurable: true
  90028. });
  90029. /**
  90030. * Attaches a new image processing configuration to the PBR Material.
  90031. * @param configuration (if null the scene configuration will be use)
  90032. */
  90033. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  90034. var _this = this;
  90035. if (configuration === this._imageProcessingConfiguration) {
  90036. return;
  90037. }
  90038. // Detaches observer.
  90039. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  90040. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  90041. }
  90042. // Pick the scene configuration if needed.
  90043. if (!configuration) {
  90044. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  90045. }
  90046. else {
  90047. this._imageProcessingConfiguration = configuration;
  90048. }
  90049. // Attaches observer.
  90050. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  90051. _this._markAllSubMeshesAsImageProcessingDirty();
  90052. });
  90053. };
  90054. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  90055. /**
  90056. * Gets the image processing configuration used either in this material.
  90057. */
  90058. get: function () {
  90059. return this._imageProcessingConfiguration;
  90060. },
  90061. /**
  90062. * Sets the Default image processing configuration used either in the this material.
  90063. *
  90064. * If sets to null, the scene one is in use.
  90065. */
  90066. set: function (value) {
  90067. this._attachImageProcessingConfiguration(value);
  90068. // Ensure the effect will be rebuilt.
  90069. this._markAllSubMeshesAsTexturesDirty();
  90070. },
  90071. enumerable: true,
  90072. configurable: true
  90073. });
  90074. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  90075. /**
  90076. * Gets wether the color curves effect is enabled.
  90077. */
  90078. get: function () {
  90079. return this.imageProcessingConfiguration.colorCurvesEnabled;
  90080. },
  90081. /**
  90082. * Sets wether the color curves effect is enabled.
  90083. */
  90084. set: function (value) {
  90085. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  90086. },
  90087. enumerable: true,
  90088. configurable: true
  90089. });
  90090. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  90091. /**
  90092. * Gets wether the color grading effect is enabled.
  90093. */
  90094. get: function () {
  90095. return this.imageProcessingConfiguration.colorGradingEnabled;
  90096. },
  90097. /**
  90098. * Gets wether the color grading effect is enabled.
  90099. */
  90100. set: function (value) {
  90101. this.imageProcessingConfiguration.colorGradingEnabled = value;
  90102. },
  90103. enumerable: true,
  90104. configurable: true
  90105. });
  90106. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  90107. /**
  90108. * Gets wether tonemapping is enabled or not.
  90109. */
  90110. get: function () {
  90111. return this._imageProcessingConfiguration.toneMappingEnabled;
  90112. },
  90113. /**
  90114. * Sets wether tonemapping is enabled or not
  90115. */
  90116. set: function (value) {
  90117. this._imageProcessingConfiguration.toneMappingEnabled = value;
  90118. },
  90119. enumerable: true,
  90120. configurable: true
  90121. });
  90122. ;
  90123. ;
  90124. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  90125. /**
  90126. * The camera exposure used on this material.
  90127. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  90128. * This corresponds to a photographic exposure.
  90129. */
  90130. get: function () {
  90131. return this._imageProcessingConfiguration.exposure;
  90132. },
  90133. /**
  90134. * The camera exposure used on this material.
  90135. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  90136. * This corresponds to a photographic exposure.
  90137. */
  90138. set: function (value) {
  90139. this._imageProcessingConfiguration.exposure = value;
  90140. },
  90141. enumerable: true,
  90142. configurable: true
  90143. });
  90144. ;
  90145. ;
  90146. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  90147. /**
  90148. * Gets The camera contrast used on this material.
  90149. */
  90150. get: function () {
  90151. return this._imageProcessingConfiguration.contrast;
  90152. },
  90153. /**
  90154. * Sets The camera contrast used on this material.
  90155. */
  90156. set: function (value) {
  90157. this._imageProcessingConfiguration.contrast = value;
  90158. },
  90159. enumerable: true,
  90160. configurable: true
  90161. });
  90162. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  90163. /**
  90164. * Gets the Color Grading 2D Lookup Texture.
  90165. */
  90166. get: function () {
  90167. return this._imageProcessingConfiguration.colorGradingTexture;
  90168. },
  90169. /**
  90170. * Sets the Color Grading 2D Lookup Texture.
  90171. */
  90172. set: function (value) {
  90173. this.imageProcessingConfiguration.colorGradingTexture = value;
  90174. },
  90175. enumerable: true,
  90176. configurable: true
  90177. });
  90178. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  90179. /**
  90180. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  90181. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  90182. * These are similar to controls found in many professional imaging or colorist software. The global controls are applied to the entire image. For advanced tuning, extra controls are provided to adjust the shadow, midtone and highlight areas of the image;
  90183. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  90184. */
  90185. get: function () {
  90186. return this.imageProcessingConfiguration.colorCurves;
  90187. },
  90188. /**
  90189. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  90190. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  90191. * These are similar to controls found in many professional imaging or colorist software. The global controls are applied to the entire image. For advanced tuning, extra controls are provided to adjust the shadow, midtone and highlight areas of the image;
  90192. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  90193. */
  90194. set: function (value) {
  90195. this.imageProcessingConfiguration.colorCurves = value;
  90196. },
  90197. enumerable: true,
  90198. configurable: true
  90199. });
  90200. /**
  90201. * The entire material has been created in order to prevent overdraw.
  90202. * @returns false
  90203. */
  90204. BackgroundMaterial.prototype.needAlphaTesting = function () {
  90205. return true;
  90206. };
  90207. /**
  90208. * The entire material has been created in order to prevent overdraw.
  90209. * @returns true if blending is enable
  90210. */
  90211. BackgroundMaterial.prototype.needAlphaBlending = function () {
  90212. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  90213. };
  90214. /**
  90215. * Checks wether the material is ready to be rendered for a given mesh.
  90216. * @param mesh The mesh to render
  90217. * @param subMesh The submesh to check against
  90218. * @param useInstances Specify wether or not the material is used with instances
  90219. * @returns true if all the dependencies are ready (Textures, Effects...)
  90220. */
  90221. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  90222. var _this = this;
  90223. if (useInstances === void 0) { useInstances = false; }
  90224. if (subMesh.effect && this.isFrozen) {
  90225. if (this._wasPreviouslyReady) {
  90226. return true;
  90227. }
  90228. }
  90229. if (!subMesh._materialDefines) {
  90230. subMesh._materialDefines = new BackgroundMaterialDefines();
  90231. }
  90232. var scene = this.getScene();
  90233. var defines = subMesh._materialDefines;
  90234. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  90235. if (defines._renderId === scene.getRenderId()) {
  90236. return true;
  90237. }
  90238. }
  90239. var engine = scene.getEngine();
  90240. // Lights
  90241. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  90242. defines._needNormals = true;
  90243. // Textures
  90244. if (defines._areTexturesDirty) {
  90245. defines._needUVs = false;
  90246. if (scene.texturesEnabled) {
  90247. if (scene.getEngine().getCaps().textureLOD) {
  90248. defines.TEXTURELODSUPPORT = true;
  90249. }
  90250. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  90251. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  90252. return false;
  90253. }
  90254. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  90255. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  90256. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  90257. defines.OPACITYFRESNEL = this._opacityFresnel;
  90258. }
  90259. else {
  90260. defines.DIFFUSE = false;
  90261. defines.DIFFUSEHASALPHA = false;
  90262. defines.GAMMADIFFUSE = false;
  90263. defines.OPACITYFRESNEL = false;
  90264. }
  90265. var reflectionTexture = this._reflectionTexture;
  90266. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  90267. if (!reflectionTexture.isReadyOrNotBlocking()) {
  90268. return false;
  90269. }
  90270. defines.REFLECTION = true;
  90271. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  90272. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  90273. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  90274. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  90275. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  90276. defines.REFLECTIONBGR = this.switchToBGR;
  90277. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  90278. defines.INVERTCUBICMAP = true;
  90279. }
  90280. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  90281. switch (reflectionTexture.coordinatesMode) {
  90282. case BABYLON.Texture.CUBIC_MODE:
  90283. case BABYLON.Texture.INVCUBIC_MODE:
  90284. defines.REFLECTIONMAP_CUBIC = true;
  90285. break;
  90286. case BABYLON.Texture.EXPLICIT_MODE:
  90287. defines.REFLECTIONMAP_EXPLICIT = true;
  90288. break;
  90289. case BABYLON.Texture.PLANAR_MODE:
  90290. defines.REFLECTIONMAP_PLANAR = true;
  90291. break;
  90292. case BABYLON.Texture.PROJECTION_MODE:
  90293. defines.REFLECTIONMAP_PROJECTION = true;
  90294. break;
  90295. case BABYLON.Texture.SKYBOX_MODE:
  90296. defines.REFLECTIONMAP_SKYBOX = true;
  90297. break;
  90298. case BABYLON.Texture.SPHERICAL_MODE:
  90299. defines.REFLECTIONMAP_SPHERICAL = true;
  90300. break;
  90301. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  90302. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  90303. break;
  90304. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  90305. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  90306. break;
  90307. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  90308. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  90309. break;
  90310. }
  90311. if (this.reflectionFresnel) {
  90312. defines.REFLECTIONFRESNEL = true;
  90313. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  90314. this._reflectionControls.x = this.reflectionAmount;
  90315. this._reflectionControls.y = this.reflectionReflectance0;
  90316. this._reflectionControls.z = this.reflectionReflectance90;
  90317. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  90318. }
  90319. else {
  90320. defines.REFLECTIONFRESNEL = false;
  90321. defines.REFLECTIONFALLOFF = false;
  90322. }
  90323. }
  90324. else {
  90325. defines.REFLECTION = false;
  90326. defines.REFLECTIONFALLOFF = false;
  90327. defines.REFLECTIONBLUR = false;
  90328. defines.REFLECTIONMAP_3D = false;
  90329. defines.REFLECTIONMAP_SPHERICAL = false;
  90330. defines.REFLECTIONMAP_PLANAR = false;
  90331. defines.REFLECTIONMAP_CUBIC = false;
  90332. defines.REFLECTIONMAP_PROJECTION = false;
  90333. defines.REFLECTIONMAP_SKYBOX = false;
  90334. defines.REFLECTIONMAP_EXPLICIT = false;
  90335. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  90336. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  90337. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  90338. defines.INVERTCUBICMAP = false;
  90339. defines.REFLECTIONMAP_OPPOSITEZ = false;
  90340. defines.LODINREFLECTIONALPHA = false;
  90341. defines.GAMMAREFLECTION = false;
  90342. }
  90343. }
  90344. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  90345. defines.USERGBCOLOR = this._useRGBColor;
  90346. defines.NOISE = this._enableNoise;
  90347. }
  90348. if (defines._areImageProcessingDirty) {
  90349. if (!this._imageProcessingConfiguration.isReady()) {
  90350. return false;
  90351. }
  90352. this._imageProcessingConfiguration.prepareDefines(defines);
  90353. }
  90354. // Misc.
  90355. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  90356. // Values that need to be evaluated on every frame
  90357. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  90358. // Attribs
  90359. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  90360. if (mesh) {
  90361. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  90362. mesh.createNormals(true);
  90363. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  90364. }
  90365. }
  90366. }
  90367. // Get correct effect
  90368. if (defines.isDirty) {
  90369. defines.markAsProcessed();
  90370. scene.resetCachedMaterial();
  90371. // Fallbacks
  90372. var fallbacks = new BABYLON.EffectFallbacks();
  90373. if (defines.FOG) {
  90374. fallbacks.addFallback(0, "FOG");
  90375. }
  90376. if (defines.POINTSIZE) {
  90377. fallbacks.addFallback(1, "POINTSIZE");
  90378. }
  90379. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  90380. if (defines.NUM_BONE_INFLUENCERS > 0) {
  90381. fallbacks.addCPUSkinningFallback(0, mesh);
  90382. }
  90383. //Attributes
  90384. var attribs = [BABYLON.VertexBuffer.PositionKind];
  90385. if (defines.NORMAL) {
  90386. attribs.push(BABYLON.VertexBuffer.NormalKind);
  90387. }
  90388. if (defines.UV1) {
  90389. attribs.push(BABYLON.VertexBuffer.UVKind);
  90390. }
  90391. if (defines.UV2) {
  90392. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  90393. }
  90394. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  90395. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  90396. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  90397. "vFogInfos", "vFogColor", "pointSize",
  90398. "vClipPlane", "mBones",
  90399. "vPrimaryColor", "vSecondaryColor", "vTertiaryColor",
  90400. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  90401. "shadowLevel", "alpha",
  90402. "vBackgroundCenter", "vReflectionControl",
  90403. "vDiffuseInfos", "diffuseMatrix",
  90404. ];
  90405. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  90406. var uniformBuffers = ["Material", "Scene"];
  90407. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  90408. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  90409. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  90410. uniformsNames: uniforms,
  90411. uniformBuffersNames: uniformBuffers,
  90412. samplers: samplers,
  90413. defines: defines,
  90414. maxSimultaneousLights: this._maxSimultaneousLights
  90415. });
  90416. var onCompiled = function (effect) {
  90417. if (_this.onCompiled) {
  90418. _this.onCompiled(effect);
  90419. }
  90420. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  90421. };
  90422. var join = defines.toString();
  90423. subMesh.setEffect(scene.getEngine().createEffect("background", {
  90424. attributes: attribs,
  90425. uniformsNames: uniforms,
  90426. uniformBuffersNames: uniformBuffers,
  90427. samplers: samplers,
  90428. defines: join,
  90429. fallbacks: fallbacks,
  90430. onCompiled: onCompiled,
  90431. onError: this.onError,
  90432. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  90433. }, engine), defines);
  90434. this.buildUniformLayout();
  90435. }
  90436. if (!subMesh.effect || !subMesh.effect.isReady()) {
  90437. return false;
  90438. }
  90439. defines._renderId = scene.getRenderId();
  90440. this._wasPreviouslyReady = true;
  90441. return true;
  90442. };
  90443. /**
  90444. * Build the uniform buffer used in the material.
  90445. */
  90446. BackgroundMaterial.prototype.buildUniformLayout = function () {
  90447. // Order is important !
  90448. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  90449. this._uniformBuffer.addUniform("vSecondaryColor", 4);
  90450. this._uniformBuffer.addUniform("vTertiaryColor", 4);
  90451. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  90452. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  90453. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  90454. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  90455. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  90456. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  90457. this._uniformBuffer.addUniform("pointSize", 1);
  90458. this._uniformBuffer.addUniform("shadowLevel", 1);
  90459. this._uniformBuffer.addUniform("alpha", 1);
  90460. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  90461. this._uniformBuffer.addUniform("vReflectionControl", 4);
  90462. this._uniformBuffer.create();
  90463. };
  90464. /**
  90465. * Unbind the material.
  90466. */
  90467. BackgroundMaterial.prototype.unbind = function () {
  90468. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  90469. this._uniformBuffer.setTexture("diffuseSampler", null);
  90470. }
  90471. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  90472. this._uniformBuffer.setTexture("reflectionSampler", null);
  90473. }
  90474. _super.prototype.unbind.call(this);
  90475. };
  90476. /**
  90477. * Bind only the world matrix to the material.
  90478. * @param world The world matrix to bind.
  90479. */
  90480. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  90481. this._activeEffect.setMatrix("world", world);
  90482. };
  90483. /**
  90484. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  90485. * @param world The world matrix to bind.
  90486. * @param subMesh The submesh to bind for.
  90487. */
  90488. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  90489. var scene = this.getScene();
  90490. var defines = subMesh._materialDefines;
  90491. if (!defines) {
  90492. return;
  90493. }
  90494. var effect = subMesh.effect;
  90495. if (!effect) {
  90496. return;
  90497. }
  90498. this._activeEffect = effect;
  90499. // Matrices
  90500. this.bindOnlyWorldMatrix(world);
  90501. // Bones
  90502. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  90503. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  90504. if (mustRebind) {
  90505. this._uniformBuffer.bindToEffect(effect, "Material");
  90506. this.bindViewProjection(effect);
  90507. var reflectionTexture = this._reflectionTexture;
  90508. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  90509. // Texture uniforms
  90510. if (scene.texturesEnabled) {
  90511. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  90512. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  90513. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  90514. }
  90515. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  90516. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  90517. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  90518. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  90519. }
  90520. }
  90521. if (this.shadowLevel > 0) {
  90522. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  90523. }
  90524. this._uniformBuffer.updateFloat("alpha", this.alpha);
  90525. // Point size
  90526. if (this.pointsCloud) {
  90527. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  90528. }
  90529. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, this._primaryLevel);
  90530. this._uniformBuffer.updateColor4("vSecondaryColor", this._secondaryColor, this._secondaryLevel);
  90531. this._uniformBuffer.updateColor4("vTertiaryColor", this._tertiaryColor, this._tertiaryLevel);
  90532. }
  90533. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  90534. // Textures
  90535. if (scene.texturesEnabled) {
  90536. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  90537. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  90538. }
  90539. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  90540. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  90541. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  90542. }
  90543. else if (!defines.REFLECTIONBLUR) {
  90544. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  90545. }
  90546. else {
  90547. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  90548. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  90549. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  90550. }
  90551. if (defines.REFLECTIONFRESNEL) {
  90552. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  90553. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  90554. }
  90555. }
  90556. }
  90557. // Clip plane
  90558. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  90559. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  90560. }
  90561. if (mustRebind || !this.isFrozen) {
  90562. if (scene.lightsEnabled) {
  90563. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  90564. }
  90565. // View
  90566. this.bindView(effect);
  90567. // Fog
  90568. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  90569. // image processing
  90570. this._imageProcessingConfiguration.bind(this._activeEffect);
  90571. }
  90572. this._uniformBuffer.update();
  90573. this._afterBind(mesh);
  90574. };
  90575. /**
  90576. * Dispose the material.
  90577. * @param forceDisposeEffect Force disposal of the associated effect.
  90578. * @param forceDisposeTextures Force disposal of the associated textures.
  90579. */
  90580. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  90581. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  90582. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  90583. if (forceDisposeTextures) {
  90584. if (this.diffuseTexture) {
  90585. this.diffuseTexture.dispose();
  90586. }
  90587. if (this.reflectionTexture) {
  90588. this.reflectionTexture.dispose();
  90589. }
  90590. }
  90591. this._renderTargets.dispose();
  90592. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  90593. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  90594. }
  90595. _super.prototype.dispose.call(this, forceDisposeEffect);
  90596. };
  90597. /**
  90598. * Clones the material.
  90599. * @param name The cloned name.
  90600. * @returns The cloned material.
  90601. */
  90602. BackgroundMaterial.prototype.clone = function (name) {
  90603. var _this = this;
  90604. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  90605. };
  90606. /**
  90607. * Serializes the current material to its JSON representation.
  90608. * @returns The JSON representation.
  90609. */
  90610. BackgroundMaterial.prototype.serialize = function () {
  90611. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  90612. serializationObject.customType = "BABYLON.BackgroundMaterial";
  90613. return serializationObject;
  90614. };
  90615. /**
  90616. * Gets the class name of the material
  90617. * @returns "BackgroundMaterial"
  90618. */
  90619. BackgroundMaterial.prototype.getClassName = function () {
  90620. return "BackgroundMaterial";
  90621. };
  90622. /**
  90623. * Parse a JSON input to create back a background material.
  90624. * @param source The JSON data to parse
  90625. * @param scene The scene to create the parsed material in
  90626. * @param rootUrl The root url of the assets the material depends upon
  90627. * @returns the instantiated BackgroundMaterial.
  90628. */
  90629. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  90630. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  90631. };
  90632. /**
  90633. * Standard reflectance value at parallel view angle.
  90634. */
  90635. BackgroundMaterial.StandardReflectance0 = 0.05;
  90636. /**
  90637. * Standard reflectance value at grazing angle.
  90638. */
  90639. BackgroundMaterial.StandardReflectance90 = 0.5;
  90640. __decorate([
  90641. BABYLON.serializeAsColor3()
  90642. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  90643. __decorate([
  90644. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  90645. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  90646. __decorate([
  90647. BABYLON.serialize()
  90648. ], BackgroundMaterial.prototype, "_primaryLevel", void 0);
  90649. __decorate([
  90650. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  90651. ], BackgroundMaterial.prototype, "primaryLevel", void 0);
  90652. __decorate([
  90653. BABYLON.serializeAsColor3()
  90654. ], BackgroundMaterial.prototype, "_secondaryColor", void 0);
  90655. __decorate([
  90656. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  90657. ], BackgroundMaterial.prototype, "secondaryColor", void 0);
  90658. __decorate([
  90659. BABYLON.serialize()
  90660. ], BackgroundMaterial.prototype, "_secondaryLevel", void 0);
  90661. __decorate([
  90662. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  90663. ], BackgroundMaterial.prototype, "secondaryLevel", void 0);
  90664. __decorate([
  90665. BABYLON.serializeAsColor3()
  90666. ], BackgroundMaterial.prototype, "_tertiaryColor", void 0);
  90667. __decorate([
  90668. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  90669. ], BackgroundMaterial.prototype, "tertiaryColor", void 0);
  90670. __decorate([
  90671. BABYLON.serialize()
  90672. ], BackgroundMaterial.prototype, "_tertiaryLevel", void 0);
  90673. __decorate([
  90674. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  90675. ], BackgroundMaterial.prototype, "tertiaryLevel", void 0);
  90676. __decorate([
  90677. BABYLON.serializeAsTexture()
  90678. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  90679. __decorate([
  90680. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90681. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  90682. __decorate([
  90683. BABYLON.serialize()
  90684. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  90685. __decorate([
  90686. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90687. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  90688. __decorate([
  90689. BABYLON.serializeAsTexture()
  90690. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  90691. __decorate([
  90692. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90693. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  90694. __decorate([
  90695. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90696. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  90697. __decorate([
  90698. BABYLON.serialize()
  90699. ], BackgroundMaterial.prototype, "_shadowBlurScale", void 0);
  90700. __decorate([
  90701. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90702. ], BackgroundMaterial.prototype, "shadowBlurScale", void 0);
  90703. __decorate([
  90704. BABYLON.serialize()
  90705. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  90706. __decorate([
  90707. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90708. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  90709. __decorate([
  90710. BABYLON.serializeAsVector3()
  90711. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  90712. __decorate([
  90713. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90714. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  90715. __decorate([
  90716. BABYLON.serialize()
  90717. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  90718. __decorate([
  90719. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90720. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  90721. __decorate([
  90722. BABYLON.serialize()
  90723. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  90724. __decorate([
  90725. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90726. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  90727. __decorate([
  90728. BABYLON.serialize()
  90729. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  90730. __decorate([
  90731. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90732. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  90733. __decorate([
  90734. BABYLON.serialize()
  90735. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  90736. __decorate([
  90737. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90738. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  90739. __decorate([
  90740. BABYLON.serialize()
  90741. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  90742. __decorate([
  90743. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90744. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  90745. __decorate([
  90746. BABYLON.serialize()
  90747. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  90748. __decorate([
  90749. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90750. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  90751. __decorate([
  90752. BABYLON.serialize()
  90753. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  90754. __decorate([
  90755. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90756. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  90757. __decorate([
  90758. BABYLON.serialize()
  90759. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  90760. __decorate([
  90761. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90762. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  90763. __decorate([
  90764. BABYLON.serialize()
  90765. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  90766. __decorate([
  90767. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90768. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  90769. __decorate([
  90770. BABYLON.serializeAsImageProcessingConfiguration()
  90771. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  90772. return BackgroundMaterial;
  90773. }(BABYLON.PushMaterial));
  90774. BABYLON.BackgroundMaterial = BackgroundMaterial;
  90775. })(BABYLON || (BABYLON = {}));
  90776. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  90777. var __assign = (this && this.__assign) || Object.assign || function(t) {
  90778. for (var s, i = 1, n = arguments.length; i < n; i++) {
  90779. s = arguments[i];
  90780. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  90781. t[p] = s[p];
  90782. }
  90783. return t;
  90784. };
  90785. var BABYLON;
  90786. (function (BABYLON) {
  90787. /**
  90788. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  90789. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  90790. * It also helps with the default setup of your imageProcessing configuration.
  90791. */
  90792. var EnvironmentHelper = /** @class */ (function () {
  90793. /**
  90794. * constructor
  90795. * @param options
  90796. * @param scene The scene to add the material to
  90797. */
  90798. function EnvironmentHelper(options, scene) {
  90799. var _this = this;
  90800. this._errorHandler = function (message, exception) {
  90801. _this.onErrorObservable.notifyObservers({ message: message, exception: exception });
  90802. };
  90803. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  90804. this._scene = scene;
  90805. this.onErrorObservable = new BABYLON.Observable();
  90806. this._setupBackground();
  90807. this._setupImageProcessing();
  90808. }
  90809. /**
  90810. * Creates the default options for the helper.
  90811. */
  90812. EnvironmentHelper._getDefaultOptions = function () {
  90813. return {
  90814. createGround: true,
  90815. groundSize: 15,
  90816. groundTexture: this._groundTextureCDNUrl,
  90817. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  90818. groundOpacity: 0.9,
  90819. enableGroundShadow: true,
  90820. groundShadowLevel: 0.5,
  90821. enableGroundMirror: false,
  90822. groundMirrorSizeRatio: 0.3,
  90823. groundMirrorBlurKernel: 64,
  90824. groundMirrorAmount: 1,
  90825. groundMirrorFresnelWeight: 1,
  90826. groundMirrorFallOffDistance: 0,
  90827. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  90828. groundYBias: 0.00001,
  90829. createSkybox: true,
  90830. skyboxSize: 20,
  90831. skyboxTexture: this._skyboxTextureCDNUrl,
  90832. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  90833. backgroundYRotation: 0,
  90834. sizeAuto: true,
  90835. rootPosition: BABYLON.Vector3.Zero(),
  90836. setupImageProcessing: true,
  90837. environmentTexture: this._environmentTextureCDNUrl,
  90838. cameraExposure: 0.8,
  90839. cameraContrast: 1.2,
  90840. toneMappingEnabled: true,
  90841. };
  90842. };
  90843. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  90844. /**
  90845. * Gets the root mesh created by the helper.
  90846. */
  90847. get: function () {
  90848. return this._rootMesh;
  90849. },
  90850. enumerable: true,
  90851. configurable: true
  90852. });
  90853. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  90854. /**
  90855. * Gets the skybox created by the helper.
  90856. */
  90857. get: function () {
  90858. return this._skybox;
  90859. },
  90860. enumerable: true,
  90861. configurable: true
  90862. });
  90863. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  90864. /**
  90865. * Gets the skybox texture created by the helper.
  90866. */
  90867. get: function () {
  90868. return this._skyboxTexture;
  90869. },
  90870. enumerable: true,
  90871. configurable: true
  90872. });
  90873. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  90874. /**
  90875. * Gets the skybox material created by the helper.
  90876. */
  90877. get: function () {
  90878. return this._skyboxMaterial;
  90879. },
  90880. enumerable: true,
  90881. configurable: true
  90882. });
  90883. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  90884. /**
  90885. * Gets the ground mesh created by the helper.
  90886. */
  90887. get: function () {
  90888. return this._ground;
  90889. },
  90890. enumerable: true,
  90891. configurable: true
  90892. });
  90893. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  90894. /**
  90895. * Gets the ground texture created by the helper.
  90896. */
  90897. get: function () {
  90898. return this._groundTexture;
  90899. },
  90900. enumerable: true,
  90901. configurable: true
  90902. });
  90903. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  90904. /**
  90905. * Gets the ground mirror created by the helper.
  90906. */
  90907. get: function () {
  90908. return this._groundMirror;
  90909. },
  90910. enumerable: true,
  90911. configurable: true
  90912. });
  90913. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  90914. /**
  90915. * Gets the ground mirror render list to helps pushing the meshes
  90916. * you wish in the ground reflection.
  90917. */
  90918. get: function () {
  90919. if (this._groundMirror) {
  90920. return this._groundMirror.renderList;
  90921. }
  90922. return null;
  90923. },
  90924. enumerable: true,
  90925. configurable: true
  90926. });
  90927. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  90928. /**
  90929. * Gets the ground material created by the helper.
  90930. */
  90931. get: function () {
  90932. return this._groundMaterial;
  90933. },
  90934. enumerable: true,
  90935. configurable: true
  90936. });
  90937. /**
  90938. * Updates the background according to the new options
  90939. * @param options
  90940. */
  90941. EnvironmentHelper.prototype.updateOptions = function (options) {
  90942. var newOptions = __assign({}, this._options, options);
  90943. if (this._ground && !newOptions.createGround) {
  90944. this._ground.dispose();
  90945. this._ground = null;
  90946. }
  90947. if (this._groundMaterial && !newOptions.createGround) {
  90948. this._groundMaterial.dispose();
  90949. this._groundMaterial = null;
  90950. }
  90951. if (this._groundTexture) {
  90952. if (this._options.groundTexture != newOptions.groundTexture) {
  90953. this._groundTexture.dispose();
  90954. this._groundTexture = null;
  90955. }
  90956. }
  90957. if (this._skybox && !newOptions.createSkybox) {
  90958. this._skybox.dispose();
  90959. this._skybox = null;
  90960. }
  90961. if (this._skyboxMaterial && !newOptions.createSkybox) {
  90962. this._skyboxMaterial.dispose();
  90963. this._skyboxMaterial = null;
  90964. }
  90965. if (this._skyboxTexture) {
  90966. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  90967. this._skyboxTexture.dispose();
  90968. this._skyboxTexture = null;
  90969. }
  90970. }
  90971. if (this._groundMirror && !newOptions.enableGroundMirror) {
  90972. this._groundMirror.dispose();
  90973. this._groundMirror = null;
  90974. }
  90975. if (this._scene.environmentTexture) {
  90976. if (this._options.environmentTexture != newOptions.environmentTexture) {
  90977. this._scene.environmentTexture.dispose();
  90978. }
  90979. }
  90980. this._options = newOptions;
  90981. this._setupBackground();
  90982. this._setupImageProcessing();
  90983. };
  90984. /**
  90985. * Sets the primary color of all the available elements.
  90986. * @param color
  90987. */
  90988. EnvironmentHelper.prototype.setMainColor = function (color) {
  90989. if (this.groundMaterial) {
  90990. this.groundMaterial.primaryColor = color;
  90991. }
  90992. if (this.skyboxMaterial) {
  90993. this.skyboxMaterial.primaryColor = color;
  90994. }
  90995. if (this.groundMirror) {
  90996. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  90997. }
  90998. };
  90999. /**
  91000. * Setup the image processing according to the specified options.
  91001. */
  91002. EnvironmentHelper.prototype._setupImageProcessing = function () {
  91003. if (this._options.setupImageProcessing) {
  91004. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  91005. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  91006. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  91007. this._setupEnvironmentTexture();
  91008. }
  91009. };
  91010. /**
  91011. * Setup the environment texture according to the specified options.
  91012. */
  91013. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  91014. if (this._scene.environmentTexture) {
  91015. return;
  91016. }
  91017. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  91018. this._scene.environmentTexture = this._options.environmentTexture;
  91019. return;
  91020. }
  91021. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  91022. this._scene.environmentTexture = environmentTexture;
  91023. };
  91024. /**
  91025. * Setup the background according to the specified options.
  91026. */
  91027. EnvironmentHelper.prototype._setupBackground = function () {
  91028. if (!this._rootMesh) {
  91029. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  91030. }
  91031. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  91032. var sceneSize = this._getSceneSize();
  91033. if (this._options.createGround) {
  91034. this._setupGround(sceneSize);
  91035. this._setupGroundMaterial();
  91036. this._setupGroundDiffuseTexture();
  91037. if (this._options.enableGroundMirror) {
  91038. this._setupGroundMirrorTexture(sceneSize);
  91039. }
  91040. this._setupMirrorInGroundMaterial();
  91041. }
  91042. if (this._options.createSkybox) {
  91043. this._setupSkybox(sceneSize);
  91044. this._setupSkyboxMaterial();
  91045. this._setupSkyboxReflectionTexture();
  91046. }
  91047. this._rootMesh.position.x = sceneSize.rootPosition.x;
  91048. this._rootMesh.position.z = sceneSize.rootPosition.z;
  91049. this._rootMesh.position.y = sceneSize.rootPosition.y;
  91050. };
  91051. /**
  91052. * Get the scene sizes according to the setup.
  91053. */
  91054. EnvironmentHelper.prototype._getSceneSize = function () {
  91055. var _this = this;
  91056. var groundSize = this._options.groundSize;
  91057. var skyboxSize = this._options.skyboxSize;
  91058. var rootPosition = this._options.rootPosition;
  91059. if (!this._scene.meshes || this._scene.meshes.length === 1) {
  91060. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  91061. }
  91062. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  91063. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  91064. });
  91065. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  91066. if (this._options.sizeAuto) {
  91067. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  91068. this._scene.activeCamera.upperRadiusLimit) {
  91069. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  91070. skyboxSize = groundSize;
  91071. }
  91072. var sceneDiagonalLenght = sceneDiagonal.length();
  91073. if (sceneDiagonalLenght > groundSize) {
  91074. groundSize = sceneDiagonalLenght * 2;
  91075. skyboxSize = groundSize;
  91076. }
  91077. // 10 % bigger.
  91078. groundSize *= 1.1;
  91079. skyboxSize *= 1.5;
  91080. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  91081. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  91082. }
  91083. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  91084. };
  91085. /**
  91086. * Setup the ground according to the specified options.
  91087. */
  91088. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  91089. var _this = this;
  91090. if (!this._ground) {
  91091. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  91092. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  91093. this._ground.parent = this._rootMesh;
  91094. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  91095. }
  91096. this._ground.receiveShadows = this._options.enableGroundShadow;
  91097. };
  91098. /**
  91099. * Setup the ground material according to the specified options.
  91100. */
  91101. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  91102. if (!this._groundMaterial) {
  91103. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  91104. }
  91105. this._groundMaterial.alpha = this._options.groundOpacity;
  91106. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  91107. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  91108. this._groundMaterial.primaryLevel = 1;
  91109. this._groundMaterial.primaryColor = this._options.groundColor;
  91110. this._groundMaterial.secondaryLevel = 0;
  91111. this._groundMaterial.tertiaryLevel = 0;
  91112. this._groundMaterial.useRGBColor = false;
  91113. this._groundMaterial.enableNoise = true;
  91114. if (this._ground) {
  91115. this._ground.material = this._groundMaterial;
  91116. }
  91117. };
  91118. /**
  91119. * Setup the ground diffuse texture according to the specified options.
  91120. */
  91121. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  91122. if (!this._groundMaterial) {
  91123. return;
  91124. }
  91125. if (this._groundTexture) {
  91126. return;
  91127. }
  91128. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  91129. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  91130. return;
  91131. }
  91132. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  91133. diffuseTexture.gammaSpace = false;
  91134. diffuseTexture.hasAlpha = true;
  91135. this._groundMaterial.diffuseTexture = diffuseTexture;
  91136. };
  91137. /**
  91138. * Setup the ground mirror texture according to the specified options.
  91139. */
  91140. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  91141. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  91142. if (!this._groundMirror) {
  91143. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  91144. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  91145. this._groundMirror.anisotropicFilteringLevel = 1;
  91146. this._groundMirror.wrapU = wrapping;
  91147. this._groundMirror.wrapV = wrapping;
  91148. this._groundMirror.gammaSpace = false;
  91149. if (this._groundMirror.renderList) {
  91150. for (var i = 0; i < this._scene.meshes.length; i++) {
  91151. var mesh = this._scene.meshes[i];
  91152. if (mesh !== this._ground &&
  91153. mesh !== this._skybox &&
  91154. mesh !== this._rootMesh) {
  91155. this._groundMirror.renderList.push(mesh);
  91156. }
  91157. }
  91158. }
  91159. }
  91160. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  91161. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  91162. };
  91163. /**
  91164. * Setup the ground to receive the mirror texture.
  91165. */
  91166. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  91167. if (this._groundMaterial) {
  91168. this._groundMaterial.reflectionTexture = this._groundMirror;
  91169. this._groundMaterial.reflectionFresnel = true;
  91170. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  91171. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  91172. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  91173. }
  91174. };
  91175. /**
  91176. * Setup the skybox according to the specified options.
  91177. */
  91178. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  91179. var _this = this;
  91180. if (!this._skybox) {
  91181. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  91182. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  91183. }
  91184. this._skybox.parent = this._rootMesh;
  91185. };
  91186. /**
  91187. * Setup the skybox material according to the specified options.
  91188. */
  91189. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  91190. if (!this._skybox) {
  91191. return;
  91192. }
  91193. if (!this._skyboxMaterial) {
  91194. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  91195. }
  91196. this._skyboxMaterial.useRGBColor = false;
  91197. this._skyboxMaterial.primaryLevel = 1;
  91198. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  91199. this._skyboxMaterial.secondaryLevel = 0;
  91200. this._skyboxMaterial.tertiaryLevel = 0;
  91201. this._skyboxMaterial.enableNoise = true;
  91202. this._skybox.material = this._skyboxMaterial;
  91203. };
  91204. /**
  91205. * Setup the skybox reflection texture according to the specified options.
  91206. */
  91207. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  91208. if (!this._skyboxMaterial) {
  91209. return;
  91210. }
  91211. if (this._skyboxTexture) {
  91212. return;
  91213. }
  91214. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  91215. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  91216. return;
  91217. }
  91218. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  91219. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  91220. this._skyboxTexture.gammaSpace = false;
  91221. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  91222. };
  91223. /**
  91224. * Dispose all the elements created by the Helper.
  91225. */
  91226. EnvironmentHelper.prototype.dispose = function () {
  91227. if (this._groundMaterial) {
  91228. this._groundMaterial.dispose(true, true);
  91229. }
  91230. if (this._skyboxMaterial) {
  91231. this._skyboxMaterial.dispose(true, true);
  91232. }
  91233. this._rootMesh.dispose(false);
  91234. };
  91235. /**
  91236. * Default ground texture URL.
  91237. */
  91238. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  91239. /**
  91240. * Default skybox texture URL.
  91241. */
  91242. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  91243. /**
  91244. * Default environment texture URL.
  91245. */
  91246. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.dds";
  91247. return EnvironmentHelper;
  91248. }());
  91249. BABYLON.EnvironmentHelper = EnvironmentHelper;
  91250. })(BABYLON || (BABYLON = {}));
  91251. //# sourceMappingURL=babylon.environmentHelper.js.map
  91252. var BABYLON;
  91253. (function (BABYLON) {
  91254. /**
  91255. * Display a 360 degree video on an approximately spherical surface, useful for VR applications or skyboxes.
  91256. * As a subclass of Node, this allow parenting to the camera or multiple videos with different locations in the scene.
  91257. * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere.
  91258. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  91259. */
  91260. var VideoDome = /** @class */ (function (_super) {
  91261. __extends(VideoDome, _super);
  91262. /**
  91263. * Create an instance of this class and pass through the parameters to the relevant classes, VideoTexture, StandardMaterial, and Mesh.
  91264. * @param name Element's name, child elements will append suffixes for their own names.
  91265. * @param urlsOrVideo
  91266. * @param options An object containing optional or exposed sub element properties:
  91267. * @param options **resolution=12** Integer, lower resolutions have more artifacts at extreme fovs
  91268. * @param options **clickToPlay=false** Add a click to play listener to the video, does not prevent autoplay.
  91269. * @param options **autoPlay=true** Automatically attempt to being playing the video.
  91270. * @param options **loop=true** Automatically loop video on end.
  91271. * @param options **size=1000** Physical radius to create the dome at, defaults to approximately half the far clip plane.
  91272. */
  91273. function VideoDome(name, urlsOrVideo, options, scene) {
  91274. var _this = _super.call(this, name, scene) || this;
  91275. // set defaults and manage values
  91276. name = name || "videoDome";
  91277. options.resolution = (Math.abs(options.resolution) | 0) || 12;
  91278. options.clickToPlay = Boolean(options.clickToPlay);
  91279. options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay);
  91280. options.loop = options.loop === undefined ? true : Boolean(options.loop);
  91281. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  91282. // create
  91283. var tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true };
  91284. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  91285. var texture = _this._videoTexture = new BABYLON.VideoTexture(name + "_texture", urlsOrVideo, scene, false, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, tempOptions);
  91286. _this._mesh = BABYLON.MeshBuilder.CreateIcoSphere(name + "_mesh", {
  91287. flat: false,
  91288. radius: options.size,
  91289. subdivisions: options.resolution,
  91290. sideOrientation: BABYLON.Mesh.BACKSIDE // needs to be inside out
  91291. }, scene);
  91292. // configure material
  91293. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  91294. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE; // always clamp the up/down
  91295. material.reflectionTexture = _this._videoTexture;
  91296. material.useEquirectangularFOV = true;
  91297. material.fovMultiplier = 1.0;
  91298. // configure mesh
  91299. _this._mesh.material = material;
  91300. _this._mesh.parent = _this;
  91301. // optional configuration
  91302. if (options.clickToPlay) {
  91303. scene.onPointerUp = function () {
  91304. _this._videoTexture.video.play();
  91305. };
  91306. }
  91307. return _this;
  91308. }
  91309. Object.defineProperty(VideoDome.prototype, "fovMultiplier", {
  91310. /**
  91311. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  91312. * Also see the options.resolution property.
  91313. */
  91314. get: function () {
  91315. return this._material.fovMultiplier;
  91316. },
  91317. set: function (value) {
  91318. this._material.fovMultiplier = value;
  91319. },
  91320. enumerable: true,
  91321. configurable: true
  91322. });
  91323. /**
  91324. * Releases resources associated with this node.
  91325. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  91326. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  91327. */
  91328. VideoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  91329. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  91330. this._videoTexture.dispose();
  91331. this._mesh.dispose();
  91332. this._material.dispose();
  91333. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  91334. };
  91335. return VideoDome;
  91336. }(BABYLON.Node));
  91337. BABYLON.VideoDome = VideoDome;
  91338. })(BABYLON || (BABYLON = {}));
  91339. //# sourceMappingURL=babylon.videoDome.js.map
  91340. BABYLON.Effect.ShadersStore={"defaultVertexShader":"#include<__decl__defaultVertex>\n\n#define CUSTOM_VERTEX_BEGIN\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nvarying vec2 vSpecularUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvec3 positionUpdated=position;\n#ifdef NORMAL \nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#define CUSTOM_VERTEX_UPDATE_POSITION\n#define CUSTOM_VERTEX_UPDATE_NORMAL\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif\n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<bumpVertex>\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n#include<pointCloudVertex>\n#include<logDepthVertex>\n#define CUSTOM_VERTEX_MAIN_END\n}\n","defaultPixelShader":"#include<__decl__defaultFragment>\n#if defined(BUMP) || !defined(NORMAL)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#define CUSTOM_FRAGMENT_BEGIN\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n\n#define RECIPROCAL_PI2 0.15915494\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY \n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\n#if SPECULARDIRECTUV == 1\n#define vSpecularUV vMainUV1\n#elif SPECULARDIRECTUV == 2\n#define vSpecularUV vMainUV2\n#else\nvarying vec2 vSpecularUV;\n#endif\nuniform sampler2D specularSampler;\n#endif\n\n#include<fresnelFunction>\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#include<imageProcessingDeclaration>\n#include<imageProcessingFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#include<fogFragmentDeclaration>\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(-cross(dFdx(vPositionW),dFdy(vPositionW)));\n#endif\n#include<bumpFragment>\n#ifdef TWOSIDEDLIGHTING\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#ifdef ALPHAFROMDIFFUSE\nalpha*=baseColor.a;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_ALPHA\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_DIFFUSE\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_LIGHTS\n\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV+uvOffset);\nspecularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#else\nfloat glossiness=0.;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nfloat shadow=1.;\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\n\nvec3 refractionColor=vec3(0.,0.,0.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0)\n{\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb*vRefractionInfos.x;\n}\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\nrefractionColor=texture2D(refraction2DSampler,refractionCoords).rgb*vRefractionInfos.x;\n#endif\n#endif\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nfloat bias=vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias).rgb*vReflectionInfos.x;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb*vReflectionInfos.x;\n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb*vReflectionInfos.x;\n#endif\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);\nrefractionColor*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\n#ifdef LINKEMISSIVEWITHDIFFUSE\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#endif\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef REFLECTIONOVERALPHA\nalpha=clamp(alpha+dot(reflectionColor,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+emissiveColor+refractionColor,0.0,1.0),alpha);\n#else\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+refractionColor,alpha);\n#endif\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FOG\ncolor.rgb=max(color.rgb,0.);\n#include<logDepthFragment>\n#include<fogFragment>\n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\ncolor.rgb=toLinearSpace(color.rgb);\n#else\n#ifdef IMAGEPROCESSING\ncolor.rgb=toLinearSpace(color.rgb);\ncolor=applyImageProcessing(color);\n#endif\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR\ngl_FragColor=color;\n}\n","pbrVertexShader":"precision highp float;\n#include<__decl__pbrVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif \n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#if defined(ALBEDO) && ALBEDODIRECTUV == 0\nvarying vec2 vAlbedoUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0\nvarying vec2 vReflectivityUV;\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#include<harmonicsFunctions>\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL\nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvec3 reflectionVector=vec3(reflectionMatrix*vec4(vNormalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\nvEnvironmentIrradiance=environmentIrradianceJones(reflectionVector);\n#endif\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif \n#if defined(ALBEDO) && ALBEDODIRECTUV == 0 \nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0 \nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0 \nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0 \nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0 \nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0 \nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0 \nif (vMicroSurfaceSamplerInfos.x == 0.)\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0 \nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<bumpVertex>\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n\n#include<logDepthVertex>\n}","pbrPixelShader":"#if defined(BUMP) || !defined(NORMAL) || defined(FORCENORMALFORWARD)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LODBASEDMICROSFURACE\n#extension GL_EXT_shader_texture_lod : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nprecision highp float;\n#include<__decl__pbrFragment>\nuniform vec4 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vCameraInfos;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2;\n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\n#if ALBEDODIRECTUV == 1\n#define vAlbedoUV vMainUV1\n#elif ALBEDODIRECTUV == 2\n#define vAlbedoUV vMainUV2\n#else\nvarying vec2 vAlbedoUV;\n#endif\nuniform sampler2D albedoSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY\n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFLECTIVITY\n#if REFLECTIVITYDIRECTUV == 1\n#define vReflectivityUV vMainUV1\n#elif REFLECTIVITYDIRECTUV == 2\n#define vReflectivityUV vMainUV2\n#else\nvarying vec2 vReflectivityUV;\n#endif\nuniform sampler2D reflectivitySampler;\n#endif\n#ifdef MICROSURFACEMAP\n#if MICROSURFACEMAPDIRECTUV == 1\n#define vMicroSurfaceSamplerUV vMainUV1\n#elif MICROSURFACEMAPDIRECTUV == 2\n#define vMicroSurfaceSamplerUV vMainUV2\n#else\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\nuniform sampler2D microSurfaceSampler;\n#endif\n\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\n#define sampleRefraction(s,c) textureCube(s,c)\nuniform samplerCube refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#else\n#define sampleRefraction(s,c) texture2D(s,c)\nuniform sampler2D refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#endif\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#ifdef ENVIRONMENTBRDF\nuniform sampler2D environmentBrdfSampler;\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\n\n#include<shadowsFragmentFunctions>\n#include<pbrFunctions>\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\n\n\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#endif\n#include<bumpFragment>\n#if defined(FORCENORMALFORWARD) && defined(NORMAL)\nvec3 faceNormal=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#if defined(TWOSIDEDLIGHTING)\nfaceNormal=gl_FrontFacing ? faceNormal : -faceNormal;\n#endif\nnormalW*=sign(dot(normalW,faceNormal));\n#endif\n#if defined(TWOSIDEDLIGHTING) && defined(NORMAL)\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n\n\nvec3 surfaceAlbedo=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nvec4 albedoTexture=texture2D(albedoSampler,vAlbedoUV+uvOffset);\n#if defined(ALPHAFROMALBEDO) || defined(ALPHATEST)\nalpha*=albedoTexture.a;\n#endif\nsurfaceAlbedo*=toLinearSpace(albedoTexture.rgb);\nsurfaceAlbedo*=vAlbedoInfos.y;\n#endif\n\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nalpha=getLuminance(opacityMap.rgb);\n#else\nalpha*=opacityMap.a;\n#endif\nalpha*=vOpacityInfos.y;\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#if !defined(LINKREFRACTIONTOTRANSPARENCY) && !defined(ALPHAFRESNEL)\n#ifdef ALPHATEST\nif (alpha<=ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nsurfaceAlbedo*=vColor.rgb;\n#endif\n\nvec3 ambientOcclusionColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nvec3 ambientOcclusionColorMap=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#ifdef AMBIENTINGRAYSCALE\nambientOcclusionColorMap=vec3(ambientOcclusionColorMap.r,ambientOcclusionColorMap.r,ambientOcclusionColorMap.r);\n#endif\nambientOcclusionColor=mix(ambientOcclusionColor,ambientOcclusionColorMap,vAmbientInfos.z);\n#endif\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef METALLICWORKFLOW\nvec2 metallicRoughness=surfaceReflectivityColor.rg;\n#ifdef REFLECTIVITY\nvec4 surfaceMetallicColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\n#ifdef AOSTOREINMETALMAPRED\nvec3 aoStoreInMetalMap=vec3(surfaceMetallicColorMap.r,surfaceMetallicColorMap.r,surfaceMetallicColorMap.r);\nambientOcclusionColor=mix(ambientOcclusionColor,aoStoreInMetalMap,vReflectivityInfos.z);\n#endif\n#ifdef METALLNESSSTOREINMETALMAPBLUE\nmetallicRoughness.r*=surfaceMetallicColorMap.b;\n#else\nmetallicRoughness.r*=surfaceMetallicColorMap.r;\n#endif\n#ifdef ROUGHNESSSTOREINMETALMAPALPHA\nmetallicRoughness.g*=surfaceMetallicColorMap.a;\n#else\n#ifdef ROUGHNESSSTOREINMETALMAPGREEN\nmetallicRoughness.g*=surfaceMetallicColorMap.g;\n#endif\n#endif\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmetallicRoughness.g*=microSurfaceTexel.r;\n#endif\n\nmicroSurface=1.0-metallicRoughness.g;\n\nvec3 baseColor=surfaceAlbedo;\n\n\nconst vec3 DefaultSpecularReflectanceDielectric=vec3(0.04,0.04,0.04);\n\nsurfaceAlbedo=mix(baseColor.rgb*(1.0-DefaultSpecularReflectanceDielectric.r),vec3(0.,0.,0.),metallicRoughness.r);\n\nsurfaceReflectivityColor=mix(DefaultSpecularReflectanceDielectric,baseColor,metallicRoughness.r);\n#else\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\nsurfaceReflectivityColor*=toLinearSpace(surfaceReflectivityColorMap.rgb);\nsurfaceReflectivityColor*=vReflectivityInfos.y;\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface*=surfaceReflectivityColorMap.a;\nmicroSurface*=vReflectivityInfos.z;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface*=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmicroSurface*=microSurfaceTexel.r;\n#endif\n#endif\n#endif\n#endif\n\nmicroSurface=clamp(microSurface,0.,1.);\n\nfloat roughness=1.-microSurface;\n\n#ifdef ALPHAFRESNEL\n#if defined(ALPHATEST) || defined(ALPHABLEND)\n\n\n\nfloat opacityPerceptual=alpha;\n#ifdef LINEARALPHAFRESNEL\nfloat opacity0=opacityPerceptual;\n#else\nfloat opacity0=opacityPerceptual*opacityPerceptual;\n#endif\nfloat opacity90=fresnelGrazingReflectance(opacity0);\nvec3 normalForward=faceforward(normalW,-viewDirectionW,normalW);\n\nalpha=fresnelSchlickEnvironmentGGX(clamp(dot(viewDirectionW,normalForward),0.0,1.0),vec3(opacity0),vec3(opacity90),sqrt(microSurface)).x;\n#ifdef ALPHATEST\nif (alpha<=ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#endif\n\n\nfloat NdotVUnclamped=dot(normalW,viewDirectionW);\nfloat NdotV=clamp(NdotVUnclamped,0.,1.)+0.00001;\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\n\n#ifdef REFRACTION\nvec3 environmentRefraction=vec3(0.,0.,0.);\nvec3 refractionVector=refract(-viewDirectionW,normalW,vRefractionInfos.y);\n#ifdef REFRACTIONMAP_OPPOSITEZ\nrefractionVector.z*=-1.0;\n#endif\n\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nvec3 refractionCoords=refractionVector;\nrefractionCoords=vec3(refractionMatrix*vec4(refractionCoords,0));\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\n#endif\n#ifdef LODINREFRACTIONALPHA\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,1.0);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nrefractionLOD=refractionLOD*vRefractionMicrosurfaceInfos.y+vRefractionMicrosurfaceInfos.z;\n#ifdef LODINREFRACTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticRefractionLOD=UNPACK_LOD(sampleRefraction(refractionSampler,refractionCoords).a);\nfloat requestedRefractionLOD=max(automaticRefractionLOD,refractionLOD);\n#else\nfloat requestedRefractionLOD=refractionLOD;\n#endif\nenvironmentRefraction=sampleRefractionLod(refractionSampler,refractionCoords,requestedRefractionLOD).rgb;\n#else\nfloat lodRefractionNormalized=clamp(refractionLOD/log2(vRefractionMicrosurfaceInfos.x),0.,1.);\nfloat lodRefractionNormalizedDoubled=lodRefractionNormalized*2.0;\nvec3 environmentRefractionMid=sampleRefraction(refractionSampler,refractionCoords).rgb;\nif(lodRefractionNormalizedDoubled<1.0){\nenvironmentRefraction=mix(\nsampleRefraction(refractionSamplerHigh,refractionCoords).rgb,\nenvironmentRefractionMid,\nlodRefractionNormalizedDoubled\n);\n}else{\nenvironmentRefraction=mix(\nenvironmentRefractionMid,\nsampleRefraction(refractionSamplerLow,refractionCoords).rgb,\nlodRefractionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFRACTION\nenvironmentRefraction=toLinearSpace(environmentRefraction.rgb);\n#endif\n\nenvironmentRefraction*=vRefractionInfos.x;\n#endif\n\n#ifdef REFLECTION\nvec3 environmentRadiance=vec3(0.,0.,0.);\nvec3 environmentIrradiance=vec3(0.,0.,0.);\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,1.);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nreflectionLOD=reflectionLOD*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\n#ifdef LODINREFLECTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticReflectionLOD=UNPACK_LOD(sampleReflection(reflectionSampler,reflectionCoords).a);\nfloat requestedReflectionLOD=max(automaticReflectionLOD,reflectionLOD);\n#else\nfloat requestedReflectionLOD=reflectionLOD;\n#endif\nenvironmentRadiance=sampleReflectionLod(reflectionSampler,reflectionCoords,requestedReflectionLOD).rgb;\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD/log2(vReflectionMicrosurfaceInfos.x),0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec3 environmentSpecularMid=sampleReflection(reflectionSampler,reflectionCoords).rgb;\nif(lodReflectionNormalizedDoubled<1.0){\nenvironmentRadiance=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords).rgb,\nenvironmentSpecularMid,\nlodReflectionNormalizedDoubled\n);\n}else{\nenvironmentRadiance=mix(\nenvironmentSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords).rgb,\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFLECTION\nenvironmentRadiance=toLinearSpace(environmentRadiance.rgb);\n#endif\n\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#if defined(NORMAL) && defined(USESPHERICALINVERTEX)\nenvironmentIrradiance=vEnvironmentIrradiance;\n#else\nvec3 irradianceVector=vec3(reflectionMatrix*vec4(normalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nirradianceVector.z*=-1.0;\n#endif\nenvironmentIrradiance=environmentIrradianceJones(irradianceVector);\n#endif\n#endif\n\nenvironmentRadiance*=vReflectionInfos.x;\nenvironmentRadiance*=vReflectionColor.rgb;\nenvironmentIrradiance*=vReflectionColor.rgb;\n#endif\n\n\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\nfloat reflectance90=fresnelGrazingReflectance(reflectance);\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0)*reflectance90;\n\nvec3 diffuseBase=vec3(0.,0.,0.);\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\n#ifdef LIGHTMAP\nvec3 lightmapColor=toLinearSpace(texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb)*vLightmapInfos.y;\n#endif\nlightingInfo info;\nfloat shadow=1.; \nfloat NdotL=-1.;\n#include<lightFragment>[0..maxSimultaneousLights]\n\n#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\n\nvec2 brdfSamplerUV=vec2(NdotV,roughness);\n\nvec4 environmentBrdf=texture2D(environmentBrdfSampler,brdfSamplerUV);\nvec3 specularEnvironmentReflectance=specularEnvironmentR0*environmentBrdf.x+environmentBrdf.y;\n#ifdef RADIANCEOCCLUSION\n#ifdef AMBIENTINGRAYSCALE\nfloat ambientMonochrome=ambientOcclusionColor.r;\n#else\nfloat ambientMonochrome=getLuminance(ambientOcclusionColor);\n#endif\nfloat seo=environmentRadianceOcclusion(ambientMonochrome,NdotVUnclamped);\nspecularEnvironmentReflectance*=seo;\n#endif\n#ifdef HORIZONOCCLUSION\n#ifdef BUMP\n#ifdef REFLECTIONMAP_3D\nfloat eho=environmentHorizonOcclusion(reflectionCoords,normalW);\nspecularEnvironmentReflectance*=eho;\n#endif\n#endif\n#endif\n#else\n\nvec3 specularEnvironmentReflectance=fresnelSchlickEnvironmentGGX(NdotV,specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n#endif\n\n#ifdef REFRACTION\nvec3 refractance=vec3(0.0,0.0,0.0);\nvec3 transmission=vec3(1.0,1.0,1.0);\n#ifdef LINKREFRACTIONTOTRANSPARENCY\n\ntransmission*=(1.0-alpha);\n\n\nvec3 mixedAlbedo=surfaceAlbedo;\nfloat maxChannel=max(max(mixedAlbedo.r,mixedAlbedo.g),mixedAlbedo.b);\nvec3 tint=clamp(maxChannel*mixedAlbedo,0.0,1.0);\n\nsurfaceAlbedo*=alpha;\n\nenvironmentIrradiance*=alpha;\n\nenvironmentRefraction*=tint;\n\nalpha=1.0;\n#endif\n\nvec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);\nspecularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,alpha);\n\ntransmission*=1.0-specularEnvironmentReflectance;\n\nrefractance=transmission;\n#endif\n\n\n\n\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\n\nvec3 finalDiffuse=diffuseBase;\nfinalDiffuse.rgb+=vAmbientColor;\nfinalDiffuse*=surfaceAlbedo.rgb;\nfinalDiffuse=max(finalDiffuse,0.0);\n\n#ifdef REFLECTION\nvec3 finalIrradiance=environmentIrradiance;\nfinalIrradiance*=surfaceAlbedo.rgb;\n#endif\n\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase;\nfinalSpecular=max(finalSpecular,0.0);\n\nvec3 finalSpecularScaled=finalSpecular*vLightingIntensity.x*vLightingIntensity.w;\n#endif\n\n#ifdef REFLECTION\nvec3 finalRadiance=environmentRadiance;\nfinalRadiance*=specularEnvironmentReflectance;\n\nvec3 finalRadianceScaled=finalRadiance*vLightingIntensity.z;\n#endif\n\n#ifdef REFRACTION\nvec3 finalRefraction=environmentRefraction;\nfinalRefraction*=refractance;\n#endif\n\nvec3 finalEmissive=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb;\nfinalEmissive*=toLinearSpace(emissiveColorTex.rgb);\nfinalEmissive*=vEmissiveInfos.y;\n#endif\n\n#ifdef ALPHABLEND\nfloat luminanceOverAlpha=0.0;\n#if defined(REFLECTION) && defined(RADIANCEOVERALPHA)\nluminanceOverAlpha+=getLuminance(finalRadianceScaled);\n#endif\n#if defined(SPECULARTERM) && defined(SPECULAROVERALPHA)\nluminanceOverAlpha+=getLuminance(finalSpecularScaled);\n#endif\n#if defined(RADIANCEOVERALPHA) || defined(SPECULAROVERALPHA)\nalpha=clamp(alpha+luminanceOverAlpha*luminanceOverAlpha,0.,1.);\n#endif\n#endif\n\n\n\nvec4 finalColor=vec4(finalDiffuse*ambientOcclusionColor*vLightingIntensity.x +\n#ifdef REFLECTION\nfinalIrradiance*ambientOcclusionColor*vLightingIntensity.z +\n#endif\n#ifdef SPECULARTERM\n\n\nfinalSpecularScaled +\n#endif\n#ifdef REFLECTION\n\n\nfinalRadianceScaled +\n#endif\n#ifdef REFRACTION\nfinalRefraction*vLightingIntensity.z +\n#endif\nfinalEmissive*vLightingIntensity.y,\nalpha);\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor;\n#else\nfinalColor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n\nfinalColor=max(finalColor,0.0);\n#include<logDepthFragment>\n#include<fogFragment>(color,finalColor)\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\nfinalColor.rgb=clamp(finalColor.rgb,0.,30.0);\n#else\n\nfinalColor=applyImageProcessing(finalColor);\n#endif\n#ifdef PREMULTIPLYALPHA\n\nfinalColor.rgb*=finalColor.a;\n#endif\ngl_FragColor=finalColor;\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n}","spritesVertexShader":"\nattribute vec4 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#include<fogVertexDeclaration>\nvoid main(void) { \nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; \nvec2 cornerPos;\nfloat angle=position.w;\nvec2 size=vec2(options.x,options.y);\nvec2 offset=options.zw;\nvec2 uvScale=textureInfos.xy;\ncornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \n\nvColor=color;\n\nvec2 uvOffset=vec2(abs(offset.x-cellInfo.x),1.0-abs(offset.y-cellInfo.y));\nvUV=(uvOffset+cellInfo.zw)*uvScale;\n\n#ifdef FOG\nvFogDistance=viewPos;\n#endif\n}","spritesPixelShader":"uniform bool alphaTest;\nvarying vec4 vColor;\n\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (alphaTest) \n{\nif (color.a<0.95)\ndiscard;\n}\ncolor*=vColor;\n#include<fogFragment>\ngl_FragColor=color;\n}","particlesVertexShader":"\nattribute vec3 position;\nattribute vec4 color;\nattribute vec4 options;\nattribute float cellIndex;\n\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec3 particlesInfos; \n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nvarying float fClipDistance;\n#endif\nvoid main(void) { \nvec3 viewPos=(view*vec4(position,1.0)).xyz; \nvec3 cornerPos;\nfloat size=options.y;\nfloat angle=options.x;\nvec2 offset=options.zw;\ncornerPos=vec3(offset.x-0.5,offset.y-0.5,0.)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \nvColor=color;\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex/particlesInfos.z);\nfloat columnOffset=cellIndex-rowOffset*particlesInfos.z;\nvec2 uvScale=particlesInfos.xy;\nvec2 uvOffset=vec2(offset.x ,1.0-offset.y);\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else\nvUV=offset;\n#endif\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*vec4(viewPos,1.0);\nfClipDistance=dot(worldPos,vClipPlane);\n#endif\n}","particlesPixelShader":"\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\nvoid main(void) {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif\nvec4 baseColor=texture2D(diffuseSampler,vUV);\ngl_FragColor=(baseColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n}","gpuRenderParticlesVertexShader":"#version 300 es\nuniform vec4 colorDead;\nuniform mat4 view;\nuniform mat4 projection;\n\nin vec3 position;\nin float age;\nin float life;\nin float size;\nin vec4 color;\nin vec2 offset;\nin vec2 uv;\nout vec2 vUV;\nout vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nout float fClipDistance;\n#endif\nvoid main() {\nvUV=uv;\nfloat ratio=age/life;\nvColor=color*vec4(1.0-ratio)+colorDead*vec4(ratio);\n\nvec4 viewPosition=view*vec4(position,1.0);\ngl_Position=projection*(viewPosition+vec4(offset*size,0.,0.));\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*viewPosition;\nfClipDistance=dot(worldPos,vClipPlane);\n#endif \n}","gpuRenderParticlesPixelShader":"#version 300 es\nuniform sampler2D textureSampler;\nin vec2 vUV;\nin vec4 vColor;\nout vec4 outFragColor;\n#ifdef CLIPPLANE\nin float fClipDistance;\n#endif\nvoid main() {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif \noutFragColor=texture(textureSampler,vUV)*vColor;\n}\n","gpuUpdateParticlesVertexShader":"#version 300 es\n#define PI 3.14159\nuniform float currentCount;\nuniform float timeDelta;\nuniform float stopFactor;\nuniform vec3 generalRandoms;\nuniform mat4 emitterWM;\nuniform vec2 lifeTime;\nuniform vec2 emitPower;\nuniform vec2 sizeRange;\nuniform vec4 color1;\nuniform vec4 color2;\nuniform vec3 gravity;\nuniform sampler2D randomSampler;\n#ifdef BOXEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\nuniform vec3 minEmitBox;\nuniform vec3 maxEmitBox;\n#endif\n#ifdef SPHEREEMITTER\nuniform float radius;\n#ifdef DIRECTEDSPHEREEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\n#else\nuniform float directionRandomizer;\n#endif\n#endif\n#ifdef CONEEMITTER\nuniform float radius;\nuniform float angle;\nuniform float height;\nuniform float directionRandomizer;\n#endif\n\nin vec3 position;\nin float age;\nin float life;\nin float seed;\nin float size;\nin vec4 color;\nin vec3 direction;\n\nout vec3 outPosition;\nout float outAge;\nout float outLife;\nout float outSeed;\nout float outSize;\nout vec4 outColor;\nout vec3 outDirection;\nvec3 getRandomVec3(float offset) {\nreturn texture(randomSampler,vec2(float(gl_VertexID)*offset/currentCount,0)).rgb;\n}\nvec4 getRandomVec4(float offset) {\nreturn texture(randomSampler,vec2(float(gl_VertexID)*offset/currentCount,0));\n}\nvoid main() {\nif (age>=life) {\nif (stopFactor == 0.) {\noutPosition=position;\noutAge=life;\noutLife=life;\noutSeed=seed;\noutColor=vec4(0.,0.,0.,0.);\noutSize=0.;\noutDirection=direction;\nreturn;\n}\nvec3 position;\nvec3 direction;\n\nvec4 randoms=getRandomVec4(generalRandoms.x);\n\noutAge=0.0;\noutLife=lifeTime.x+(lifeTime.y-lifeTime.x)*randoms.r;\n\noutSeed=seed;\n\noutSize=sizeRange.x+(sizeRange.y-sizeRange.x)*randoms.g;\n\noutColor=color1+(color2-color1)*randoms.b;\n\n#ifdef BOXEMITTER\nvec3 randoms2=getRandomVec3(generalRandoms.y);\nvec3 randoms3=getRandomVec3(generalRandoms.z);\nposition=minEmitBox+(maxEmitBox-minEmitBox)*randoms2;\ndirection=direction1+(direction2-direction1)*randoms3;\n#elif defined(SPHEREEMITTER)\nvec3 randoms2=getRandomVec3(generalRandoms.y);\nvec3 randoms3=getRandomVec3(generalRandoms.z);\n\nfloat phi=2.0*PI*randoms2.x;\nfloat theta=PI*randoms2.y;\nfloat randX=cos(phi)*sin(theta);\nfloat randY=cos(theta);\nfloat randZ=sin(phi)*sin(theta);\nposition=(radius*randoms2.z)*vec3(randX,randY,randZ);\n#ifdef DIRECTEDSPHEREEMITTER\ndirection=direction1+(direction2-direction1)*randoms3;\n#else\n\ndirection=position+directionRandomizer*randoms3;\n#endif\n#elif defined(CONEEMITTER)\nvec3 randoms2=getRandomVec3(generalRandoms.y);\nfloat s=2.0*PI*randoms2.x;\nfloat h=randoms2.y;\n\nh=1.-h*h;\nfloat lRadius=radius*randoms2.z;\nlRadius=lRadius*h/height;\nfloat randX=lRadius*sin(s);\nfloat randZ=lRadius*cos(s);\nfloat randY=h*height;\nposition=vec3(randX,randY,randZ); \n\nif (angle == 0.) {\ndirection=vec3(0.,1.0,0.);\n} else {\nvec3 randoms3=getRandomVec3(generalRandoms.z);\ndirection=position+directionRandomizer*randoms3;\n}\n#else \n\nposition=vec3(0.,0.,0.);\n\ndirection=2.0*(getRandomVec3(seed)-vec3(0.5,0.5,0.5));\n#endif\nfloat power=emitPower.x+(emitPower.y-emitPower.x)*randoms.a;\noutPosition=(emitterWM*vec4(position,1.)).xyz;\noutDirection=(emitterWM*vec4(direction*power,0.)).xyz;\n} else { \noutPosition=position+direction*timeDelta;\noutAge=age+timeDelta;\noutLife=life;\noutSeed=seed;\noutColor=color;\noutSize=size;\noutDirection=direction+gravity*timeDelta;\n}\n}","gpuUpdateParticlesPixelShader":"#version 300 es\nvoid main() {\ndiscard;\n}\n","colorVertexShader":"\nattribute vec3 position;\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\nuniform mat4 viewProjection;\nuniform mat4 world;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\nvoid main(void) {\nmat4 finalWorld=world;\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n}","colorPixelShader":"#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#else\nuniform vec4 color;\n#endif\nvoid main(void) {\n#ifdef VERTEXCOLOR\ngl_FragColor=vColor;\n#else\ngl_FragColor=color;\n#endif\n}","postprocessVertexShader":"\nattribute vec2 position;\nuniform vec2 scale;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd)*scale;\ngl_Position=vec4(position,0.0,1.0);\n}","passPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\n}","shadowMapVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 biasAndScale;\nuniform vec2 depthValues;\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 worldPos=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*worldPos;\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y))+biasAndScale.x;\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","shadowMapPixelShader":"#ifndef FLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nuniform vec2 biasAndScale;\nuniform vec2 depthValues;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nfloat depth=vDepthMetric;\n#ifdef ESM\ndepth=clamp(exp(-min(87.,biasAndScale.y*depth)),0.,1.);\n#endif\n#ifdef FLOAT\ngl_FragColor=vec4(depth,1.0,1.0,1.0);\n#else\ngl_FragColor=pack(depth);\n#endif\n}","depthBoxBlurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nvoid main(void)\n{\nvec4 colorDepth=vec4(0.0);\nfor (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);\ngl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));\n}","proceduralVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvPosition=position;\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","depthVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 depthValues;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y));\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","depthPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(vDepthMetric,vDepthMetric*vDepthMetric,0.0,1.0);\n}","ssaoPixelShader":"\nuniform sampler2D textureSampler;\nvarying vec2 vUV;\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float radius;\nuniform float area;\nuniform float fallOff;\nuniform float base;\nvec3 normalFromDepth(float depth,vec2 coords)\n{\nvec2 offset1=vec2(0.0,radius);\nvec2 offset2=vec2(radius,0.0);\nfloat depth1=texture2D(textureSampler,coords+offset1).r;\nfloat depth2=texture2D(textureSampler,coords+offset2).r;\nvec3 p1=vec3(offset1,depth1-depth);\nvec3 p2=vec3(offset2,depth2-depth);\nvec3 normal=cross(p1,p2);\nnormal.z=-normal.z;\nreturn normalize(normal);\n}\nvoid main()\n{\nvec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);\nfloat depth=texture2D(textureSampler,vUV).r;\nvec3 position=vec3(vUV,depth);\nvec3 normal=normalFromDepth(depth,vUV);\nfloat radiusDepth=radius/depth;\nfloat occlusion=0.0;\nvec3 ray;\nvec3 hemiRay;\nfloat occlusionDepth;\nfloat difference;\nfor (int i=0; i<SAMPLES; i++)\n{\nray=radiusDepth*reflect(sampleSphere[i],random);\nhemiRay=position+sign(dot(ray,normal))*ray;\nocclusionDepth=texture2D(textureSampler,clamp(hemiRay.xy,vec2(0.001,0.001),vec2(0.999,0.999))).r;\ndifference=depth-occlusionDepth;\nocclusion+=step(fallOff,difference)*(1.0-smoothstep(fallOff,area,difference));\n}\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor.r=result;\ngl_FragColor.g=result;\ngl_FragColor.b=result;\ngl_FragColor.a=1.0;\n}\n#endif\n","ssao2PixelShader":"\nprecision highp float;\nuniform sampler2D textureSampler;\nuniform float near;\nuniform float far;\nuniform float radius;\nvarying vec2 vUV;\nfloat perspectiveDepthToViewZ( const in float invClipZ,const in float near,const in float far ) {\nreturn ( near*far )/( ( far-near )*invClipZ-far );\n}\nfloat viewZToPerspectiveDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( near*far/viewZ+far)/( far-near );\n}\nfloat viewZToOrthographicDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( viewZ+near )/( near-far );\n}\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform sampler2D normalSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float base;\nuniform float xViewport;\nuniform float yViewport;\nuniform float maxZ;\nuniform float minZAspect;\nuniform vec2 texelSize;\nuniform mat4 projection;\nvoid main()\n{\nvec3 random=texture2D(randomSampler,vUV*randTextureTiles).rgb;\nfloat depth=texture2D(textureSampler,vUV).r;\nfloat depthSign=depth/abs(depth);\ndepth=depth*depthSign;\nvec3 normal=texture2D(normalSampler,vUV).rgb; \nfloat occlusion=0.0;\nfloat correctedRadius=min(radius,minZAspect*depth/near);\nvec3 vViewRay=vec3((vUV.x*2.0-1.0)*xViewport,(vUV.y*2.0-1.0)*yViewport,depthSign);\nvec3 origin=vViewRay*depth;\nvec3 rvec=random*2.0-1.0;\nrvec.z=0.0;\nvec3 tangent=normalize(rvec-normal*dot(rvec,normal));\nvec3 bitangent=cross(normal,tangent);\nmat3 tbn=mat3(tangent,bitangent,normal);\nfloat difference;\nif (depth>maxZ) {\ngl_FragColor=vec4(1.0,1.0,1.0,1.0);\nreturn;\n}\nfor (int i=0; i<SAMPLES; ++i) {\n\nvec3 samplePosition=tbn*sampleSphere[i];\nsamplePosition=samplePosition*correctedRadius+origin;\n\nvec4 offset=vec4(samplePosition,1.0);\noffset=projection*offset;\noffset.xyz/=offset.w;\noffset.xy=offset.xy*0.5+0.5;\nif (offset.x<0.0 || offset.y<0.0 || offset.x>1.0 || offset.y>1.0) {\ncontinue;\n}\n\nfloat sampleDepth=abs(texture2D(textureSampler,offset.xy).r);\n\nfloat rangeCheck=abs(depth-sampleDepth)<correctedRadius ? 1.0 : 0.0;\ndifference=depthSign*samplePosition.z-sampleDepth;\n\nocclusion+=(difference>=1e-5 ? 1.0 : 0.0)*rangeCheck;\n}\n\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor=vec4(vec3(result),1.0);\n}\n#endif\n#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvec4 blur9(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.3846153846)*direction;\nvec2 off2=vec2(3.2307692308)*direction;\ncolor+=texture2D(image,uv)*0.2270270270;\ncolor+=texture2D(image,uv+(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv-(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv+(off2/resolution))*0.0702702703;\ncolor+=texture2D(image,uv-(off2/resolution))*0.0702702703;\nreturn color;\n}\nvec4 blur13(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\ncolor+=texture2D(image,uv)*0.1964825501511404;\ncolor+=texture2D(image,uv+(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv-(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv+(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv-(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv+(off3/resolution))*0.010381362401148057;\ncolor+=texture2D(image,uv-(off3/resolution))*0.010381362401148057;\nreturn color;\n}\nvec4 blur13Bilateral(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\nfloat compareDepth=abs(texture2D(depthSampler,uv).r);\nfloat sampleDepth;\nfloat weight;\nfloat weightSum=30.0;\ncolor+=texture2D(image,uv)*30.0;\nsampleDepth=abs(texture2D(depthSampler,uv+(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off3/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off3/resolution))*weight;\nreturn color/weightSum;\n}\nvoid main()\n{\n#if EXPENSIVE\nfloat compareDepth=abs(texture2D(depthSampler,vUV).r);\nfloat texelsize=1.0/outSize;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i<SAMPLES; ++i)\n{\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\nvec2 sampleOffset=vec2(texelsize*samplerOffsets[i],0.0);\n#else\nvec2 direction=vec2(0.0,1.0);\nvec2 sampleOffset=vec2(0.0,texelsize*samplerOffsets[i]);\n#endif\nvec2 samplePos=vUV+sampleOffset;\nfloat sampleDepth=abs(texture2D(depthSampler,samplePos).r);\nfloat weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30000.0);\nresult+=texture2D(textureSampler,samplePos).r*weight;\nweightSum+=weight;\n}\nresult/=weightSum;\ngl_FragColor.rgb=vec3(result);\ngl_FragColor.a=1.0;\n#else\nvec4 color;\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#else\nvec2 direction=vec2(0.0,1.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#endif\ngl_FragColor.rgb=vec3(color.r);\ngl_FragColor.a=1.0;\n#endif\n}\n#endif\n","ssaoCombinePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D originalColor;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,vUV);\nvec4 sceneColor=texture2D(originalColor,vUV);\ngl_FragColor=sceneColor*ssaoColor;\n}\n","chromaticAberrationPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float chromatic_aberration;\nuniform float radialIntensity;\nuniform vec2 direction;\nuniform vec2 centerPosition;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-centerPosition.x,vUV.y-centerPosition.y);\nvec2 directionOfEffect=direction;\nif(directionOfEffect.x == 0. && directionOfEffect.y == 0.){\ndirectionOfEffect=normalize(centered_screen_pos);\n}\nfloat radius2=centered_screen_pos.x*centered_screen_pos.x\n+centered_screen_pos.y*centered_screen_pos.y;\nfloat radius=sqrt(radius2);\nvec4 original=texture2D(textureSampler,vUV);\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.x/screen_width;\nfloat ref_shiftY=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.y/screen_height;\n\nvec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);\nvec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);\nvec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);\noriginal.r=texture2D(textureSampler,ref_coords_r).r;\noriginal.g=texture2D(textureSampler,ref_coords_g).g;\noriginal.b=texture2D(textureSampler,ref_coords_b).b;\ngl_FragColor=original;\n}","lensHighlightsPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float gain;\nuniform float threshold;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvec4 highlightColor(vec4 color) {\nvec4 highlight=color;\nfloat luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));\nfloat lum_threshold;\nif (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);\nhighlight*=luminance*gain;\nhighlight.a=1.0;\nreturn highlight;\n}\nvoid main(void)\n{\nvec4 original=texture2D(textureSampler,vUV);\n\nif (gain == -1.0) {\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nreturn;\n}\nfloat w=2.0/screen_width;\nfloat h=2.0/screen_height;\nfloat weight=1.0;\n\nvec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;\ngl_FragColor=blurred;\n\n}","depthOfFieldPixelShader":"\n\n\n\n\nuniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\nuniform float grain_amount;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform bool dof_enabled;\n\nuniform float screen_distance; \nuniform float aperture;\nuniform float darken;\nuniform float edge_blur;\nuniform bool highlights;\n\nuniform float near;\nuniform float far;\n\nvarying vec2 vUV;\n\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \n\nvec2 centered_screen_pos;\nvec2 distorted_coords;\nfloat radius2;\nfloat radius;\n\nvec2 rand(vec2 co)\n{\nfloat noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));\nfloat noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));\nreturn clamp(vec2(noise1,noise2),0.0,1.0);\n}\n\nvec2 getDistortedCoords(vec2 coords) {\nif (distortion == 0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);\nvec2 dist_coords=vec2(0.5,0.5);\ndist_coords.x=0.5+direction.x*radius2*1.0;\ndist_coords.y=0.5+direction.y*radius2*1.0;\nfloat dist_amount=clamp(distortion*0.23,0.0,1.0);\ndist_coords=mix(coords,dist_coords,dist_amount);\nreturn dist_coords;\n}\n\nfloat sampleScreen(inout vec4 color,const in vec2 offset,const in float weight) {\n\nvec2 coords=distorted_coords;\nfloat angle=rand(coords*100.0).x*TWOPI;\ncoords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));\ncolor+=texture2D(textureSampler,coords)*weight;\nreturn weight;\n}\n\nfloat getBlurLevel(float size) {\nreturn min(3.0,ceil(size/1.0));\n}\n\nvec4 getBlurColor(float size) {\nvec4 col=texture2D(textureSampler,distorted_coords);\nif (size == 0.0) { return col; }\n\n\nfloat blur_level=getBlurLevel(size);\nfloat w=(size/screen_width);\nfloat h=(size/screen_height);\nfloat total_weight=1.0;\nvec2 sample_coords;\ntotal_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);\ntotal_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);\ntotal_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);\ntotal_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);\ntotal_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);\ntotal_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);\ntotal_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);\ntotal_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);\ntotal_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);\nif (blur_level>1.0) {\ntotal_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);\ntotal_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);\ntotal_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);\ntotal_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);\ntotal_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);\ntotal_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);\ntotal_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);\ntotal_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);\ntotal_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);\n}\nif (blur_level>2.0) {\ntotal_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);\ntotal_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);\ntotal_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);\ntotal_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);\ntotal_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);\ntotal_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);\ntotal_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);\ntotal_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);\ntotal_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);\n}\ncol/=total_weight; \n\nif (darken>0.0) {\ncol.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);\n}\n\n\n\n\nreturn col;\n}\nvoid main(void)\n{\n\ncentered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nradius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;\nradius=sqrt(radius2);\ndistorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \n\n\nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));\n\nif (dof_enabled == false || coc<0.07) { coc=0.0; }\n\nfloat edge_blur_amount=0.0;\nif (edge_blur>0.0) {\nedge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;\n}\n\nfloat blur_amount=max(edge_blur_amount,coc);\n\nif (blur_amount == 0.0) {\ngl_FragColor=texture2D(textureSampler,distorted_coords);\n}\nelse {\n\ngl_FragColor=getBlurColor(blur_amount*1.7);\n\nif (highlights) {\ngl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;\n}\nif (blur_noise) {\n\nvec2 noise=rand(distorted_coords)*0.01*blur_amount;\nvec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);\ngl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;\n}\n}\n\nif (grain_amount>0.0) {\nvec4 grain_color=texture2D(grainSampler,texels_coords*0.003);\ngl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;\n}\n}\n","standardPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(PASS_POST_PROCESS)\nvoid main(void)\n{\nvec4 color=texture2D(textureSampler,vUV);\ngl_FragColor=color;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nuniform sampler2D lensSampler;\nuniform float exposure;\nvoid main(void)\n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\ncolour*=exposure;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\ncolour+=colour*texture2D(lensSampler,vUV).rgb;\nvec4 finalColor=vec4(colour.rgb,1.0)+texture2D(otherSampler,vUV);\ngl_FragColor=finalColor;\n}\n#endif\n#if defined(VLS)\n#define PI 3.1415926535897932384626433832795\nuniform mat4 shadowViewProjection;\nuniform mat4 lightWorld;\nuniform vec3 cameraPosition;\nuniform vec3 sunDirection;\nuniform vec3 sunColor;\nuniform vec2 depthValues;\nuniform float scatteringCoefficient;\nuniform float scatteringPower;\nuniform sampler2D shadowMapSampler;\nuniform sampler2D positionSampler;\nfloat computeScattering(float lightDotView)\n{\nfloat result=1.0-scatteringCoefficient*scatteringCoefficient;\nresult/=(4.0*PI*pow(1.0+scatteringCoefficient*scatteringCoefficient-(2.0*scatteringCoefficient)*lightDotView,1.5));\nreturn result;\n}\nvoid main(void)\n{\n\nvec3 worldPos=texture2D(positionSampler,vUV).rgb;\nvec3 startPosition=cameraPosition;\nvec3 rayVector=worldPos-startPosition;\nfloat rayLength=length(rayVector);\nvec3 rayDirection=rayVector/rayLength;\nfloat stepLength=rayLength/NB_STEPS;\nvec3 stepL=rayDirection*stepLength;\nvec3 currentPosition=startPosition;\nvec3 accumFog=vec3(0.0);\nfor (int i=0; i<int(NB_STEPS); i++)\n{\nvec4 worldInShadowCameraSpace=shadowViewProjection*vec4(currentPosition,1.0);\nfloat depthMetric=(worldInShadowCameraSpace.z+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depthMetric,0.0,1.0);\nworldInShadowCameraSpace.xyz/=worldInShadowCameraSpace.w;\nworldInShadowCameraSpace.xyz=0.5*worldInShadowCameraSpace.xyz+vec3(0.5);\nfloat shadowMapValue=texture2D(shadowMapSampler,worldInShadowCameraSpace.xy).r;\nif (shadowMapValue>shadowPixelDepth)\naccumFog+=sunColor*computeScattering(dot(rayDirection,sunDirection));\ncurrentPosition+=stepL;\n}\naccumFog/=NB_STEPS;\nvec3 color=accumFog*scatteringPower;\ngl_FragColor=vec4(color*exp(color) ,1.0);\n}\n#endif\n#if defined(VLSMERGE)\nuniform sampler2D originalSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(originalSampler,vUV)+texture2D(textureSampler,vUV);\n}\n#endif\n#if defined(LUMINANCE)\nuniform vec2 lumOffsets[4];\nvoid main()\n{\nfloat average=0.0;\nvec4 color=vec4(0.0);\nfloat maximum=-1e20;\nvec3 weight=vec3(0.299,0.587,0.114);\nfor (int i=0; i<4; i++)\n{\ncolor=texture2D(textureSampler,vUV+ lumOffsets[i]);\n\nfloat GreyValue=dot(color.rgb,vec3(0.33,0.33,0.33));\n\n#ifdef WEIGHTED_AVERAGE\nfloat GreyValue=dot(color.rgb,weight);\n#endif\n#ifdef BRIGHTNESS\nfloat GreyValue=max(color.r,max(color.g,color.b));\n#endif\n#ifdef HSL_COMPONENT\nfloat GreyValue=0.5*(max(color.r,max(color.g,color.b))+min(color.r,min(color.g,color.b)));\n#endif\n#ifdef MAGNITUDE\nfloat GreyValue=length(color.rgb);\n#endif\nmaximum=max(maximum,GreyValue);\naverage+=(0.25*log(1e-5+GreyValue));\n}\naverage=exp(average);\ngl_FragColor=vec4(average,maximum,0.0,1.0);\n}\n#endif\n#if defined(LUMINANCE_DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLER\nvec4 pack(float value) {\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(value*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvoid main()\n{\nvec4 color=vec4(0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++)\n{\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifdef FINAL_DOWN_SAMPLER\ngl_FragColor=pack(average);\n#else\ngl_FragColor=vec4(average,average,0.0,1.0);\n#endif\n}\n#endif\n#if defined(HDR)\nuniform sampler2D textureAdderSampler;\nuniform float averageLuminance;\nvoid main()\n{\nvec4 color=texture2D(textureAdderSampler,vUV);\nvec4 adjustedColor=color/averageLuminance;\ncolor=adjustedColor;\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(LENS_FLARE)\n#define GHOSTS 3\nuniform sampler2D lensColorSampler;\nuniform float strength;\nuniform float ghostDispersal;\nuniform float haloWidth;\nuniform vec2 resolution;\nuniform float distortionStrength;\nfloat hash(vec2 p)\n{\nfloat h=dot(p,vec2(127.1,311.7));\nreturn -1.0+2.0*fract(sin(h)*43758.5453123);\n}\nfloat noise(in vec2 p)\n{\nvec2 i=floor(p);\nvec2 f=fract(p);\nvec2 u=f*f*(3.0-2.0*f);\nreturn mix(mix(hash(i+vec2(0.0,0.0)),\nhash(i+vec2(1.0,0.0)),u.x),\nmix(hash(i+vec2(0.0,1.0)),\nhash(i+vec2(1.0,1.0)),u.x),u.y);\n}\nfloat fbm(vec2 p)\n{\nfloat f=0.0;\nf+=0.5000*noise(p); p*=2.02;\nf+=0.2500*noise(p); p*=2.03;\nf+=0.1250*noise(p); p*=2.01;\nf+=0.0625*noise(p); p*=2.04;\nf/=0.9375;\nreturn f;\n}\nvec3 pattern(vec2 uv)\n{\nvec2 p=-1.0+2.0*uv;\nfloat p2=dot(p,p);\nfloat f=fbm(vec2(15.0*p2))/2.0;\nfloat r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));\nfloat g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));\nfloat b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));\nreturn (1.0-f)*vec3(r,g,b);\n}\nfloat luminance(vec3 color)\n{\nreturn dot(color.rgb,vec3(0.2126,0.7152,0.0722));\n}\nvec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion)\n{\nreturn vec4(\ntexture2D(tex,texcoord+direction*distortion.r).r,\ntexture2D(tex,texcoord+direction*distortion.g).g,\ntexture2D(tex,texcoord+direction*distortion.b).b,\n1.0\n);\n}\nvoid main(void)\n{\nvec2 uv=-vUV+vec2(1.0);\nvec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;\nvec2 texelSize=1.0/resolution;\nvec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);\nvec4 result=vec4(0.0);\nfloat ghostIndice=1.0;\nfor (int i=0; i<GHOSTS; ++i)\n{\nvec2 offset=fract(uv+ghostDir*ghostIndice);\nfloat weight=length(vec2(0.5)-offset)/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,offset,normalize(ghostDir),distortion)*weight*strength;\nghostIndice+=1.0;\n}\nvec2 haloVec=normalize(ghostDir)*haloWidth;\nfloat weight=length(vec2(0.5)-fract(uv+haloVec))/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,fract(uv+haloVec),normalize(ghostDir),distortion)*weight*strength;\nresult*=texture2D(lensColorSampler,vec2(length(vec2(0.5)-uv)/length(vec2(0.5))));\ngl_FragColor=result;\n}\n#endif\n#if defined(LENS_FLARE_COMPOSE)\nuniform sampler2D otherSampler;\nuniform sampler2D lensDirtSampler;\nuniform sampler2D lensStarSampler;\nuniform mat4 lensStarMatrix;\nvoid main(void)\n{\nvec2 lensFlareCoords=(lensStarMatrix*vec4(vUV,1.0,1.0)).xy;\nvec4 lensMod=texture2D(lensDirtSampler,vUV);\nlensMod+=texture2D(lensStarSampler,vUV);\nvec4 result=texture2D(textureSampler,vUV)*lensMod;\ngl_FragColor=texture2D(otherSampler,vUV)+result;\n}\n#endif\n#if defined(DEPTH_OF_FIELD)\nuniform sampler2D otherSampler;\nuniform sampler2D depthSampler;\nuniform float distance;\nvoid main(void)\n{\nvec4 sharp=texture2D(otherSampler,vUV);\nvec4 blur=texture2D(textureSampler,vUV);\nfloat dist=clamp(texture2D(depthSampler,vUV).r*distance,0.0,1.0);\nfloat factor=0.0;\nif (dist<0.05)\nfactor=1.0;\nelse if (dist<0.1)\nfactor=20.0*(0.1-dist);\nelse if (dist<0.5)\nfactor=0.0;\nelse\nfactor=2.0*(dist-0.5);\nfactor=clamp(factor,0.0,0.90);\ngl_FragColor=mix(sharp,blur,factor);\n}\n#endif\n#if defined(MOTION_BLUR)\nuniform mat4 inverseViewProjection;\nuniform mat4 prevViewProjection;\nuniform vec2 screenSize;\nuniform float motionScale;\nuniform float motionStrength;\nuniform sampler2D depthSampler;\nvoid main(void)\n{\nvec2 texelSize=1.0/screenSize;\nfloat depth=texture2D(depthSampler,vUV).r;\nvec4 cpos=vec4(vUV*2.0-1.0,depth,1.0);\ncpos=cpos*inverseViewProjection;\nvec4 ppos=cpos*prevViewProjection;\nppos.xyz/=ppos.w;\nppos.xy=ppos.xy*0.5+0.5;\nvec2 velocity=(ppos.xy-vUV)*motionScale*motionStrength;\nfloat speed=length(velocity/texelSize);\nint nSamples=int(clamp(speed,1.0,MAX_MOTION_SAMPLES));\nvec4 result=texture2D(textureSampler,vUV);\nfor (int i=1; i<int(MAX_MOTION_SAMPLES); ++i) {\nif (i>=nSamples)\nbreak;\nvec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);\nresult+=texture2D(textureSampler,offset1);\n}\ngl_FragColor=result/float(nSamples);\n}\n#endif\n","fxaaVertexShader":"\nattribute vec2 position;\nuniform vec2 texelSize;\n\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd);\nsampleCoordS=vUV+vec2( 0.0,1.0)*texelSize;\nsampleCoordE=vUV+vec2( 1.0,0.0)*texelSize;\nsampleCoordN=vUV+vec2( 0.0,-1.0)*texelSize;\nsampleCoordW=vUV+vec2(-1.0,0.0)*texelSize;\nsampleCoordNW=vUV+vec2(-1.0,-1.0)*texelSize;\nsampleCoordSE=vUV+vec2( 1.0,1.0)*texelSize;\nsampleCoordNE=vUV+vec2( 1.0,-1.0)*texelSize;\nsampleCoordSW=vUV+vec2(-1.0,1.0)*texelSize;\ngl_Position=vec4(position,0.0,1.0);\n}","fxaaPixelShader":"uniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst float fxaaQualitySubpix=1.0;\nconst float fxaaQualityEdgeThreshold=0.166;\nconst float fxaaQualityEdgeThresholdMin=0.0833;\nconst vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722);\n#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients)\nvoid main(){\nvec2 posM;\nposM.x=vUV.x;\nposM.y=vUV.y;\nvec4 rgbyM=texture2D(textureSampler,vUV,0.0);\nfloat lumaM=FxaaLuma(rgbyM);\nfloat lumaS=FxaaLuma(texture2D(textureSampler,sampleCoordS,0.0));\nfloat lumaE=FxaaLuma(texture2D(textureSampler,sampleCoordE,0.0));\nfloat lumaN=FxaaLuma(texture2D(textureSampler,sampleCoordN,0.0));\nfloat lumaW=FxaaLuma(texture2D(textureSampler,sampleCoordW,0.0));\nfloat maxSM=max(lumaS,lumaM);\nfloat minSM=min(lumaS,lumaM);\nfloat maxESM=max(lumaE,maxSM);\nfloat minESM=min(lumaE,minSM);\nfloat maxWN=max(lumaN,lumaW);\nfloat minWN=min(lumaN,lumaW);\nfloat rangeMax=max(maxWN,maxESM);\nfloat rangeMin=min(minWN,minESM);\nfloat rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;\nfloat range=rangeMax-rangeMin;\nfloat rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled);\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\nreturn;\n}\nfloat lumaNW=FxaaLuma(texture2D(textureSampler,sampleCoordNW,0.0));\nfloat lumaSE=FxaaLuma(texture2D(textureSampler,sampleCoordSE,0.0));\nfloat lumaNE=FxaaLuma(texture2D(textureSampler,sampleCoordNE,0.0));\nfloat lumaSW=FxaaLuma(texture2D(textureSampler,sampleCoordSW,0.0));\nfloat lumaNS=lumaN+lumaS;\nfloat lumaWE=lumaW+lumaE;\nfloat subpixRcpRange=1.0/range;\nfloat subpixNSWE=lumaNS+lumaWE;\nfloat edgeHorz1=(-2.0*lumaM)+lumaNS;\nfloat edgeVert1=(-2.0*lumaM)+lumaWE;\nfloat lumaNESE=lumaNE+lumaSE;\nfloat lumaNWNE=lumaNW+lumaNE;\nfloat edgeHorz2=(-2.0*lumaE)+lumaNESE;\nfloat edgeVert2=(-2.0*lumaN)+lumaNWNE;\nfloat lumaNWSW=lumaNW+lumaSW;\nfloat lumaSWSE=lumaSW+lumaSE;\nfloat edgeHorz4=(abs(edgeHorz1)*2.0)+abs(edgeHorz2);\nfloat edgeVert4=(abs(edgeVert1)*2.0)+abs(edgeVert2);\nfloat edgeHorz3=(-2.0*lumaW)+lumaNWSW;\nfloat edgeVert3=(-2.0*lumaS)+lumaSWSE;\nfloat edgeHorz=abs(edgeHorz3)+edgeHorz4;\nfloat edgeVert=abs(edgeVert3)+edgeVert4;\nfloat subpixNWSWNESE=lumaNWSW+lumaNESE;\nfloat lengthSign=texelSize.x;\nbool horzSpan=edgeHorz>=edgeVert;\nfloat subpixA=subpixNSWE*2.0+subpixNWSWNESE;\nif (!horzSpan)\n{\nlumaN=lumaW;\n}\nif (!horzSpan) \n{\nlumaS=lumaE;\n}\nif (horzSpan) \n{\nlengthSign=texelSize.y;\n}\nfloat subpixB=(subpixA*(1.0/12.0))-lumaM;\nfloat gradientN=lumaN-lumaM;\nfloat gradientS=lumaS-lumaM;\nfloat lumaNN=lumaN+lumaM;\nfloat lumaSS=lumaS+lumaM;\nbool pairN=abs(gradientN)>=abs(gradientS);\nfloat gradient=max(abs(gradientN),abs(gradientS));\nif (pairN)\n{\nlengthSign=-lengthSign;\n}\nfloat subpixC=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);\nvec2 posB;\nposB.x=posM.x;\nposB.y=posM.y;\nvec2 offNP;\noffNP.x=(!horzSpan) ? 0.0 : texelSize.x;\noffNP.y=(horzSpan) ? 0.0 : texelSize.y;\nif (!horzSpan) \n{\nposB.x+=lengthSign*0.5;\n}\nif (horzSpan)\n{\nposB.y+=lengthSign*0.5;\n}\nvec2 posN;\nposN.x=posB.x-offNP.x*1.5;\nposN.y=posB.y-offNP.y*1.5;\nvec2 posP;\nposP.x=posB.x+offNP.x*1.5;\nposP.y=posB.y+offNP.y*1.5;\nfloat subpixD=((-2.0)*subpixC)+3.0;\nfloat lumaEndN=FxaaLuma(texture2D(textureSampler,posN,0.0));\nfloat subpixE=subpixC*subpixC;\nfloat lumaEndP=FxaaLuma(texture2D(textureSampler,posP,0.0));\nif (!pairN) \n{\nlumaNN=lumaSS;\n}\nfloat gradientScaled=gradient*1.0/4.0;\nfloat lumaMM=lumaM-lumaNN*0.5;\nfloat subpixF=subpixD*subpixE;\nbool lumaMLTZero=lumaMM<0.0;\nlumaEndN-=lumaNN*0.5;\nlumaEndP-=lumaNN*0.5;\nbool doneN=abs(lumaEndN)>=gradientScaled;\nbool doneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) \n{\nposN.x-=offNP.x*3.0;\n}\nif (!doneN) \n{\nposN.y-=offNP.y*3.0;\n}\nbool doneNP=(!doneN) || (!doneP);\nif (!doneP) \n{\nposP.x+=offNP.x*3.0;\n}\nif (!doneP)\n{\nposP.y+=offNP.y*3.0;\n}\nif (doneNP)\n{\nif (!doneN) lumaEndN=FxaaLuma(texture2D(textureSampler,posN.xy,0.0));\nif (!doneP) lumaEndP=FxaaLuma(texture2D(textureSampler,posP.xy,0.0));\nif (!doneN) lumaEndN=lumaEndN-lumaNN*0.5;\nif (!doneP) lumaEndP=lumaEndP-lumaNN*0.5;\ndoneN=abs(lumaEndN)>=gradientScaled;\ndoneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) posN.x-=offNP.x*12.0;\nif (!doneN) posN.y-=offNP.y*12.0;\ndoneNP=(!doneN) || (!doneP);\nif (!doneP) posP.x+=offNP.x*12.0;\nif (!doneP) posP.y+=offNP.y*12.0;\n}\nfloat dstN=posM.x-posN.x;\nfloat dstP=posP.x-posM.x;\nif (!horzSpan)\n{\ndstN=posM.y-posN.y;\n}\nif (!horzSpan) \n{\ndstP=posP.y-posM.y;\n}\nbool goodSpanN=(lumaEndN<0.0) != lumaMLTZero;\nfloat spanLength=(dstP+dstN);\nbool goodSpanP=(lumaEndP<0.0) != lumaMLTZero;\nfloat spanLengthRcp=1.0/spanLength;\nbool directionN=dstN<dstP;\nfloat dst=min(dstN,dstP);\nbool goodSpan=directionN ? goodSpanN : goodSpanP;\nfloat subpixG=subpixF*subpixF;\nfloat pixelOffset=(dst*(-spanLengthRcp))+0.5;\nfloat subpixH=subpixG*fxaaQualitySubpix;\nfloat pixelOffsetGood=goodSpan ? pixelOffset : 0.0;\nfloat pixelOffsetSubpix=max(pixelOffsetGood,subpixH);\nif (!horzSpan)\n{\nposM.x+=pixelOffsetSubpix*lengthSign;\n}\nif (horzSpan)\n{\nposM.y+=pixelOffsetSubpix*lengthSign;\n}\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n}","sharpenPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform vec2 sharpnessAmounts;\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 color=texture2D(textureSampler,vUV);\nvec4 edgeDetection=texture2D(textureSampler,vUV+onePixel*vec2(0,-1)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1)) -\ncolor*4.0;\ngl_FragColor=max(vec4(color.rgb*sharpnessAmounts.y,color.a)-(sharpnessAmounts.x*vec4(edgeDetection.rgb,0)),0.);\n}","kernelBlurVertexShader":"\nattribute vec2 position;\n\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nsampleCenter=(position*madd+madd);\n#include<kernelBlurVertex>[0..varyingCount]\ngl_Position=vec4(position,0.0,1.0);\n}","kernelBlurPixelShader":"\nuniform sampler2D textureSampler;\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#ifdef DOF\nuniform sampler2D circleOfConfusionSampler;\nuniform vec2 cameraMinMaxZ;\nfloat sampleDistance(const in vec2 offset) {\nfloat depth=texture2D(circleOfConfusionSampler,offset).g; \nreturn cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth; \n}\n#endif\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\n#ifdef PACKEDFLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nvoid main(void)\n{\n#ifdef DOF\nfloat sumOfWeights=0.0; \nfloat sampleDepth=0.0;\nfloat factor=0.0;\nfloat centerSampleDepth=sampleDistance(sampleCenter);\n#endif\nfloat computedWeight=0.0;\n#ifdef PACKEDFLOAT \nfloat blend=0.;\n#else\nvec4 blend=vec4(0.);\n#endif\n#include<kernelBlurFragment>[0..varyingCount]\n#include<kernelBlurFragment2>[0..depCount]\n#ifdef PACKEDFLOAT\ngl_FragColor=pack(blend);\n#else\ngl_FragColor=blend;\n#endif\n#ifdef DOF\n\nif(sumOfWeights == 0.0){\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor/=sumOfWeights;\n#endif\n}","depthOfFieldMergePixelShader":"\nuniform sampler2D textureSampler;\nuniform sampler2D originalSampler;\nuniform sampler2D circleOfConfusionSampler;\n#if BLUR_LEVEL>0\nuniform sampler2D blurStep1;\n#endif\n#if BLUR_LEVEL>1\nuniform sampler2D blurStep2;\n#endif\n\nvarying vec2 vUV;\nvoid main(void)\n{\nfloat coc=texture2D(circleOfConfusionSampler,vUV).r;\nvec4 original=texture2D(originalSampler,vUV);\n#if BLUR_LEVEL == 0\nvec4 blurred1=texture2D(textureSampler,vUV);\ngl_FragColor=mix(original,blurred1,coc);\n#endif\n#if BLUR_LEVEL == 1\nvec4 blurred1=texture2D(blurStep1,vUV);\nvec4 blurred2=texture2D(textureSampler,vUV); \nif(coc<0.5){\ngl_FragColor=mix(original,blurred1,coc/0.5);\n}else{\ngl_FragColor=mix(blurred1,blurred2,(coc-0.5)/0.5);\n}\n#endif\n#if BLUR_LEVEL == 2\nvec4 blurred1=texture2D(blurStep1,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\nvec4 blurred3=texture2D(textureSampler,vUV);\nif(coc<0.33){\ngl_FragColor=mix(original,blurred1,coc/0.33);\n}else if(coc<0.66){\ngl_FragColor=mix(blurred1,blurred2,(coc-0.33)/0.33);\n}else{\ngl_FragColor=mix(blurred2,blurred3,(coc-0.66)/0.34);\n}\n#endif\n}\n","circleOfConfusionPixelShader":"\nuniform sampler2D depthSampler;\n\nvarying vec2 vUV;\n\nuniform vec2 cameraMinMaxZ;\n\nuniform float focusDistance;\nuniform float cocPrecalculation;\nfloat sampleDistance(const in vec2 offset) {\nfloat depth=texture2D(depthSampler,offset).r; \nreturn (cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth)*1000.0; \n}\nvoid main(void)\n{\nfloat pixelDistance=sampleDistance(vUV);\nfloat coc=abs(cocPrecalculation* ((focusDistance-pixelDistance)/pixelDistance));\ncoc=clamp(coc,0.0,1.0);\ngl_FragColor=vec4(coc,texture2D(depthSampler,vUV).r,coc,1.0);\n}\n","geometryVertexShader":"precision highp float;\nprecision highp int;\n#include<bonesDeclaration>\n#include<instancesDeclaration>\nattribute vec3 position;\nattribute vec3 normal;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nvarying vec2 uv;\n#endif\n#ifdef UV2\nvarying vec2 uv2;\n#endif\n#endif\n\nuniform mat4 viewProjection;\nuniform mat4 view;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 pos=vec4(finalWorld*vec4(position,1.0));\nvNormalV=normalize(vec3((view*finalWorld)*vec4(normal,0.0)));\nvViewPos=view*pos;\n#ifdef POSITION\nvPosition=pos.xyz/pos.w;\n#endif\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","geometryPixelShader":"#extension GL_EXT_draw_buffers : require\nprecision highp float;\nprecision highp int;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef POSITION\n#include<mrtFragmentDeclaration>[3]\n#else\n#include<mrtFragmentDeclaration>[2]\n#endif\nvoid main() {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragData[0]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0);\n\ngl_FragData[1]=vec4(normalize(vNormalV),1.0);\n\n#ifdef POSITION\ngl_FragData[2]=vec4(vPosition,1.0);\n#endif\n}","refractionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\nvoid main() {\nfloat ref=1.0-texture2D(refractionSampler,vUV).r;\nvec2 uv=vUV-vec2(0.5);\nvec2 offset=uv*depth*ref;\nvec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;\ngl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);\n}","blackAndWhitePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float degree;\nvoid main(void) \n{\nvec3 color=texture2D(textureSampler,vUV).rgb;\nfloat luminance=dot(color,vec3(0.3,0.59,0.11)); \nvec3 blackAndWhite=vec3(luminance,luminance,luminance);\ngl_FragColor=vec4(color-((color-blackAndWhite)*degree),1.0);\n}","convolutionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform float kernel[9];\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 colorSum =\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];\nfloat kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];\nif (kernelWeight<=0.0) {\nkernelWeight=1.0;\n}\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);\n}","filterPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform mat4 kernelMatrix;\nvoid main(void)\n{\nvec3 baseColor=texture2D(textureSampler,vUV).rgb;\nvec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;\ngl_FragColor=vec4(updatedColor,1.0);\n}","volumetricLightScatteringPixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\nvarying vec2 vUV;\nvoid main(void) {\nvec2 tc=vUV;\nvec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);\ndeltaTexCoord*=1.0/float(NUM_SAMPLES)*density;\nfloat illuminationDecay=1.0;\nvec4 color=texture2D(lightScatteringSampler,tc)*0.4;\nfor(int i=0; i<NUM_SAMPLES; i++) {\ntc-=deltaTexCoord;\nvec4 dataSample=texture2D(lightScatteringSampler,tc)*0.4;\ndataSample*=illuminationDecay*weight;\ncolor+=dataSample;\nilluminationDecay*=decay;\n}\nvec4 realColor=texture2D(textureSampler,vUV);\ngl_FragColor=((vec4((vec3(color.r,color.g,color.b)*exposure),1))+(realColor*(1.5-0.4)));\n}\n","volumetricLightScatteringPassPixelShader":"#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\n#endif\n#if defined(ALPHATEST)\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void)\n{\n#if defined(ALPHATEST)\nvec4 diffuseColor=texture2D(diffuseSampler,vUV);\nif (diffuseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\n","colorCorrectionPixelShader":"\nuniform sampler2D textureSampler; \nuniform sampler2D colorTable; \n\nvarying vec2 vUV;\n\nconst float SLICE_COUNT=16.0; \n\nvec4 sampleAs3DTexture(sampler2D textureSampler,vec3 uv,float width) {\nfloat sliceSize=1.0/width; \nfloat slicePixelSize=sliceSize/width; \nfloat sliceInnerSize=slicePixelSize*(width-1.0); \nfloat zSlice0=min(floor(uv.z*width),width-1.0);\nfloat zSlice1=min(zSlice0+1.0,width-1.0);\nfloat xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;\nfloat s0=xOffset+(zSlice0*sliceSize);\nfloat s1=xOffset+(zSlice1*sliceSize);\nvec4 slice0Color=texture2D(textureSampler,vec2(s0,uv.y));\nvec4 slice1Color=texture2D(textureSampler,vec2(s1,uv.y));\nfloat zOffset=mod(uv.z*width,1.0);\nvec4 result=mix(slice0Color,slice1Color,zOffset);\nreturn result;\n}\nvoid main(void)\n{\nvec4 screen_color=texture2D(textureSampler,vUV);\ngl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);\n}","tonemapPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float _ExposureAdjustment;\n#if defined(HABLE_TONEMAPPING)\nconst float A=0.15;\nconst float B=0.50;\nconst float C=0.10;\nconst float D=0.20;\nconst float E=0.02;\nconst float F=0.30;\nconst float W=11.2;\n#endif\nfloat Luminance(vec3 c)\n{\nreturn dot(c,vec3(0.22,0.707,0.071));\n}\nvoid main(void) \n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\nfloat lum=Luminance(colour.rgb); \nfloat lumTm=lum*_ExposureAdjustment;\nfloat scale=lumTm/(1.0+lumTm); \ncolour*=scale/lum;\n#elif defined(HABLE_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nconst float ExposureBias=2.0;\nvec3 x=ExposureBias*colour;\nvec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;\nx=vec3(W,W,W);\nvec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);\ncolour=curr*whiteScale;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour=vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);\n#endif\ngl_FragColor=vec4(colour.rgb,1.0);\n}","displayPassPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(passSampler,vUV);\n}","highlightsPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nconst vec3 RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\nvoid main(void) \n{\nvec4 tex=texture2D(textureSampler,vUV);\nvec3 c=tex.rgb;\nfloat luma=dot(c.rgb,RGBLuminanceCoefficients);\n\n\ngl_FragColor=vec4(pow(c,vec3(25.0-luma*15.0)),tex.a); \n}","imageProcessingPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\nvoid main(void)\n{\nvec4 result=texture2D(textureSampler,vUV);\n#ifdef IMAGEPROCESSING\n#ifndef FROMLINEARSPACE\n\nresult.rgb=toLinearSpace(result.rgb);\n#endif\n#ifdef GRAIN\nvec2 seed=vUV*(grainAnimatedSeed);\nfloat grain=dither(seed,grainVarianceAmount);\n\nfloat lum=getLuminance(result.rgb);\nfloat grainAmount=(cos(-PI+(lum*PI*2.))+1.)/2.;\nresult.rgb+=grain*grainAmount;\nresult.rgb=max(result.rgb,0.0);\n#endif\nresult=applyImageProcessing(result);\n#else\n\n#ifdef FROMLINEARSPACE\nresult=applyImageProcessing(result);\n#endif\n#endif\ngl_FragColor=result;\n}","lensFlareVertexShader":"\nattribute vec2 position;\n\nuniform mat4 viewportMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=position*madd+madd;\ngl_Position=viewportMatrix*vec4(position,0.0,1.0);\n}","lensFlarePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\ngl_FragColor=baseColor*color;\n}","anaglyphPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\nvoid main(void)\n{\nvec4 leftFrag=texture2D(leftSampler,vUV);\nleftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);\nvec4 rightFrag=texture2D(textureSampler,vUV);\nrightFrag=vec4(rightFrag.r,1.0,1.0,1.0);\ngl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);\n}","stereoscopicInterlacePixelShader":"const vec3 TWO=vec3(2.0,2.0,2.0);\nvarying vec2 vUV;\nuniform sampler2D camASampler;\nuniform sampler2D textureSampler;\nuniform vec2 stepSize;\nvoid main(void)\n{\nbool useCamB;\nvec2 texCoord1;\nvec2 texCoord2;\nvec3 frag1;\nvec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;\ntexCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);\ntexCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;\ntexCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);\ntexCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n\nif (useCamB){\nfrag1=texture2D(textureSampler,texCoord1).rgb;\nfrag2=texture2D(textureSampler,texCoord2).rgb;\n}else{\nfrag1=texture2D(camASampler ,texCoord1).rgb;\nfrag2=texture2D(camASampler ,texCoord2).rgb;\n}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);\n}","vrDistortionCorrectionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\nvec2 HmdWarp(vec2 in01) {\nvec2 theta=(in01-LensCenter)*ScaleIn; \nfloat rSq=theta.x*theta.x+theta.y*theta.y;\nvec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);\nreturn LensCenter+Scale*rvector;\n}\nvoid main(void)\n{\nvec2 tc=HmdWarp(vUV);\nif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor=vec4(0.0,0.0,0.0,0.0);\nelse{\ngl_FragColor=texture2D(textureSampler,tc);\n}\n}","glowBlurPostProcessPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\n\nfloat getLuminance(vec3 color)\n{\nreturn dot(color,vec3(0.2126,0.7152,0.0722));\n}\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\n\nvec4 texel=texture2D(textureSampler,start+texelOffset);\nbaseColor.a+=texel.a*weights[i];\n\nfloat luminance=getLuminance(baseColor.rgb);\nfloat luminanceTexel=getLuminance(texel.rgb);\nfloat choice=step(luminanceTexel,luminance);\nbaseColor.rgb=choice*baseColor.rgb+(1.0-choice)*texel.rgb;\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}","glowMapGenerationPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform sampler2D emissiveSampler;\n#endif\nuniform vec4 color;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUVDiffuse).a<0.4)\ndiscard;\n#endif\n#ifdef EMISSIVE\ngl_FragColor=texture2D(emissiveSampler,vUVEmissive)*color;\n#else\ngl_FragColor=color;\n#endif\n}","glowMapGenerationVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform mat4 diffuseMatrix;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform mat4 emissiveMatrix;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(position,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef DIFFUSEUV1\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef DIFFUSEUV2\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef EMISSIVE\n#ifdef EMISSIVEUV1\nvUVEmissive=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef EMISSIVEUV2\nvUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","glowMapMergePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#ifdef EMISSIVE\nuniform sampler2D textureSampler2;\n#endif\n\nuniform float offset;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef EMISSIVE\nbaseColor+=texture2D(textureSampler2,vUV);\nbaseColor*=offset;\n#else\nbaseColor.a=abs(offset-baseColor.a);\n#ifdef STROKE\nfloat alpha=smoothstep(.0,.1,baseColor.a);\nbaseColor.a=alpha;\nbaseColor.rgb=baseColor.rgb*alpha;\n#endif\n#endif\ngl_FragColor=baseColor;\n}","glowMapMergeVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) {\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","lineVertexShader":"\nattribute vec3 position;\nattribute vec4 normal;\n\nuniform mat4 worldViewProjection;\nuniform float width;\nuniform float aspectRatio;\nvoid main(void) {\nvec4 viewPosition=worldViewProjection*vec4(position,1.0);\nvec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);\nvec2 currentScreen=viewPosition.xy/viewPosition.w;\nvec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;\ncurrentScreen.x*=aspectRatio;\nnextScreen.x*=aspectRatio;\nvec2 dir=normalize(nextScreen-currentScreen);\nvec2 normalDir=vec2(-dir.y,dir.x);\nnormalDir*=width/2.0;\nnormalDir.x/=aspectRatio;\nvec4 offset=vec4(normalDir*normal.w,0.0,0.0);\ngl_Position=viewPosition+offset;\n}","linePixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","outlineVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\n#include<bonesDeclaration>\n\nuniform float offset;\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#include<logDepthDeclaration>\nvoid main(void)\n{\nvec3 offsetPosition=position+normal*offset;\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(offsetPosition,1.0);\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#include<logDepthVertex>\n}\n","outlinePixelShader":"#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nuniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#include<logDepthFragment>\ngl_FragColor=color;\n}","layerVertexShader":"\nattribute vec2 position;\n\nuniform vec2 scale;\nuniform vec2 offset;\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvec2 shiftedPosition=position*scale+offset;\nvUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));\ngl_Position=vec4(shiftedPosition,0.0,1.0);\n}","layerPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n}","backgroundVertexShader":"precision highp float;\n#include<__decl__backgroundVertex>\n#include<helperFunctions>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normal);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#ifdef EQUIRECTANGULAR_RELFECTION_FOV\nmat3 screenToWorld=inverseMat3(mat3(finalWorld*viewProjection));\nvec3 segment=mix(vDirectionW,screenToWorld*vec3(0.0,0.0,1.0),abs(fFovMultiplier-1.0));\nif (fFovMultiplier<=1.0) {\nvDirectionW=normalize(segment);\n} else {\nvDirectionW=normalize(vDirectionW+(vDirectionW-segment));\n}\n#endif\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0 \nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n}\n","backgroundPixelShader":"#ifdef TEXTURELODSUPPORT\n#extension GL_EXT_shader_texture_lod : enable\n#endif\nprecision highp float;\n#include<__decl__backgroundFragment>\n#define RECIPROCAL_PI2 0.15915494\n\nuniform vec3 vEyePosition;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2; \n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n\n#ifndef SHADOWONLY\n#define SHADOWONLY;\n#endif\n#include<imageProcessingDeclaration>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<helperFunctions>\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n#include<imageProcessingFunctions>\n#include<clipPlaneFragmentDeclaration>\n\n#include<fogFragmentDeclaration>\n#ifdef REFLECTIONFRESNEL\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n#endif\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(0.0,1.0,0.0);\n#endif\n\nfloat shadow=1.;\nfloat globalShadow=0.;\nfloat shadowLightCount=0.;\n#include<lightFragment>[0..maxSimultaneousLights]\n#ifdef SHADOWINUSE\nglobalShadow/=shadowLightCount;\n#else\nglobalShadow=1.0;\n#endif\n\nvec3 reflectionColor=vec3(1.,1.,1.);\n#ifdef REFLECTION\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#ifdef REFLECTIONBLUR\nfloat reflectionLOD=vReflectionInfos.y;\n#ifdef TEXTURELODSUPPORT\n\nreflectionLOD=reflectionLOD*log2(vReflectionMicrosurfaceInfos.x)*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\nreflectionColor=sampleReflectionLod(reflectionSampler,reflectionCoords,reflectionLOD).rgb;\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD,0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec3 reflectionSpecularMid=sampleReflection(reflectionSampler,reflectionCoords).rgb;\nif(lodReflectionNormalizedDoubled<1.0){\nreflectionColor=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords).rgb,\nreflectionSpecularMid,\nlodReflectionNormalizedDoubled\n);\n} else {\nreflectionColor=mix(\nreflectionSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords).rgb,\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#else\nvec4 reflectionSample=sampleReflection(reflectionSampler,reflectionCoords);\nreflectionColor=reflectionSample.rgb;\n#endif\n#ifdef GAMMAREFLECTION\nreflectionColor=toLinearSpace(reflectionColor.rgb);\n#endif\n#ifdef REFLECTIONBGR\nreflectionColor=reflectionColor.bgr;\n#endif\n\nreflectionColor*=vReflectionInfos.x;\n#endif\n\nvec3 diffuseColor=vec3(1.,1.,1.);\nfloat finalAlpha=alpha;\n#ifdef DIFFUSE\nvec4 diffuseMap=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef GAMMADIFFUSE\ndiffuseMap.rgb=toLinearSpace(diffuseMap.rgb);\n#endif\n\ndiffuseMap.rgb*=vDiffuseInfos.y;\n#ifdef DIFFUSEHASALPHA\nfinalAlpha*=diffuseMap.a;\n#endif\ndiffuseColor=diffuseMap.rgb;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 colorBase=diffuseColor;\n#else\nvec3 colorBase=reflectionColor*diffuseColor;\n#endif\ncolorBase=max(colorBase,0.0);\n\n#ifdef USERGBCOLOR\nvec3 finalColor=colorBase;\n#else\nvec3 finalColor=colorBase.r*vPrimaryColor.rgb*vPrimaryColor.a;\nfinalColor+=colorBase.g*vSecondaryColor.rgb*vSecondaryColor.a;\nfinalColor+=colorBase.b*vTertiaryColor.rgb*vTertiaryColor.a;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 reflectionAmount=vReflectionControl.xxx;\nvec3 reflectionReflectance0=vReflectionControl.yyy;\nvec3 reflectionReflectance90=vReflectionControl.zzz;\nfloat VdotN=dot(normalize(vEyePosition),normalW);\nvec3 planarReflectionFresnel=fresnelSchlickEnvironmentGGX(clamp(VdotN,0.0,1.0),reflectionReflectance0,reflectionReflectance90,1.0);\nreflectionAmount*=planarReflectionFresnel;\n#ifdef REFLECTIONFALLOFF\nfloat reflectionDistanceFalloff=1.0-clamp(length(vPositionW.xyz-vBackgroundCenter)*vReflectionControl.w,0.0,1.0);\nreflectionDistanceFalloff*=reflectionDistanceFalloff;\nreflectionAmount*=reflectionDistanceFalloff;\n#endif\nfinalColor=mix(finalColor,reflectionColor,clamp(reflectionAmount,0.,1.));\n#endif\n#ifdef OPACITYFRESNEL\nfloat viewAngleToFloor=dot(normalW,normalize(vEyePosition-vBackgroundCenter));\n\nconst float startAngle=0.1;\nfloat fadeFactor=clamp(viewAngleToFloor/startAngle,0.0,1.0);\nfinalAlpha*=fadeFactor*fadeFactor;\n#endif\n\n#ifdef SHADOWINUSE\nfinalColor=mix(finalColor*shadowLevel,finalColor,globalShadow);\n#endif\n\nvec4 color=vec4(finalColor,finalAlpha);\n#include<fogFragment>\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\ncolor.rgb=clamp(color.rgb,0.,30.0);\n#else\n\ncolor=applyImageProcessing(color);\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#ifndef GRAIN \n#ifdef NOISE\ncolor.rgb+=dither(vPositionW.xy,0.5);\ncolor=max(color,0.0);\n#endif\n#endif\ngl_FragColor=color;\n}\n"};
  91341. BABYLON.Effect.IncludesShadersStore={"depthPrePass":"#ifdef DEPTHPREPASS\ngl_FragColor=vec4(0.,0.,0.,1.0);\nreturn;\n#endif","bonesDeclaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nattribute vec4 matricesIndicesExtra;\nattribute vec4 matricesWeightsExtra;\n#endif\n#endif","instancesDeclaration":"#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif","pointCloudVertexDeclaration":"#ifdef POINTSIZE\nuniform float pointSize;\n#endif","bumpVertexDeclaration":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#endif\n","clipPlaneVertexDeclaration":"#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif","fogVertexDeclaration":"#ifdef FOG\nvarying vec3 vFogDistance;\n#endif","morphTargetsVertexGlobalDeclaration":"#ifdef MORPHTARGETS\nuniform float morphTargetInfluences[NUM_MORPH_INFLUENCERS];\n#endif","morphTargetsVertexDeclaration":"#ifdef MORPHTARGETS\nattribute vec3 position{X};\n#ifdef MORPHTARGETS_NORMAL\nattribute vec3 normal{X};\n#endif\n#ifdef MORPHTARGETS_TANGENT\nattribute vec3 tangent{X};\n#endif\n#endif","logDepthDeclaration":"#ifdef LOGARITHMICDEPTH\nuniform float logarithmicDepthConstant;\nvarying float vFragmentDepth;\n#endif","morphTargetsVertex":"#ifdef MORPHTARGETS\npositionUpdated+=(position{X}-position)*morphTargetInfluences[{X}];\n#ifdef MORPHTARGETS_NORMAL\nnormalUpdated+=(normal{X}-normal)*morphTargetInfluences[{X}];\n#endif\n#ifdef MORPHTARGETS_TANGENT\ntangentUpdated.xyz+=(tangent{X}-tangent.xyz)*morphTargetInfluences[{X}];\n#endif\n#endif","instancesVertex":"#ifdef INSTANCES\nmat4 finalWorld=mat4(world0,world1,world2,world3);\n#else\nmat4 finalWorld=world;\n#endif","bonesVertex":"#if NUM_BONE_INFLUENCERS>0\nmat4 influence;\ninfluence=mBones[int(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence+=mBones[int(matricesIndices[1])]*matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence+=mBones[int(matricesIndices[2])]*matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence+=mBones[int(matricesIndices[3])]*matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence+=mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence+=mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence+=mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif \nfinalWorld=finalWorld*influence;\n#endif","bumpVertex":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL)\nvec3 tbnNormal=normalize(normalUpdated);\nvec3 tbnTangent=normalize(tangentUpdated.xyz);\nvec3 tbnBitangent=cross(tbnNormal,tbnTangent)*tangentUpdated.w;\nvTBN=mat3(finalWorld)*mat3(tbnTangent,tbnBitangent,tbnNormal);\n#endif\n#endif","clipPlaneVertex":"#ifdef CLIPPLANE\nfClipDistance=dot(worldPos,vClipPlane);\n#endif","fogVertex":"#ifdef FOG\nvFogDistance=(view*worldPos).xyz;\n#endif","shadowsVertex":"#ifdef SHADOWS\n#if defined(SHADOW{X}) && !defined(SHADOWCUBE{X})\nvPositionFromLight{X}=lightMatrix{X}*worldPos;\nvDepthMetric{X}=((vPositionFromLight{X}.z+light{X}.depthValues.x)/(light{X}.depthValues.y));\n#endif\n#endif","pointCloudVertex":"#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif","logDepthVertex":"#ifdef LOGARITHMICDEPTH\nvFragmentDepth=1.0+gl_Position.w;\ngl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;\n#endif","helperFunctions":"const float PI=3.1415926535897932384626433832795;\nconst float LinearEncodePowerApprox=2.2;\nconst float GammaEncodePowerApprox=1.0/LinearEncodePowerApprox;\nconst vec3 LuminanceEncodeApprox=vec3(0.2126,0.7152,0.0722);\nmat3 transposeMat3(mat3 inMatrix) {\nvec3 i0=inMatrix[0];\nvec3 i1=inMatrix[1];\nvec3 i2=inMatrix[2];\nmat3 outMatrix=mat3(\nvec3(i0.x,i1.x,i2.x),\nvec3(i0.y,i1.y,i2.y),\nvec3(i0.z,i1.z,i2.z)\n);\nreturn outMatrix;\n}\n\nmat3 inverseMat3(mat3 inMatrix) {\nfloat a00=inMatrix[0][0],a01=inMatrix[0][1],a02=inMatrix[0][2];\nfloat a10=inMatrix[1][0],a11=inMatrix[1][1],a12=inMatrix[1][2];\nfloat a20=inMatrix[2][0],a21=inMatrix[2][1],a22=inMatrix[2][2];\nfloat b01=a22*a11-a12*a21;\nfloat b11=-a22*a10+a12*a20;\nfloat b21=a21*a10-a11*a20;\nfloat det=a00*b01+a01*b11+a02*b21;\nreturn mat3(b01,(-a22*a01+a02*a21),(a12*a01-a02*a11),\nb11,(a22*a00-a02*a20),(-a12*a00+a02*a10),\nb21,(-a21*a00+a01*a20),(a11*a00-a01*a10))/det;\n}\nfloat computeFallOff(float value,vec2 clipSpace,float frustumEdgeFalloff)\n{\nfloat mask=smoothstep(1.0-frustumEdgeFalloff,1.0,clamp(dot(clipSpace,clipSpace),0.,1.));\nreturn mix(value,1.0,mask);\n}\nvec3 applyEaseInOut(vec3 x){\nreturn x*x*(3.0-2.0*x);\n}\nvec3 toLinearSpace(vec3 color)\n{\nreturn pow(color,vec3(LinearEncodePowerApprox));\n}\nvec3 toGammaSpace(vec3 color)\n{\nreturn pow(color,vec3(GammaEncodePowerApprox));\n}\nfloat square(float value)\n{\nreturn value*value;\n}\nfloat getLuminance(vec3 color)\n{\nreturn clamp(dot(color,LuminanceEncodeApprox),0.,1.);\n}\n\nfloat getRand(vec2 seed) {\nreturn fract(sin(dot(seed.xy ,vec2(12.9898,78.233)))*43758.5453);\n}\nfloat dither(vec2 seed,float varianceAmount) {\nfloat rand=getRand(seed);\nfloat dither=mix(-varianceAmount/255.0,varianceAmount/255.0,rand);\nreturn dither;\n}","lightFragmentDeclaration":"#ifdef LIGHT{X}\nuniform vec4 vLightData{X};\nuniform vec4 vLightDiffuse{X};\n#ifdef SPECULARTERM\nuniform vec3 vLightSpecular{X};\n#else\nvec3 vLightSpecular{X}=vec3(0.);\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\nuniform sampler2D shadowSampler{X};\nuniform mat4 lightMatrix{X};\n#endif\nuniform vec4 shadowsInfo{X};\nuniform vec2 depthValues{X};\n#endif\n#ifdef SPOTLIGHT{X}\nuniform vec4 vLightDirection{X};\n#endif\n#ifdef HEMILIGHT{X}\nuniform vec3 vLightGround{X};\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#endif","lightsFragmentFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n#ifdef NDOTL\nfloat ndl;\n#endif\n};\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 lightVectorW;\nfloat attenuation=1.0;\nif (lightData.w == 0.)\n{\nvec3 direction=lightData.xyz-vPositionW;\nattenuation=max(0.,1.0-length(direction)/range);\nlightVectorW=normalize(direction);\n}\nelse\n{\nlightVectorW=normalize(-lightData.xyz);\n}\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 direction=lightData.xyz-vPositionW;\nvec3 lightVectorW=normalize(direction);\nfloat attenuation=max(0.,1.0-length(direction)/range);\n\nfloat cosAngle=max(0.,dot(lightDirection.xyz,-lightVectorW));\nif (cosAngle>=lightDirection.w)\n{\ncosAngle=max(0.,pow(cosAngle,lightData.w));\nattenuation*=cosAngle;\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nresult.diffuse=vec3(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3(0.);\n#endif\n#ifdef NDOTL\nresult.ndl=0.;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {\nlightingInfo result;\n\nfloat ndl=dot(vNormal,lightData.xyz)*0.5+0.5;\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=mix(groundColor,diffuseColor,ndl);\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightData.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor;\n#endif\nreturn result;\n}\nvec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){\nvec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);\nstrq/=strq.w;\nvec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;\n#ifdef PBR\ntextureColor=toLinearSpace(textureColor);\n#endif\nreturn textureColor;\n}","lightUboDeclaration":"#ifdef LIGHT{X}\nuniform Light{X}\n{\nvec4 vLightData;\nvec4 vLightDiffuse;\nvec3 vLightSpecular;\n#ifdef SPOTLIGHT{X}\nvec4 vLightDirection;\n#endif\n#ifdef HEMILIGHT{X}\nvec3 vLightGround;\n#endif\nvec4 shadowsInfo;\nvec2 depthValues;\n} light{X};\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\nuniform sampler2D shadowSampler{X};\nuniform mat4 lightMatrix{X};\n#endif\n#endif\n#endif","defaultVertexDeclaration":"\nuniform mat4 viewProjection;\nuniform mat4 view;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n","defaultFragmentDeclaration":"uniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifndef REFRACTIONMAP_3D\nuniform mat4 refractionMatrix;\n#endif\n#ifdef REFRACTIONFRESNEL\nuniform vec4 refractionLeftColor;\nuniform vec4 refractionRightColor;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\n#endif\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_SKYBOX\n#else\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \n#endif\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#endif","defaultUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nvec4 diffuseLeftColor;\nvec4 diffuseRightColor;\nvec4 opacityParts;\nvec4 reflectionLeftColor;\nvec4 reflectionRightColor;\nvec4 refractionLeftColor;\nvec4 refractionRightColor;\nvec4 emissiveLeftColor; \nvec4 emissiveRightColor;\nvec2 vDiffuseInfos;\nvec2 vAmbientInfos;\nvec2 vOpacityInfos;\nvec2 vReflectionInfos;\nvec3 vReflectionPosition;\nvec3 vReflectionSize;\nvec2 vEmissiveInfos;\nvec2 vLightmapInfos;\nvec2 vSpecularInfos;\nvec3 vBumpInfos;\nmat4 diffuseMatrix;\nmat4 ambientMatrix;\nmat4 opacityMatrix;\nmat4 reflectionMatrix;\nmat4 emissiveMatrix;\nmat4 lightmapMatrix;\nmat4 specularMatrix;\nmat4 bumpMatrix; \nvec4 vTangentSpaceParams;\nmat4 refractionMatrix;\nvec4 vRefractionInfos;\nvec4 vSpecularColor;\nvec3 vEmissiveColor;\nvec4 vDiffuseColor;\nfloat pointSize; \n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","shadowsFragmentFunctions":"#ifdef SHADOWS\n#ifndef SHADOWFLOAT\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x;\n#endif\nif (depth>shadow)\n{\nreturn darkness;\n}\nreturn 1.0;\n}\nfloat computeShadowWithPCFCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat visibility=1.;\nvec3 poissonDisk[4];\npoissonDisk[0]=vec3(-1.0,1.0,-1.0);\npoissonDisk[1]=vec3(1.0,-1.0,-1.0);\npoissonDisk[2]=vec3(-1.0,-1.0,-1.0);\npoissonDisk[3]=vec3(1.0,-1.0,1.0);\n\n#ifndef SHADOWFLOAT\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<depth) visibility-=0.25;\n#else\nif (textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize).x<depth) visibility-=0.25;\n#endif\nreturn min(1.0,visibility+darkness);\n}\nfloat computeShadowWithESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness); \nreturn esm;\n}\nfloat computeShadowWithCloseESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn esm;\n}\nfloat computeShadow(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadow=texture2D(shadowSampler,uv).x;\n#endif\nif (shadowPixelDepth>shadow)\n{\nreturn computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff);\n}\nreturn 1.;\n}\nfloat computeShadowWithPCF(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float mapSize,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\nfloat visibility=1.;\nvec2 poissonDisk[4];\npoissonDisk[0]=vec2(-0.94201624,-0.39906216);\npoissonDisk[1]=vec2(0.94558609,-0.76890725);\npoissonDisk[2]=vec2(-0.094184101,-0.92938870);\npoissonDisk[3]=vec2(0.34495938,0.29387760);\n\n#ifndef SHADOWFLOAT\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<shadowPixelDepth) visibility-=0.25;\n#else\nif (texture2D(shadowSampler,uv+poissonDisk[0]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[1]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[2]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[3]*mapSize).x<shadowPixelDepth) visibility-=0.25;\n#endif\nreturn computeFallOff(min(1.0,visibility+darkness),clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithCloseESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0); \n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\n#endif\n","fresnelFunction":"#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection,vec3 worldNormal,float bias,float power)\n{\nfloat fresnelTerm=pow(bias+abs(dot(viewDirection,worldNormal)),power);\nreturn clamp(fresnelTerm,0.,1.);\n}\n#endif","reflectionFunction":"#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\nvec3 parallaxCorrectNormal( vec3 vertexPos,vec3 origVec,vec3 cubeSize,vec3 cubePos ) {\n\nvec3 invOrigVec=vec3(1.0,1.0,1.0)/origVec;\nvec3 halfSize=cubeSize*0.5;\nvec3 intersecAtMaxPlane=(cubePos+halfSize-vertexPos)*invOrigVec;\nvec3 intersecAtMinPlane=(cubePos-halfSize-vertexPos)*invOrigVec;\n\nvec3 largestIntersec=max(intersecAtMaxPlane,intersecAtMinPlane);\n\nfloat distance=min(min(largestIntersec.x,largestIntersec.y),largestIntersec.z);\n\nvec3 intersectPositionWS=vertexPos+origVec*distance;\n\nreturn intersectPositionWS-cubePos;\n}\n#endif\nvec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvec3 direction=vDirectionW;\nfloat t=clamp(direction.y*-0.5+0.5,0.,1.0);\nfloat s=atan(direction.z,direction.x)*RECIPROCAL_PI2+0.5;\n#ifdef REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED\nreturn vec3(1.0-s,t,0);\n#else\nreturn vec3(s,t,0);\n#endif\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\nvec3 cameraToVertex=normalize(worldPos.xyz-vEyePosition.xyz);\nvec3 r=reflect(cameraToVertex,worldNormal);\nfloat t=clamp(r.y*-0.5+0.5,0.,1.0);\nfloat s=atan(r.z,r.x)*RECIPROCAL_PI2+0.5;\nreturn vec3(s,t,0);\n#endif\n#ifdef REFLECTIONMAP_SPHERICAL\nvec3 viewDir=normalize(vec3(view*worldPos));\nvec3 viewNormal=normalize(vec3(view*vec4(worldNormal,0.0)));\nvec3 r=reflect(viewDir,viewNormal);\nr.z=r.z-1.0;\nfloat m=2.0*length(r);\nreturn vec3(r.x/m+0.5,1.0-r.y/m-0.5,0);\n#endif\n#ifdef REFLECTIONMAP_PLANAR\nvec3 viewDir=worldPos.xyz-vEyePosition.xyz;\nvec3 coords=normalize(reflect(viewDir,worldNormal));\nreturn vec3(reflectionMatrix*vec4(coords,1));\n#endif\n#ifdef REFLECTIONMAP_CUBIC\nvec3 viewDir=normalize(worldPos.xyz-vEyePosition.xyz);\n\nvec3 coords=reflect(viewDir,worldNormal);\n#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\ncoords=parallaxCorrectNormal(worldPos.xyz,coords,vReflectionSize,vReflectionPosition);\n#endif\ncoords=vec3(reflectionMatrix*vec4(coords,0));\n#ifdef INVERTCUBICMAP\ncoords.y*=-1.0;\n#endif\nreturn coords;\n#endif\n#ifdef REFLECTIONMAP_PROJECTION\nreturn vec3(reflectionMatrix*(view*worldPos));\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nreturn vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EXPLICIT\nreturn vec3(0,0,0);\n#endif\n}","imageProcessingDeclaration":"#ifdef EXPOSURE\nuniform float exposureLinear;\n#endif\n#ifdef CONTRAST\nuniform float contrast;\n#endif\n#ifdef VIGNETTE\nuniform vec2 vInverseScreenSize;\nuniform vec4 vignetteSettings1;\nuniform vec4 vignetteSettings2;\n#endif\n#ifdef COLORCURVES\nuniform vec4 vCameraColorCurveNegative;\nuniform vec4 vCameraColorCurveNeutral;\nuniform vec4 vCameraColorCurvePositive;\n#endif\n#ifdef COLORGRADING\n#ifdef COLORGRADING3D\nuniform highp sampler3D txColorTransform;\n#else\nuniform sampler2D txColorTransform;\n#endif\nuniform vec4 colorTransformSettings;\n#endif\n#ifdef GRAIN\nuniform float grainVarianceAmount;\nuniform float grainAnimatedSeed;\n#endif","imageProcessingFunctions":"#if defined(COLORGRADING) && !defined(COLORGRADING3D)\n\nvec3 sampleTexture3D(sampler2D colorTransform,vec3 color,vec2 sampler3dSetting)\n{\nfloat sliceSize=2.0*sampler3dSetting.x; \n#ifdef SAMPLER3DGREENDEPTH\nfloat sliceContinuous=(color.g-sampler3dSetting.x)*sampler3dSetting.y;\n#else\nfloat sliceContinuous=(color.b-sampler3dSetting.x)*sampler3dSetting.y;\n#endif\nfloat sliceInteger=floor(sliceContinuous);\n\n\nfloat sliceFraction=sliceContinuous-sliceInteger;\n#ifdef SAMPLER3DGREENDEPTH\nvec2 sliceUV=color.rb;\n#else\nvec2 sliceUV=color.rg;\n#endif\nsliceUV.x*=sliceSize;\nsliceUV.x+=sliceInteger*sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice0Color=texture2D(colorTransform,sliceUV);\nsliceUV.x+=sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice1Color=texture2D(colorTransform,sliceUV);\nvec3 result=mix(slice0Color.rgb,slice1Color.rgb,sliceFraction);\n#ifdef SAMPLER3DBGRMAP\ncolor.rgb=result.rgb;\n#else\ncolor.rgb=result.bgr;\n#endif\nreturn color;\n}\n#endif\nvec4 applyImageProcessing(vec4 result) {\n#ifdef EXPOSURE\nresult.rgb*=exposureLinear;\n#endif\n#ifdef VIGNETTE\n\nvec2 viewportXY=gl_FragCoord.xy*vInverseScreenSize;\nviewportXY=viewportXY*2.0-1.0;\nvec3 vignetteXY1=vec3(viewportXY*vignetteSettings1.xy+vignetteSettings1.zw,1.0);\nfloat vignetteTerm=dot(vignetteXY1,vignetteXY1);\nfloat vignette=pow(vignetteTerm,vignetteSettings2.w);\n\nvec3 vignetteColor=vignetteSettings2.rgb;\n#ifdef VIGNETTEBLENDMODEMULTIPLY\nvec3 vignetteColorMultiplier=mix(vignetteColor,vec3(1,1,1),vignette);\nresult.rgb*=vignetteColorMultiplier;\n#endif\n#ifdef VIGNETTEBLENDMODEOPAQUE\nresult.rgb=mix(vignetteColor,result.rgb,vignette);\n#endif\n#endif\n#ifdef TONEMAPPING\nconst float tonemappingCalibration=1.590579;\nresult.rgb=1.0-exp2(-tonemappingCalibration*result.rgb);\n#endif\n\nresult.rgb=toGammaSpace(result.rgb);\nresult.rgb=clamp(result.rgb,0.0,1.0);\n#ifdef CONTRAST\n\nvec3 resultHighContrast=applyEaseInOut(result.rgb);\nif (contrast<1.0) {\n\nresult.rgb=mix(vec3(0.5,0.5,0.5),result.rgb,contrast);\n} else {\n\nresult.rgb=mix(result.rgb,resultHighContrast,contrast-1.0);\n}\n#endif\n\n#ifdef COLORGRADING\nvec3 colorTransformInput=result.rgb*colorTransformSettings.xxx+colorTransformSettings.yyy;\n#ifdef COLORGRADING3D\nvec3 colorTransformOutput=texture(txColorTransform,colorTransformInput).rgb;\n#else\nvec3 colorTransformOutput=sampleTexture3D(txColorTransform,colorTransformInput,colorTransformSettings.yz).rgb;\n#endif\nresult.rgb=mix(result.rgb,colorTransformOutput,colorTransformSettings.www);\n#endif\n#ifdef COLORCURVES\n\nfloat luma=getLuminance(result.rgb);\nvec2 curveMix=clamp(vec2(luma*3.0-1.5,luma*-3.0+1.5),vec2(0.0),vec2(1.0));\nvec4 colorCurve=vCameraColorCurveNeutral+curveMix.x*vCameraColorCurvePositive-curveMix.y*vCameraColorCurveNegative;\nresult.rgb*=colorCurve.rgb;\nresult.rgb=mix(vec3(luma),result.rgb,colorCurve.a);\n#endif\nreturn result;\n}","bumpFragmentFunctions":"#ifdef BUMP\n#if BUMPDIRECTUV == 1\n#define vBumpUV vMainUV1\n#elif BUMPDIRECTUV == 2\n#define vBumpUV vMainUV2\n#else\nvarying vec2 vBumpUV;\n#endif\nuniform sampler2D bumpSampler;\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#ifdef OBJECTSPACE_NORMALMAP\nuniform mat4 normalMatrix;\n#endif\n\nmat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv)\n{\n\nuv=gl_FrontFacing ? uv : -uv;\n\nvec3 dp1=dFdx(p);\nvec3 dp2=dFdy(p);\nvec2 duv1=dFdx(uv);\nvec2 duv2=dFdy(uv);\n\nvec3 dp2perp=cross(dp2,normal);\nvec3 dp1perp=cross(normal,dp1);\nvec3 tangent=dp2perp*duv1.x+dp1perp*duv2.x;\nvec3 bitangent=dp2perp*duv1.y+dp1perp*duv2.y;\n\ntangent*=vTangentSpaceParams.x;\nbitangent*=vTangentSpaceParams.y;\n\nfloat invmax=inversesqrt(max(dot(tangent,tangent),dot(bitangent,bitangent)));\nreturn mat3(tangent*invmax,bitangent*invmax,normal);\n}\nvec3 perturbNormal(mat3 cotangentFrame,vec2 uv)\n{\nvec3 map=texture2D(bumpSampler,uv).xyz;\nmap=map*2.0-1.0;\n#ifdef NORMALXYSCALE\nmap=normalize(map*vec3(vBumpInfos.y,vBumpInfos.y,1.0));\n#endif\nreturn normalize(cotangentFrame*map);\n}\n#ifdef PARALLAX\nconst float minSamples=4.;\nconst float maxSamples=15.;\nconst int iMaxSamples=15;\n\nvec2 parallaxOcclusion(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale) {\nfloat parallaxLimit=length(vViewDirCoT.xy)/vViewDirCoT.z;\nparallaxLimit*=parallaxScale;\nvec2 vOffsetDir=normalize(vViewDirCoT.xy);\nvec2 vMaxOffset=vOffsetDir*parallaxLimit;\nfloat numSamples=maxSamples+(dot(vViewDirCoT,vNormalCoT)*(minSamples-maxSamples));\nfloat stepSize=1.0/numSamples;\n\nfloat currRayHeight=1.0;\nvec2 vCurrOffset=vec2(0,0);\nvec2 vLastOffset=vec2(0,0);\nfloat lastSampledHeight=1.0;\nfloat currSampledHeight=1.0;\nfor (int i=0; i<iMaxSamples; i++)\n{\ncurrSampledHeight=texture2D(bumpSampler,vBumpUV+vCurrOffset).w;\n\nif (currSampledHeight>currRayHeight)\n{\nfloat delta1=currSampledHeight-currRayHeight;\nfloat delta2=(currRayHeight+stepSize)-lastSampledHeight;\nfloat ratio=delta1/(delta1+delta2);\nvCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;\n\nbreak;\n}\nelse\n{\ncurrRayHeight-=stepSize;\nvLastOffset=vCurrOffset;\nvCurrOffset+=stepSize*vMaxOffset;\nlastSampledHeight=currSampledHeight;\n}\n}\nreturn vCurrOffset;\n}\nvec2 parallaxOffset(vec3 viewDir,float heightScale)\n{\n\nfloat height=texture2D(bumpSampler,vBumpUV).w;\nvec2 texCoordOffset=heightScale*viewDir.xy*height;\nreturn -texCoordOffset;\n}\n#endif\n#endif","clipPlaneFragmentDeclaration":"#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif","fogFragmentDeclaration":"#ifdef FOG\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying vec3 vFogDistance;\nfloat CalcFogFactor()\n{\nfloat fogCoeff=1.0;\nfloat fogStart=vFogInfos.y;\nfloat fogEnd=vFogInfos.z;\nfloat fogDensity=vFogInfos.w;\nfloat fogDistance=length(vFogDistance);\nif (FOGMODE_LINEAR == vFogInfos.x)\n{\nfogCoeff=(fogEnd-fogDistance)/(fogEnd-fogStart);\n}\nelse if (FOGMODE_EXP == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDensity);\n}\nelse if (FOGMODE_EXP2 == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDistance*fogDensity*fogDensity);\n}\nreturn clamp(fogCoeff,0.0,1.0);\n}\n#endif","clipPlaneFragment":"#ifdef CLIPPLANE\nif (fClipDistance>0.0)\n{\ndiscard;\n}\n#endif","bumpFragment":"vec2 uvOffset=vec2(0.0,0.0);\n#if defined(BUMP) || defined(PARALLAX)\n#ifdef NORMALXYSCALE\nfloat normalScale=1.0;\n#else \nfloat normalScale=vBumpInfos.y;\n#endif\n#if defined(TANGENT) && defined(NORMAL)\nmat3 TBN=vTBN;\n#else\nmat3 TBN=cotangent_frame(normalW*normalScale,vPositionW,vBumpUV);\n#endif\n#endif\n#ifdef PARALLAX\nmat3 invTBN=transposeMat3(TBN);\n#ifdef PARALLAXOCCLUSION\nuvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,vBumpUV,vBumpInfos.z);\n#else\nuvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z);\n#endif\n#endif\n#ifdef BUMP\n#ifdef OBJECTSPACE_NORMALMAP\nnormalW=normalize(texture2D(bumpSampler,vBumpUV).xyz*2.0-1.0);\nnormalW=normalize(mat3(normalMatrix)*normalW); \n#else\nnormalW=perturbNormal(TBN,vBumpUV+uvOffset);\n#endif\n#endif","lightFragment":"#ifdef LIGHT{X}\n#if defined(SHADOWONLY) || (defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X}))\n\n#else\n#ifdef PBR\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#else\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,glossiness);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\ninfo.diffuse*=computeProjectionTextureDiffuseLighting(projectionLightSampler{X},textureProjectionMatrix{X});\n#endif\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWCLOSEESM{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithCloseESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithCloseESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#else\n#ifdef SHADOWESM{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#else \n#ifdef SHADOWPCF{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithPCFCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadowWithPCF(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#else\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadow(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#endif\n#endif\n#endif\n#ifdef SHADOWONLY\n#ifndef SHADOWINUSE\n#define SHADOWINUSE\n#endif\nglobalShadow+=shadow;\nshadowLightCount+=1.0;\n#endif\n#else\nshadow=1.;\n#endif\n#ifndef SHADOWONLY\n#ifdef CUSTOMUSERLIGHTING\ndiffuseBase+=computeCustomDiffuseLighting(info,diffuseBase,shadow);\n#ifdef SPECULARTERM\nspecularBase+=computeCustomSpecularLighting(info,specularBase,shadow);\n#endif\n#elif defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})\ndiffuseBase+=lightmapColor*shadow;\n#ifdef SPECULARTERM\n#ifndef LIGHTMAPNOSPECULAR{X}\nspecularBase+=info.specular*shadow*lightmapColor;\n#endif\n#endif\n#else\ndiffuseBase+=info.diffuse*shadow;\n#ifdef SPECULARTERM\nspecularBase+=info.specular*shadow;\n#endif\n#endif\n#endif\n#endif","logDepthFragment":"#ifdef LOGARITHMICDEPTH\ngl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5;\n#endif","fogFragment":"#ifdef FOG\nfloat fog=CalcFogFactor();\ncolor.rgb=fog*color.rgb+(1.0-fog)*vFogColor;\n#endif","pbrVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef ALBEDO\nuniform mat4 albedoMatrix;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#ifdef REFLECTIVITY \nuniform vec3 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform mat4 microSurfaceSamplerMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n","pbrFragmentDeclaration":"uniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\n\nuniform vec4 vLightingIntensity;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\n\n#ifdef ALBEDO\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef REFLECTIVITY\nuniform vec3 vReflectivityInfos;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\n#endif\n\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \n#endif\n#endif","pbrUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec2 vAlbedoInfos;\nuniform vec3 vAmbientInfos;\nuniform vec2 vOpacityInfos;\nuniform vec2 vEmissiveInfos;\nuniform vec2 vLightmapInfos;\nuniform vec3 vReflectivityInfos;\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform vec4 vRefractionInfos;\nuniform vec2 vReflectionInfos;\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \nuniform vec3 vBumpInfos;\nuniform mat4 albedoMatrix;\nuniform mat4 ambientMatrix;\nuniform mat4 opacityMatrix;\nuniform mat4 emissiveMatrix;\nuniform mat4 lightmapMatrix;\nuniform mat4 reflectivityMatrix;\nuniform mat4 microSurfaceSamplerMatrix;\nuniform mat4 bumpMatrix;\nuniform vec2 vTangentSpaceParams;\nuniform mat4 refractionMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\nuniform vec4 vLightingIntensity;\nuniform vec3 vRefractionMicrosurfaceInfos;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\nuniform float pointSize;\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","pbrFunctions":"\n#define RECIPROCAL_PI2 0.15915494\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\n\nconst float kRougnhessToAlphaScale=0.1;\nconst float kRougnhessToAlphaOffset=0.29248125;\nfloat convertRoughnessToAverageSlope(float roughness)\n{\n\nconst float kMinimumVariance=0.0005;\nfloat alphaG=square(roughness)+kMinimumVariance;\nreturn alphaG;\n}\n\nfloat smithVisibilityG1_TrowbridgeReitzGGX(float dot,float alphaG)\n{\nfloat tanSquared=(1.0-dot*dot)/(dot*dot);\nreturn 2.0/(1.0+sqrt(1.0+alphaG*alphaG*tanSquared));\n}\nfloat smithVisibilityG_TrowbridgeReitzGGX_Walter(float NdotL,float NdotV,float alphaG)\n{\nreturn smithVisibilityG1_TrowbridgeReitzGGX(NdotL,alphaG)*smithVisibilityG1_TrowbridgeReitzGGX(NdotV,alphaG);\n}\n\n\nfloat normalDistributionFunction_TrowbridgeReitzGGX(float NdotH,float alphaG)\n{\n\n\n\nfloat a2=square(alphaG);\nfloat d=NdotH*NdotH*(a2-1.0)+1.0;\nreturn a2/(PI*d*d);\n}\nvec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90)\n{\nreturn reflectance0+(reflectance90-reflectance0)*pow(clamp(1.0-VdotH,0.,1.),5.0);\n}\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n\nvec3 computeSpecularTerm(float NdotH,float NdotL,float NdotV,float VdotH,float roughness,vec3 reflectance0,vec3 reflectance90)\n{\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\nfloat distribution=normalDistributionFunction_TrowbridgeReitzGGX(NdotH,alphaG);\nfloat visibility=smithVisibilityG_TrowbridgeReitzGGX_Walter(NdotL,NdotV,alphaG);\nvisibility/=(4.0*NdotL*NdotV); \nfloat specTerm=max(0.,visibility*distribution)*NdotL;\nvec3 fresnel=fresnelSchlickGGX(VdotH,reflectance0,reflectance90);\nreturn fresnel*specTerm;\n}\nfloat computeDiffuseTerm(float NdotL,float NdotV,float VdotH,float roughness)\n{\n\n\nfloat diffuseFresnelNV=pow(clamp(1.0-NdotL,0.000001,1.),5.0);\nfloat diffuseFresnelNL=pow(clamp(1.0-NdotV,0.000001,1.),5.0);\nfloat diffuseFresnel90=0.5+2.0*VdotH*VdotH*roughness;\nfloat fresnel =\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNL) *\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNV);\nreturn fresnel*NdotL/PI;\n}\nfloat adjustRoughnessFromLightProperties(float roughness,float lightRadius,float lightDistance)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\n\nfloat lightRoughness=lightRadius/lightDistance;\n\nfloat totalRoughness=clamp(lightRoughness+roughness,0.,1.);\nreturn totalRoughness;\n#else\nreturn roughness;\n#endif\n}\nfloat computeDefaultMicroSurface(float microSurface,vec3 reflectivityColor)\n{\nconst float kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;\nfloat reflectivityLuminance=getLuminance(reflectivityColor);\nfloat reflectivityLuma=sqrt(reflectivityLuminance);\nmicroSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;\nreturn microSurface;\n}\n\n\nfloat fresnelGrazingReflectance(float reflectance0) {\nfloat reflectance90=clamp(reflectance0*25.0,0.0,1.0);\nreturn reflectance90;\n}\n\n\n#define UNPACK_LOD(x) (1.0-x)*255.0\nfloat getLodFromAlphaG(float cubeMapDimensionPixels,float alphaG,float NdotV) {\nfloat microsurfaceAverageSlope=alphaG;\n\n\n\n\n\n\nmicrosurfaceAverageSlope*=sqrt(abs(NdotV));\nfloat microsurfaceAverageSlopeTexels=microsurfaceAverageSlope*cubeMapDimensionPixels;\nfloat lod=log2(microsurfaceAverageSlopeTexels);\nreturn lod;\n}\nfloat environmentRadianceOcclusion(float ambientOcclusion,float NdotVUnclamped) {\n\n\nfloat temp=NdotVUnclamped+ambientOcclusion;\nreturn clamp(square(temp)-1.0+ambientOcclusion,0.0,1.0);\n}\nfloat environmentHorizonOcclusion(vec3 reflection,vec3 normal) {\n\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflection.z*=-1.0;\n#endif\nfloat temp=clamp( 1.0+1.1*dot(reflection,normal),0.0,1.0);\nreturn square(temp);\n}","harmonicsFunctions":"#ifdef USESPHERICALFROMREFLECTIONMAP\nuniform vec3 vSphericalX;\nuniform vec3 vSphericalY;\nuniform vec3 vSphericalZ;\nuniform vec3 vSphericalXX_ZZ;\nuniform vec3 vSphericalYY_ZZ;\nuniform vec3 vSphericalZZ;\nuniform vec3 vSphericalXY;\nuniform vec3 vSphericalYZ;\nuniform vec3 vSphericalZX;\nvec3 quaternionVectorRotation_ScaledSqrtTwo(vec4 Q,vec3 V){\nvec3 T=cross(Q.xyz,V);\nT+=Q.www*V;\nreturn cross(Q.xyz,T)+V;\n}\nvec3 environmentIrradianceJones(vec3 normal)\n{\n\n\n\n\n\n\n\n\n\nfloat Nx=normal.x;\nfloat Ny=normal.y;\nfloat Nz=normal.z;\nvec3 C1=vSphericalZZ.rgb;\nvec3 Cx=vSphericalX.rgb;\nvec3 Cy=vSphericalY.rgb;\nvec3 Cz=vSphericalZ.rgb;\nvec3 Cxx_zz=vSphericalXX_ZZ.rgb;\nvec3 Cyy_zz=vSphericalYY_ZZ.rgb;\nvec3 Cxy=vSphericalXY.rgb;\nvec3 Cyz=vSphericalYZ.rgb;\nvec3 Czx=vSphericalZX.rgb;\nvec3 a1=Cyy_zz*Ny+Cy;\nvec3 a2=Cyz*Nz+a1;\nvec3 b1=Czx*Nz+Cx;\nvec3 b2=Cxy*Ny+b1;\nvec3 b3=Cxx_zz*Nx+b2;\nvec3 t1=Cz*Nz+C1;\nvec3 t2=a2*Ny+t1;\nvec3 t3=b3*Nx+t2;\nreturn t3;\n}\n#endif","pbrLightFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n};\nfloat computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range)\n{ \n#ifdef USEPHYSICALLIGHTFALLOFF\nfloat lightDistanceFalloff=1.0/((lightDistanceSquared+0.001));\n#else\nfloat lightDistanceFalloff=max(0.,1.0-length(lightOffset)/range);\n#endif\nreturn lightDistanceFalloff;\n}\nfloat computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent)\n{\nfloat falloff=0.0;\n#ifdef USEPHYSICALLIGHTFALLOFF\nconst float kMinusLog2ConeAngleIntensityRatio=6.64385618977; \n\n\n\n\n\nfloat concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);\n\n\nvec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);\nfalloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));\n#else\nfloat cosAngle=max(0.000000000000001,dot(-lightDirection,directionToLightCenterW));\nif (cosAngle>=cosHalfAngle)\n{\nfalloff=max(0.,pow(cosAngle,exponent));\n}\n#endif\nreturn falloff;\n}\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\nvec3 lightDirection;\nfloat attenuation=1.0;\nfloat lightDistance;\n\nif (lightData.w == 0.)\n{\nvec3 lightOffset=lightData.xyz-vPositionW;\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nattenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\nlightDistance=sqrt(lightDistanceSquared);\nlightDirection=normalize(lightOffset);\n}\n\nelse\n{\nlightDistance=length(-lightData.xyz);\nlightDirection=normalize(-lightData.xyz);\n}\n\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+lightDirection);\nNdotL=clamp(dot(vNormal,lightDirection),0.00000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\nvec3 lightOffset=lightData.xyz-vPositionW;\nvec3 directionToLightCenterW=normalize(lightOffset);\n\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nfloat attenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\n\nfloat directionalAttenuation=computeDirectionalLightFalloff(lightDirection.xyz,directionToLightCenterW,lightDirection.w,lightData.w);\nattenuation*=directionalAttenuation;\n\nfloat lightDistance=sqrt(lightDistanceSquared);\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+directionToLightCenterW);\nNdotL=clamp(dot(vNormal,directionToLightCenterW),0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\n\n\n\nNdotL=dot(vNormal,lightData.xyz)*0.5+0.5;\nresult.diffuse=mix(groundColor,diffuseColor,NdotL);\n#ifdef SPECULARTERM\n\nvec3 lightVectorW=normalize(lightData.xyz);\nvec3 H=normalize(viewDirectionW+lightVectorW);\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nNdotL=clamp(NdotL,0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90);\nresult.specular=specTerm*diffuseColor;\n#endif\nreturn result;\n}","kernelBlurFragment":"#ifdef DOF\nsampleDepth=sampleDistance(sampleCoord{X});\nfactor=clamp(1.0-((centerSampleDepth-sampleDepth)/centerSampleDepth),0.0,1.0);\ncomputedWeight=KERNEL_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCoord{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCoord{X})*computedWeight;\n#endif","kernelBlurFragment2":"#ifdef DOF\nsampleDepth=sampleDistance(sampleCoord{X});\nfactor=clamp(1.0-((centerSampleDepth-sampleDepth)/centerSampleDepth),0.0,1.0);\ncomputedWeight=KERNEL_DEP_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_DEP_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X})*computedWeight;\n#endif","kernelBlurVaryingDeclaration":"varying vec2 sampleCoord{X};","kernelBlurVertex":"sampleCoord{X}=sampleCenter+delta*KERNEL_OFFSET{X};","mrtFragmentDeclaration":"#if __VERSION__>=200\nlayout(location=0) out vec4 glFragData[{X}];\n#endif\n","bones300Declaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nin vec4 matricesIndices;\nin vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nin vec4 matricesIndicesExtra;\nin vec4 matricesWeightsExtra;\n#endif\n#endif","instances300Declaration":"#ifdef INSTANCES\nin vec4 world0;\nin vec4 world1;\nin vec4 world2;\nin vec4 world3;\n#else\nuniform mat4 world;\n#endif","backgroundVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\nuniform float shadowLevel;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif","backgroundFragmentDeclaration":" uniform vec4 vPrimaryColor;\nuniform vec4 vSecondaryColor;\nuniform vec4 vTertiaryColor;\nuniform float shadowLevel;\nuniform float alpha;\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif","backgroundUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec4 vPrimaryColor;\nuniform vec4 vSecondaryColor;\nuniform vec4 vTertiaryColor;\nuniform vec2 vDiffuseInfos;\nuniform vec2 vReflectionInfos;\nuniform mat4 diffuseMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\nuniform float pointSize;\nuniform float shadowLevel;\nuniform float alpha;\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};"};
  91342. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  91343. globalObject["BABYLON"] = BABYLON
  91344. return BABYLON;
  91345. });
  91346. /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(16)))
  91347. /***/ }),
  91348. /* 1 */
  91349. /***/ (function(module, exports, __webpack_require__) {
  91350. "use strict";
  91351. Object.defineProperty(exports, "__esModule", { value: true });
  91352. var babylonjs_1 = __webpack_require__(0);
  91353. var helper_1 = __webpack_require__(2);
  91354. var HTMLMapper = (function () {
  91355. function HTMLMapper() {
  91356. }
  91357. HTMLMapper.prototype.map = function (element) {
  91358. var config = {};
  91359. var _loop_1 = function (attrIdx) {
  91360. var attr = element.attributes.item(attrIdx);
  91361. var split = attr.nodeName.split('.');
  91362. split.reduce(function (currentConfig, key, idx) {
  91363. var camelKey = helper_1.kebabToCamel(key);
  91364. if (idx === split.length - 1) {
  91365. var val = attr.nodeValue;
  91366. if (val === "true") {
  91367. val = true;
  91368. }
  91369. else if (val === "false") {
  91370. val = false;
  91371. }
  91372. else {
  91373. var isnum = /^\d+$/.test(val);
  91374. if (isnum) {
  91375. var number = parseFloat(val);
  91376. if (!isNaN(number)) {
  91377. val = number;
  91378. }
  91379. }
  91380. }
  91381. currentConfig[camelKey] = val;
  91382. }
  91383. else {
  91384. currentConfig[camelKey] = currentConfig[camelKey] || {};
  91385. }
  91386. return currentConfig[camelKey];
  91387. }, config);
  91388. };
  91389. for (var attrIdx = 0; attrIdx < element.attributes.length; ++attrIdx) {
  91390. _loop_1(attrIdx);
  91391. }
  91392. return config;
  91393. };
  91394. return HTMLMapper;
  91395. }());
  91396. var JSONMapper = (function () {
  91397. function JSONMapper() {
  91398. }
  91399. JSONMapper.prototype.map = function (rawSource) {
  91400. return JSON.parse(rawSource);
  91401. };
  91402. return JSONMapper;
  91403. }());
  91404. var DOMMapper = (function () {
  91405. function DOMMapper() {
  91406. }
  91407. DOMMapper.prototype.map = function (baseElement) {
  91408. var htmlMapper = new HTMLMapper();
  91409. var config = htmlMapper.map(baseElement);
  91410. var traverseChildren = function (element, partConfig) {
  91411. var children = element.children;
  91412. if (children.length) {
  91413. for (var i = 0; i < children.length; ++i) {
  91414. var item = children.item(i);
  91415. var configMapped = htmlMapper.map(item);
  91416. var key = helper_1.kebabToCamel(item.nodeName.toLowerCase());
  91417. if (item.attributes.getNamedItem('array') && item.attributes.getNamedItem('array').nodeValue === 'true') {
  91418. partConfig[key] = [];
  91419. }
  91420. else {
  91421. if (element.attributes.getNamedItem('array') && element.attributes.getNamedItem('array').nodeValue === 'true') {
  91422. partConfig.push(configMapped);
  91423. }
  91424. else if (partConfig[key]) {
  91425. element.setAttribute('array', 'true');
  91426. var oldItem = partConfig[key];
  91427. partConfig = [oldItem, configMapped];
  91428. }
  91429. else {
  91430. partConfig[key] = configMapped;
  91431. }
  91432. }
  91433. traverseChildren(item, partConfig[key] || configMapped);
  91434. }
  91435. }
  91436. return partConfig;
  91437. };
  91438. traverseChildren(baseElement, config);
  91439. return config;
  91440. };
  91441. return DOMMapper;
  91442. }());
  91443. var MapperManager = (function () {
  91444. function MapperManager() {
  91445. this.mappers = {
  91446. "html": new HTMLMapper(),
  91447. "json": new JSONMapper(),
  91448. "dom": new DOMMapper()
  91449. };
  91450. }
  91451. MapperManager.prototype.getMapper = function (type) {
  91452. if (!this.mappers[type]) {
  91453. babylonjs_1.Tools.Error("No mapper defined for " + type);
  91454. }
  91455. return this.mappers[type] || this.mappers[MapperManager.DefaultMapper];
  91456. };
  91457. MapperManager.prototype.registerMapper = function (type, mapper) {
  91458. this.mappers[type] = mapper;
  91459. };
  91460. MapperManager.DefaultMapper = 'json';
  91461. return MapperManager;
  91462. }());
  91463. exports.MapperManager = MapperManager;
  91464. exports.mapperManager = new MapperManager();
  91465. /***/ }),
  91466. /* 2 */
  91467. /***/ (function(module, exports, __webpack_require__) {
  91468. "use strict";
  91469. Object.defineProperty(exports, "__esModule", { value: true });
  91470. function isUrl(urlToCheck) {
  91471. if (urlToCheck.indexOf('http') === 0 || urlToCheck.indexOf('/') === 0 || urlToCheck.indexOf('./') === 0 || urlToCheck.indexOf('../') === 0) {
  91472. return true;
  91473. }
  91474. return false;
  91475. }
  91476. exports.isUrl = isUrl;
  91477. function kebabToCamel(s) {
  91478. return s.replace(/(\-\w)/g, function (m) { return m[1].toUpperCase(); });
  91479. }
  91480. exports.kebabToCamel = kebabToCamel;
  91481. function camelToKebab(str) {
  91482. return !str ? null : str.replace(/([A-Z])/g, function (g) { return '-' + g[0].toLowerCase(); });
  91483. }
  91484. exports.camelToKebab = camelToKebab;
  91485. /***/ }),
  91486. /* 3 */
  91487. /***/ (function(module, exports, __webpack_require__) {
  91488. "use strict";
  91489. Object.defineProperty(exports, "__esModule", { value: true });
  91490. var babylonjs_1 = __webpack_require__(0);
  91491. var ViewerManager = (function () {
  91492. function ViewerManager() {
  91493. this.viewers = {};
  91494. this.onViewerAddedObservable = new babylonjs_1.Observable();
  91495. }
  91496. ViewerManager.prototype.addViewer = function (viewer) {
  91497. this.viewers[viewer.getBaseId()] = viewer;
  91498. this._onViewerAdded(viewer);
  91499. };
  91500. ViewerManager.prototype.getViewerById = function (id) {
  91501. return this.viewers[id];
  91502. };
  91503. ViewerManager.prototype.getViewerByHTMLElement = function (element) {
  91504. for (var id in this.viewers) {
  91505. if (this.viewers[id].containerElement === element) {
  91506. return this.getViewerById(id);
  91507. }
  91508. }
  91509. };
  91510. ViewerManager.prototype.getViewerPromiseById = function (id) {
  91511. var _this = this;
  91512. return new Promise(function (resolve, reject) {
  91513. var localViewer = _this.getViewerById(id);
  91514. if (localViewer) {
  91515. return resolve(localViewer);
  91516. }
  91517. var viewerFunction = function (viewer) {
  91518. if (viewer.getBaseId() === id) {
  91519. resolve(viewer);
  91520. _this.onViewerAddedObservable.removeCallback(viewerFunction);
  91521. }
  91522. };
  91523. _this.onViewerAddedObservable.add(viewerFunction);
  91524. });
  91525. };
  91526. ViewerManager.prototype._onViewerAdded = function (viewer) {
  91527. this.onViewerAdded && this.onViewerAdded(viewer);
  91528. this.onViewerAddedObservable.notifyObservers(viewer);
  91529. };
  91530. return ViewerManager;
  91531. }());
  91532. exports.ViewerManager = ViewerManager;
  91533. exports.viewerManager = new ViewerManager();
  91534. /***/ }),
  91535. /* 4 */
  91536. /***/ (function(module, exports, __webpack_require__) {
  91537. "use strict";
  91538. var __extends = (this && this.__extends) || (function () {
  91539. var extendStatics = Object.setPrototypeOf ||
  91540. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  91541. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  91542. return function (d, b) {
  91543. extendStatics(d, b);
  91544. function __() { this.constructor = d; }
  91545. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  91546. };
  91547. })();
  91548. Object.defineProperty(exports, "__esModule", { value: true });
  91549. var viewer_1 = __webpack_require__(5);
  91550. var babylonjs_1 = __webpack_require__(0);
  91551. var DefaultViewer = (function (_super) {
  91552. __extends(DefaultViewer, _super);
  91553. function DefaultViewer(containerElement, initialConfiguration) {
  91554. if (initialConfiguration === void 0) { initialConfiguration = { extends: 'default' }; }
  91555. var _this = _super.call(this, containerElement, initialConfiguration) || this;
  91556. _this.containerElement = containerElement;
  91557. _this.onModelLoaded = function (model) {
  91558. var hideLoadingDelay = 500;
  91559. if (_this.configuration.lab && _this.configuration.lab.hideLoadingDelay !== undefined) {
  91560. hideLoadingDelay = _this.configuration.lab.hideLoadingDelay;
  91561. }
  91562. setTimeout(function () {
  91563. _this.hideLoadingScreen();
  91564. }, hideLoadingDelay);
  91565. return;
  91566. };
  91567. _this.onModelLoadedObservable.add(_this.onModelLoaded);
  91568. return _this;
  91569. }
  91570. DefaultViewer.prototype.initScene = function () {
  91571. var _this = this;
  91572. return _super.prototype.initScene.call(this).then(function () {
  91573. _this.extendClassWithConfig(_this.scene, _this.configuration.scene);
  91574. return _this.scene;
  91575. });
  91576. };
  91577. DefaultViewer.prototype.onTemplatesLoaded = function () {
  91578. var _this = this;
  91579. this.showLoadingScreen();
  91580. this.initNavbar();
  91581. var closeButton = document.getElementById('close-button');
  91582. if (closeButton) {
  91583. closeButton.addEventListener('pointerdown', function () {
  91584. _this.hideOverlayScreen();
  91585. });
  91586. }
  91587. return _super.prototype.onTemplatesLoaded.call(this);
  91588. };
  91589. DefaultViewer.prototype.initNavbar = function () {
  91590. var navbar = this.templateManager.getTemplate('navBar');
  91591. if (navbar) {
  91592. var navbarHeight_1 = navbar.parent.clientHeight + 'px';
  91593. var navbarShown_1 = true;
  91594. var timeoutCancel_1;
  91595. var triggerNavbar = function (show, evt) {
  91596. if (show === void 0) { show = false; }
  91597. if (!navbar || evt.button > 0)
  91598. return;
  91599. timeoutCancel_1 && clearTimeout(timeoutCancel_1);
  91600. if (show === navbarShown_1)
  91601. return;
  91602. if (show) {
  91603. navbar.parent.style.bottom = show ? '0px' : '-' + navbarHeight_1;
  91604. navbarShown_1 = show;
  91605. }
  91606. else {
  91607. var visibilityTimeout = 2000;
  91608. if (navbar.configuration.params && navbar.configuration.params.visibilityTimeout !== undefined) {
  91609. visibilityTimeout = navbar.configuration.params.visibilityTimeout;
  91610. }
  91611. timeoutCancel_1 = setTimeout(function () {
  91612. if (navbar) {
  91613. navbar.parent.style.bottom = '-' + navbarHeight_1;
  91614. }
  91615. navbarShown_1 = show;
  91616. }, visibilityTimeout);
  91617. }
  91618. };
  91619. this.templateManager.eventManager.registerCallback('viewer', triggerNavbar.bind(this, false), 'pointerout');
  91620. this.templateManager.eventManager.registerCallback('viewer', triggerNavbar.bind(this, true), 'pointerdown');
  91621. this.templateManager.eventManager.registerCallback('viewer', triggerNavbar.bind(this, false), 'pointerup');
  91622. this.templateManager.eventManager.registerCallback('navBar', triggerNavbar.bind(this, true), 'pointerover');
  91623. var viewerTemplate = this.templateManager.getTemplate('viewer');
  91624. var viewerElement_1 = viewerTemplate && viewerTemplate.parent;
  91625. var triggerFullscren = function (eventData) {
  91626. if (viewerElement_1) {
  91627. var fullscreenElement = document.fullscreenElement || document.webkitFullscreenElement || document.mozFullScreenElement || document.msFullscreenElement;
  91628. if (!fullscreenElement) {
  91629. var requestFullScreen = viewerElement_1.requestFullscreen || viewerElement_1.webkitRequestFullscreen || viewerElement_1.msRequestFullscreen || viewerElement_1.mozRequestFullScreen;
  91630. requestFullScreen.call(viewerElement_1);
  91631. }
  91632. else {
  91633. var exitFullscreen = document.exitFullscreen || document.webkitExitFullscreen || document.msExitFullscreen || document.mozCancelFullScreen;
  91634. exitFullscreen.call(document);
  91635. }
  91636. }
  91637. };
  91638. this.templateManager.eventManager.registerCallback('navBar', triggerFullscren, 'pointerdown', '#fullscreen-button');
  91639. }
  91640. };
  91641. DefaultViewer.prototype.prepareContainerElement = function () {
  91642. this.containerElement.style.position = 'relative';
  91643. this.containerElement.style.display = 'flex';
  91644. };
  91645. DefaultViewer.prototype.configureModel = function (modelConfiguration, model) {
  91646. _super.prototype.configureModel.call(this, modelConfiguration, model);
  91647. var navbar = this.templateManager.getTemplate('navBar');
  91648. if (!navbar)
  91649. return;
  91650. var metadataContainer = navbar.parent.querySelector('#model-metadata');
  91651. if (metadataContainer) {
  91652. if (modelConfiguration.title !== undefined) {
  91653. var element = metadataContainer.querySelector('span.model-title');
  91654. if (element) {
  91655. element.innerHTML = modelConfiguration.title;
  91656. }
  91657. }
  91658. if (modelConfiguration.subtitle !== undefined) {
  91659. var element = metadataContainer.querySelector('span.model-subtitle');
  91660. if (element) {
  91661. element.innerHTML = modelConfiguration.subtitle;
  91662. }
  91663. }
  91664. if (modelConfiguration.thumbnail !== undefined) {
  91665. metadataContainer.querySelector('.thumbnail').style.backgroundImage = "url('" + modelConfiguration.thumbnail + "')";
  91666. }
  91667. }
  91668. };
  91669. DefaultViewer.prototype.loadModel = function (model) {
  91670. var _this = this;
  91671. if (model === void 0) { model = this.configuration.model; }
  91672. this.showLoadingScreen();
  91673. return _super.prototype.loadModel.call(this, model, true).catch(function (error) {
  91674. console.log(error);
  91675. _this.hideLoadingScreen();
  91676. _this.showOverlayScreen('error');
  91677. return Promise.reject(error);
  91678. });
  91679. };
  91680. DefaultViewer.prototype.showOverlayScreen = function (subScreen) {
  91681. var _this = this;
  91682. var template = this.templateManager.getTemplate('overlay');
  91683. if (!template)
  91684. return Promise.resolve('Overlay template not found');
  91685. return template.show((function (template) {
  91686. var canvasRect = _this.containerElement.getBoundingClientRect();
  91687. var canvasPositioning = window.getComputedStyle(_this.containerElement).position;
  91688. template.parent.style.display = 'flex';
  91689. template.parent.style.width = canvasRect.width + "px";
  91690. template.parent.style.height = canvasRect.height + "px";
  91691. template.parent.style.opacity = "1";
  91692. var subTemplate = _this.templateManager.getTemplate(subScreen);
  91693. if (!subTemplate) {
  91694. return Promise.reject(subScreen + ' template not found');
  91695. }
  91696. return subTemplate.show((function (template) {
  91697. template.parent.style.display = 'flex';
  91698. return Promise.resolve(template);
  91699. }));
  91700. }));
  91701. };
  91702. DefaultViewer.prototype.hideOverlayScreen = function () {
  91703. var template = this.templateManager.getTemplate('overlay');
  91704. if (!template)
  91705. return Promise.resolve('Overlay template not found');
  91706. return template.hide((function (template) {
  91707. template.parent.style.opacity = "0";
  91708. var onTransitionEnd = function () {
  91709. template.parent.removeEventListener("transitionend", onTransitionEnd);
  91710. template.parent.style.display = 'none';
  91711. };
  91712. template.parent.addEventListener("transitionend", onTransitionEnd);
  91713. var overlays = template.parent.querySelectorAll('.overlay');
  91714. if (overlays) {
  91715. for (var i = 0; i < overlays.length; ++i) {
  91716. var htmlElement = overlays.item(i);
  91717. htmlElement.style.display = 'none';
  91718. }
  91719. }
  91720. return Promise.resolve(template);
  91721. }));
  91722. };
  91723. DefaultViewer.prototype.showLoadingScreen = function () {
  91724. var _this = this;
  91725. var template = this.templateManager.getTemplate('loadingScreen');
  91726. if (!template)
  91727. return Promise.resolve('Loading Screen template not found');
  91728. return template.show((function (template) {
  91729. var canvasRect = _this.containerElement.getBoundingClientRect();
  91730. var canvasPositioning = window.getComputedStyle(_this.containerElement).position;
  91731. template.parent.style.display = 'flex';
  91732. template.parent.style.width = canvasRect.width + "px";
  91733. template.parent.style.height = canvasRect.height + "px";
  91734. template.parent.style.opacity = "1";
  91735. template.parent.style.backgroundColor = "black";
  91736. return Promise.resolve(template);
  91737. }));
  91738. };
  91739. DefaultViewer.prototype.hideLoadingScreen = function () {
  91740. var template = this.templateManager.getTemplate('loadingScreen');
  91741. if (!template)
  91742. return Promise.resolve('Loading Screen template not found');
  91743. return template.hide((function (template) {
  91744. template.parent.style.opacity = "0";
  91745. var onTransitionEnd = function () {
  91746. template.parent.removeEventListener("transitionend", onTransitionEnd);
  91747. template.parent.style.display = 'none';
  91748. };
  91749. template.parent.addEventListener("transitionend", onTransitionEnd);
  91750. return Promise.resolve(template);
  91751. }));
  91752. };
  91753. DefaultViewer.prototype.configureLights = function (lightsConfiguration, model) {
  91754. var _this = this;
  91755. if (lightsConfiguration === void 0) { lightsConfiguration = {}; }
  91756. _super.prototype.configureLights.call(this, lightsConfiguration, model);
  91757. if (this.configuration.lab && this.configuration.lab.flashlight) {
  91758. var pointerPosition = BABYLON.Vector3.Zero();
  91759. var lightTarget_1;
  91760. var angle = 0.5;
  91761. var exponent = Math.PI / 2;
  91762. if (typeof this.configuration.lab.flashlight === "object") {
  91763. exponent = this.configuration.lab.flashlight.exponent || exponent;
  91764. angle = this.configuration.lab.flashlight.angle || angle;
  91765. }
  91766. var flashlight = new babylonjs_1.SpotLight("flashlight", babylonjs_1.Vector3.Zero(), babylonjs_1.Vector3.Zero(), exponent, angle, this.scene);
  91767. if (typeof this.configuration.lab.flashlight === "object") {
  91768. flashlight.intensity = this.configuration.lab.flashlight.intensity || flashlight.intensity;
  91769. if (this.configuration.lab.flashlight.diffuse) {
  91770. flashlight.diffuse.r = this.configuration.lab.flashlight.diffuse.r;
  91771. flashlight.diffuse.g = this.configuration.lab.flashlight.diffuse.g;
  91772. flashlight.diffuse.b = this.configuration.lab.flashlight.diffuse.b;
  91773. }
  91774. if (this.configuration.lab.flashlight.specular) {
  91775. flashlight.specular.r = this.configuration.lab.flashlight.specular.r;
  91776. flashlight.specular.g = this.configuration.lab.flashlight.specular.g;
  91777. flashlight.specular.b = this.configuration.lab.flashlight.specular.b;
  91778. }
  91779. }
  91780. this.scene.constantlyUpdateMeshUnderPointer = true;
  91781. this.scene.onPointerObservable.add(function (eventData, eventState) {
  91782. if (eventData.type === 4 && eventData.pickInfo) {
  91783. lightTarget_1 = (eventData.pickInfo.pickedPoint);
  91784. }
  91785. else {
  91786. lightTarget_1 = undefined;
  91787. }
  91788. });
  91789. var updateFlashlightFunction = function () {
  91790. if (_this.camera && flashlight) {
  91791. flashlight.position.copyFrom(_this.camera.position);
  91792. if (lightTarget_1) {
  91793. lightTarget_1.subtractToRef(flashlight.position, flashlight.direction);
  91794. }
  91795. }
  91796. };
  91797. this.scene.registerBeforeRender(updateFlashlightFunction);
  91798. this.registeredOnBeforerenderFunctions.push(updateFlashlightFunction);
  91799. }
  91800. };
  91801. return DefaultViewer;
  91802. }(viewer_1.AbstractViewer));
  91803. exports.DefaultViewer = DefaultViewer;
  91804. /***/ }),
  91805. /* 5 */
  91806. /***/ (function(module, exports, __webpack_require__) {
  91807. "use strict";
  91808. Object.defineProperty(exports, "__esModule", { value: true });
  91809. var viewerManager_1 = __webpack_require__(3);
  91810. var templateManager_1 = __webpack_require__(19);
  91811. var loader_1 = __webpack_require__(22);
  91812. var babylonjs_1 = __webpack_require__(0);
  91813. var deepmerge = __webpack_require__(13);
  91814. var viewerModel_1 = __webpack_require__(30);
  91815. var AbstractViewer = (function () {
  91816. function AbstractViewer(containerElement, initialConfiguration) {
  91817. if (initialConfiguration === void 0) { initialConfiguration = {}; }
  91818. var _this = this;
  91819. this.containerElement = containerElement;
  91820. this.resize = function () {
  91821. if (!_this.isCanvasInDOM()) {
  91822. return;
  91823. }
  91824. if (_this.canvas.clientWidth <= 0 || _this.canvas.clientHeight <= 0) {
  91825. return;
  91826. }
  91827. _this.engine.resize();
  91828. };
  91829. this.render = function () {
  91830. _this.scene && _this.scene.activeCamera && _this.scene.render();
  91831. };
  91832. if (containerElement.id) {
  91833. this.baseId = containerElement.id;
  91834. }
  91835. else {
  91836. this.baseId = containerElement.id = 'bjs' + Math.random().toString(32).substr(2, 8);
  91837. }
  91838. this.onSceneInitObservable = new babylonjs_1.Observable();
  91839. this.onEngineInitObservable = new babylonjs_1.Observable();
  91840. this.onModelLoadedObservable = new babylonjs_1.Observable();
  91841. this.onModelLoadProgressObservable = new babylonjs_1.Observable();
  91842. this.onModelLoadErrorObservable = new babylonjs_1.Observable();
  91843. this.onInitDoneObservable = new babylonjs_1.Observable();
  91844. this.onLoaderInitObservable = new babylonjs_1.Observable();
  91845. this.registeredOnBeforerenderFunctions = [];
  91846. this.models = [];
  91847. viewerManager_1.viewerManager.addViewer(this);
  91848. this.templateManager = new templateManager_1.TemplateManager(containerElement);
  91849. this.prepareContainerElement();
  91850. loader_1.default.loadConfiguration(initialConfiguration, function (configuration) {
  91851. _this.configuration = deepmerge(_this.configuration || {}, configuration);
  91852. if (_this.configuration.observers) {
  91853. _this.configureObservers(_this.configuration.observers);
  91854. }
  91855. var templateConfiguration = _this.configuration.templates || {};
  91856. _this.templateManager.initTemplate(templateConfiguration);
  91857. _this.templateManager.onAllLoaded.add(function () {
  91858. var canvas = _this.templateManager.getCanvas();
  91859. if (canvas) {
  91860. _this.canvas = canvas;
  91861. }
  91862. _this._onTemplateLoaded();
  91863. });
  91864. });
  91865. }
  91866. Object.defineProperty(AbstractViewer.prototype, "isHdrSupported", {
  91867. get: function () {
  91868. return this._hdrSupport;
  91869. },
  91870. enumerable: true,
  91871. configurable: true
  91872. });
  91873. AbstractViewer.prototype.getBaseId = function () {
  91874. return this.baseId;
  91875. };
  91876. AbstractViewer.prototype.isCanvasInDOM = function () {
  91877. return !!this.canvas && !!this.canvas.parentElement;
  91878. };
  91879. AbstractViewer.prototype.updateConfiguration = function (newConfiguration) {
  91880. if (newConfiguration === void 0) { newConfiguration = this.configuration; }
  91881. this.configuration = deepmerge(this.configuration || {}, newConfiguration);
  91882. if (newConfiguration.scene) {
  91883. this.configureScene(newConfiguration.scene);
  91884. }
  91885. if (newConfiguration.optimizer) {
  91886. this.configureOptimizer(newConfiguration.optimizer);
  91887. }
  91888. if (newConfiguration.observers) {
  91889. this.configureObservers(newConfiguration.observers);
  91890. }
  91891. if (newConfiguration.model && typeof newConfiguration.model === 'object') {
  91892. this.configureModel(newConfiguration.model);
  91893. }
  91894. if (newConfiguration.lights) {
  91895. this.configureLights(newConfiguration.lights);
  91896. }
  91897. if (newConfiguration.skybox !== undefined || newConfiguration.ground !== undefined) {
  91898. this.configureEnvironment(newConfiguration.skybox, newConfiguration.ground);
  91899. }
  91900. if (newConfiguration.camera) {
  91901. this.configureCamera(newConfiguration.camera);
  91902. }
  91903. };
  91904. AbstractViewer.prototype.configureEnvironment = function (skyboxConifguration, groundConfiguration) {
  91905. if (!skyboxConifguration && !groundConfiguration) {
  91906. if (this.environmentHelper) {
  91907. this.environmentHelper.dispose();
  91908. delete this.environmentHelper;
  91909. }
  91910. ;
  91911. return Promise.resolve(this.scene);
  91912. }
  91913. var options = {
  91914. createGround: !!groundConfiguration,
  91915. createSkybox: !!skyboxConifguration,
  91916. setupImageProcessing: false
  91917. };
  91918. if (groundConfiguration) {
  91919. var groundConfig = (typeof groundConfiguration === 'boolean') ? {} : groundConfiguration;
  91920. var groundSize = groundConfig.size || (typeof skyboxConifguration === 'object' && skyboxConifguration.scale);
  91921. if (groundSize) {
  91922. options.groundSize = groundSize;
  91923. }
  91924. options.enableGroundShadow = groundConfig === true || groundConfig.receiveShadows;
  91925. if (groundConfig.shadowLevel !== undefined) {
  91926. options.groundShadowLevel = groundConfig.shadowLevel;
  91927. }
  91928. options.enableGroundMirror = !!groundConfig.mirror;
  91929. if (groundConfig.texture) {
  91930. options.groundTexture = groundConfig.texture;
  91931. }
  91932. if (groundConfig.color) {
  91933. options.groundColor = new babylonjs_1.Color3(groundConfig.color.r, groundConfig.color.g, groundConfig.color.b);
  91934. }
  91935. if (groundConfig.opacity !== undefined) {
  91936. options.groundOpacity = groundConfig.opacity;
  91937. }
  91938. if (groundConfig.mirror) {
  91939. options.enableGroundMirror = true;
  91940. if (typeof groundConfig.mirror === "object") {
  91941. if (groundConfig.mirror.amount !== undefined)
  91942. options.groundMirrorAmount = groundConfig.mirror.amount;
  91943. if (groundConfig.mirror.sizeRatio !== undefined)
  91944. options.groundMirrorSizeRatio = groundConfig.mirror.sizeRatio;
  91945. if (groundConfig.mirror.blurKernel !== undefined)
  91946. options.groundMirrorBlurKernel = groundConfig.mirror.blurKernel;
  91947. if (groundConfig.mirror.fresnelWeight !== undefined)
  91948. options.groundMirrorFresnelWeight = groundConfig.mirror.fresnelWeight;
  91949. if (groundConfig.mirror.fallOffDistance !== undefined)
  91950. options.groundMirrorFallOffDistance = groundConfig.mirror.fallOffDistance;
  91951. if (this.defaultPipelineTextureType !== undefined)
  91952. options.groundMirrorTextureType = this.defaultPipelineTextureType;
  91953. }
  91954. }
  91955. }
  91956. var postInitSkyboxMaterial = false;
  91957. if (skyboxConifguration) {
  91958. var conf = skyboxConifguration === true ? {} : skyboxConifguration;
  91959. if (conf.material && conf.material.imageProcessingConfiguration) {
  91960. options.setupImageProcessing = false;
  91961. }
  91962. var skyboxSize = conf.scale;
  91963. if (skyboxSize) {
  91964. options.skyboxSize = skyboxSize;
  91965. }
  91966. options.sizeAuto = !options.skyboxSize;
  91967. if (conf.color) {
  91968. options.skyboxColor = new babylonjs_1.Color3(conf.color.r, conf.color.g, conf.color.b);
  91969. }
  91970. if (conf.cubeTexture && conf.cubeTexture.url) {
  91971. if (typeof conf.cubeTexture.url === "string") {
  91972. options.skyboxTexture = conf.cubeTexture.url;
  91973. }
  91974. else {
  91975. postInitSkyboxMaterial = true;
  91976. }
  91977. }
  91978. if (conf.material && conf.material.imageProcessingConfiguration) {
  91979. postInitSkyboxMaterial = true;
  91980. }
  91981. }
  91982. options.setupImageProcessing = false;
  91983. if (!this.environmentHelper) {
  91984. this.environmentHelper = this.scene.createDefaultEnvironment(options);
  91985. }
  91986. else {
  91987. var scene = this.environmentHelper.rootMesh.getScene();
  91988. if (scene !== this.scene) {
  91989. this.environmentHelper.dispose();
  91990. this.environmentHelper = this.scene.createDefaultEnvironment(options);
  91991. }
  91992. else {
  91993. this.environmentHelper.updateOptions(options);
  91994. }
  91995. }
  91996. if (postInitSkyboxMaterial) {
  91997. var skyboxMaterial = this.environmentHelper.skyboxMaterial;
  91998. if (skyboxMaterial) {
  91999. if (typeof skyboxConifguration === 'object' && skyboxConifguration.material && skyboxConifguration.material.imageProcessingConfiguration) {
  92000. this.extendClassWithConfig(skyboxMaterial.imageProcessingConfiguration, skyboxConifguration.material.imageProcessingConfiguration);
  92001. }
  92002. }
  92003. }
  92004. };
  92005. AbstractViewer.prototype.configureScene = function (sceneConfig, optimizerConfig) {
  92006. if (!this.scene) {
  92007. return;
  92008. }
  92009. if (sceneConfig.debug) {
  92010. this.scene.debugLayer.show();
  92011. }
  92012. else {
  92013. if (this.scene.debugLayer.isVisible()) {
  92014. this.scene.debugLayer.hide();
  92015. }
  92016. }
  92017. if (sceneConfig.clearColor) {
  92018. var cc = sceneConfig.clearColor;
  92019. var oldcc = this.scene.clearColor;
  92020. if (cc.r !== undefined) {
  92021. oldcc.r = cc.r;
  92022. }
  92023. if (cc.g !== undefined) {
  92024. oldcc.g = cc.g;
  92025. }
  92026. if (cc.b !== undefined) {
  92027. oldcc.b = cc.b;
  92028. }
  92029. if (cc.a !== undefined) {
  92030. oldcc.a = cc.a;
  92031. }
  92032. }
  92033. if (sceneConfig.imageProcessingConfiguration) {
  92034. this.extendClassWithConfig(this.scene.imageProcessingConfiguration, sceneConfig.imageProcessingConfiguration);
  92035. }
  92036. if (sceneConfig.environmentTexture) {
  92037. if (this.scene.environmentTexture) {
  92038. this.scene.environmentTexture.dispose();
  92039. }
  92040. var environmentTexture = babylonjs_1.CubeTexture.CreateFromPrefilteredData(sceneConfig.environmentTexture, this.scene);
  92041. this.scene.environmentTexture = environmentTexture;
  92042. }
  92043. if (sceneConfig.autoRotate) {
  92044. this.camera.useAutoRotationBehavior = true;
  92045. }
  92046. };
  92047. AbstractViewer.prototype.configureOptimizer = function (optimizerConfig) {
  92048. if (typeof optimizerConfig === 'boolean') {
  92049. if (this.sceneOptimizer) {
  92050. this.sceneOptimizer.stop();
  92051. this.sceneOptimizer.dispose();
  92052. delete this.sceneOptimizer;
  92053. }
  92054. if (optimizerConfig) {
  92055. this.sceneOptimizer = new babylonjs_1.SceneOptimizer(this.scene);
  92056. this.sceneOptimizer.start();
  92057. }
  92058. }
  92059. else {
  92060. var optimizerOptions = new babylonjs_1.SceneOptimizerOptions(optimizerConfig.targetFrameRate, optimizerConfig.trackerDuration);
  92061. if (optimizerConfig.degradation) {
  92062. switch (optimizerConfig.degradation) {
  92063. case "low":
  92064. optimizerOptions = babylonjs_1.SceneOptimizerOptions.LowDegradationAllowed(optimizerConfig.targetFrameRate);
  92065. break;
  92066. case "moderate":
  92067. optimizerOptions = babylonjs_1.SceneOptimizerOptions.ModerateDegradationAllowed(optimizerConfig.targetFrameRate);
  92068. break;
  92069. case "hight":
  92070. optimizerOptions = babylonjs_1.SceneOptimizerOptions.HighDegradationAllowed(optimizerConfig.targetFrameRate);
  92071. break;
  92072. }
  92073. }
  92074. if (this.sceneOptimizer) {
  92075. this.sceneOptimizer.stop();
  92076. this.sceneOptimizer.dispose();
  92077. }
  92078. this.sceneOptimizer = new babylonjs_1.SceneOptimizer(this.scene, optimizerOptions, optimizerConfig.autoGeneratePriorities, optimizerConfig.improvementMode);
  92079. this.sceneOptimizer.start();
  92080. }
  92081. };
  92082. AbstractViewer.prototype.configureObservers = function (observersConfiguration) {
  92083. if (observersConfiguration.onEngineInit) {
  92084. this.onEngineInitObservable.add(window[observersConfiguration.onEngineInit]);
  92085. }
  92086. else {
  92087. if (observersConfiguration.onEngineInit === '' && this.configuration.observers && this.configuration.observers.onEngineInit) {
  92088. this.onEngineInitObservable.removeCallback(window[this.configuration.observers.onEngineInit]);
  92089. }
  92090. }
  92091. if (observersConfiguration.onSceneInit) {
  92092. this.onSceneInitObservable.add(window[observersConfiguration.onSceneInit]);
  92093. }
  92094. else {
  92095. if (observersConfiguration.onSceneInit === '' && this.configuration.observers && this.configuration.observers.onSceneInit) {
  92096. this.onSceneInitObservable.removeCallback(window[this.configuration.observers.onSceneInit]);
  92097. }
  92098. }
  92099. if (observersConfiguration.onModelLoaded) {
  92100. this.onModelLoadedObservable.add(window[observersConfiguration.onModelLoaded]);
  92101. }
  92102. else {
  92103. if (observersConfiguration.onModelLoaded === '' && this.configuration.observers && this.configuration.observers.onModelLoaded) {
  92104. this.onModelLoadedObservable.removeCallback(window[this.configuration.observers.onModelLoaded]);
  92105. }
  92106. }
  92107. };
  92108. AbstractViewer.prototype.configureCamera = function (cameraConfig, model) {
  92109. var _this = this;
  92110. var focusMeshes = model ? model.meshes : this.scene.meshes;
  92111. if (!this.scene.activeCamera) {
  92112. this.scene.createDefaultCamera(true, true, true);
  92113. this.camera = this.scene.activeCamera;
  92114. }
  92115. if (cameraConfig.position) {
  92116. this.camera.position.copyFromFloats(cameraConfig.position.x || 0, cameraConfig.position.y || 0, cameraConfig.position.z || 0);
  92117. }
  92118. if (cameraConfig.rotation) {
  92119. this.camera.rotationQuaternion = new babylonjs_1.Quaternion(cameraConfig.rotation.x || 0, cameraConfig.rotation.y || 0, cameraConfig.rotation.z || 0, cameraConfig.rotation.w || 0);
  92120. }
  92121. this.extendClassWithConfig(this.camera, cameraConfig);
  92122. this.camera.minZ = cameraConfig.minZ || this.camera.minZ;
  92123. this.camera.maxZ = cameraConfig.maxZ || this.camera.maxZ;
  92124. if (cameraConfig.behaviors) {
  92125. for (var name_1 in cameraConfig.behaviors) {
  92126. this.setCameraBehavior(cameraConfig.behaviors[name_1], focusMeshes);
  92127. }
  92128. }
  92129. ;
  92130. var sceneExtends = this.scene.getWorldExtends(function (mesh) {
  92131. return !_this.environmentHelper || (mesh !== _this.environmentHelper.ground && mesh !== _this.environmentHelper.rootMesh && mesh !== _this.environmentHelper.skybox);
  92132. });
  92133. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  92134. var sceneDiagonalLenght = sceneDiagonal.length();
  92135. if (isFinite(sceneDiagonalLenght))
  92136. this.camera.upperRadiusLimit = sceneDiagonalLenght * 3;
  92137. };
  92138. AbstractViewer.prototype.configureLights = function (lightsConfiguration, model) {
  92139. var _this = this;
  92140. if (lightsConfiguration === void 0) { lightsConfiguration = {}; }
  92141. var focusMeshes = model ? model.meshes : this.scene.meshes;
  92142. if (!Object.keys(lightsConfiguration).length)
  92143. return;
  92144. var lightsAvailable = this.scene.lights.map(function (light) { return light.name; });
  92145. var lightsToConfigure = Object.keys(this.configuration.lights || []);
  92146. if (Object.keys(lightsToConfigure).length !== lightsAvailable.length) {
  92147. lightsAvailable.forEach(function (lName) {
  92148. if (lightsToConfigure.indexOf(lName) === -1) {
  92149. _this.scene.getLightByName(lName).dispose();
  92150. }
  92151. });
  92152. }
  92153. Object.keys(lightsConfiguration).forEach(function (name, idx) {
  92154. var lightConfig = { type: 0 };
  92155. if (typeof lightsConfiguration[name] === 'object') {
  92156. lightConfig = lightsConfiguration[name];
  92157. }
  92158. lightConfig.name = name;
  92159. var light;
  92160. if (lightsAvailable.indexOf(name) === -1) {
  92161. var constructor = babylonjs_1.Light.GetConstructorFromName(lightConfig.type, lightConfig.name, _this.scene);
  92162. if (!constructor)
  92163. return;
  92164. light = constructor();
  92165. }
  92166. else {
  92167. light = _this.scene.getLightByName(name);
  92168. lightsAvailable = lightsAvailable.filter(function (ln) { return ln !== name; });
  92169. if (lightConfig.type !== undefined && light.getTypeID() !== lightConfig.type) {
  92170. light.dispose();
  92171. var constructor = babylonjs_1.Light.GetConstructorFromName(lightConfig.type, lightConfig.name, _this.scene);
  92172. if (!constructor)
  92173. return;
  92174. light = constructor();
  92175. }
  92176. }
  92177. if (lightsConfiguration[name] === false) {
  92178. light.dispose();
  92179. return;
  92180. }
  92181. var enabled = lightConfig.enabled !== undefined ? lightConfig.enabled : !lightConfig.disabled;
  92182. light.setEnabled(enabled);
  92183. _this.extendClassWithConfig(light, lightConfig);
  92184. if (light instanceof babylonjs_1.ShadowLight) {
  92185. if (lightConfig.target) {
  92186. if (light.setDirectionToTarget) {
  92187. var target = babylonjs_1.Vector3.Zero().copyFrom(lightConfig.target);
  92188. light.setDirectionToTarget(target);
  92189. }
  92190. }
  92191. else if (lightConfig.direction) {
  92192. var direction = babylonjs_1.Vector3.Zero().copyFrom(lightConfig.direction);
  92193. light.direction = direction;
  92194. }
  92195. var shadowGenerator = light.getShadowGenerator();
  92196. if (lightConfig.shadowEnabled && _this.maxShadows) {
  92197. if (!shadowGenerator) {
  92198. shadowGenerator = new babylonjs_1.ShadowGenerator(512, light);
  92199. }
  92200. _this.extendClassWithConfig(shadowGenerator, lightConfig.shadowConfig || {});
  92201. var shadownMap = shadowGenerator.getShadowMap();
  92202. if (!shadownMap)
  92203. return;
  92204. var renderList = shadownMap.renderList;
  92205. for (var index = 0; index < focusMeshes.length; index++) {
  92206. if (babylonjs_1.Tags.MatchesQuery(focusMeshes[index], 'castShadow')) {
  92207. renderList && renderList.push(focusMeshes[index]);
  92208. }
  92209. }
  92210. }
  92211. else if (shadowGenerator) {
  92212. shadowGenerator.dispose();
  92213. }
  92214. }
  92215. });
  92216. };
  92217. AbstractViewer.prototype.configureModel = function (modelConfiguration, model) {
  92218. var focusMeshes = model ? model.meshes : this.scene.meshes;
  92219. var meshesWithNoParent = focusMeshes.filter(function (m) { return !m.parent; });
  92220. var updateMeshesWithNoParent = function (variable, value, param) {
  92221. meshesWithNoParent.forEach(function (mesh) {
  92222. if (param) {
  92223. mesh[variable][param] = value;
  92224. }
  92225. else {
  92226. mesh[variable] = value;
  92227. }
  92228. });
  92229. };
  92230. var updateXYZ = function (variable, configValues) {
  92231. if (configValues.x !== undefined) {
  92232. updateMeshesWithNoParent(variable, configValues.x, 'x');
  92233. }
  92234. if (configValues.y !== undefined) {
  92235. updateMeshesWithNoParent(variable, configValues.y, 'y');
  92236. }
  92237. if (configValues.z !== undefined) {
  92238. updateMeshesWithNoParent(variable, configValues.z, 'z');
  92239. }
  92240. if (configValues.w !== undefined) {
  92241. updateMeshesWithNoParent(variable, configValues.w, 'w');
  92242. }
  92243. };
  92244. if (modelConfiguration.position) {
  92245. updateXYZ('position', modelConfiguration.position);
  92246. }
  92247. if (modelConfiguration.rotation) {
  92248. if (modelConfiguration.rotation.w) {
  92249. meshesWithNoParent.forEach(function (mesh) {
  92250. if (!mesh.rotationQuaternion) {
  92251. mesh.rotationQuaternion = new babylonjs_1.Quaternion();
  92252. }
  92253. });
  92254. updateXYZ('rotationQuaternion', modelConfiguration.rotation);
  92255. }
  92256. else {
  92257. updateXYZ('rotation', modelConfiguration.rotation);
  92258. }
  92259. }
  92260. if (modelConfiguration.scaling) {
  92261. updateXYZ('scaling', modelConfiguration.scaling);
  92262. }
  92263. if (modelConfiguration.castShadow) {
  92264. focusMeshes.forEach(function (mesh) {
  92265. babylonjs_1.Tags.AddTagsTo(mesh, 'castShadow');
  92266. });
  92267. }
  92268. if (modelConfiguration.normalize) {
  92269. var center = false;
  92270. var unitSize = false;
  92271. var parentIndex = void 0;
  92272. if (modelConfiguration.normalize === true) {
  92273. center = true;
  92274. unitSize = true;
  92275. parentIndex = 0;
  92276. }
  92277. else {
  92278. center = !!modelConfiguration.normalize.center;
  92279. unitSize = !!modelConfiguration.normalize.unitSize;
  92280. parentIndex = modelConfiguration.normalize.parentIndex;
  92281. }
  92282. var meshesToNormalize = [];
  92283. if (parentIndex !== undefined) {
  92284. meshesToNormalize.push(focusMeshes[parentIndex]);
  92285. }
  92286. else {
  92287. meshesToNormalize = meshesWithNoParent;
  92288. }
  92289. if (unitSize) {
  92290. meshesToNormalize.forEach(function (mesh) {
  92291. mesh.normalizeToUnitCube(true);
  92292. mesh.computeWorldMatrix(true);
  92293. });
  92294. }
  92295. if (center) {
  92296. meshesToNormalize.forEach(function (mesh) {
  92297. var boundingInfo = mesh.getHierarchyBoundingVectors(true);
  92298. var sizeVec = boundingInfo.max.subtract(boundingInfo.min);
  92299. var halfSizeVec = sizeVec.scale(0.5);
  92300. var center = boundingInfo.min.add(halfSizeVec);
  92301. mesh.position = center.scale(-1);
  92302. mesh.position.y += halfSizeVec.y;
  92303. mesh.computeWorldMatrix(true);
  92304. });
  92305. }
  92306. }
  92307. };
  92308. AbstractViewer.prototype.dispose = function () {
  92309. window.removeEventListener('resize', this.resize);
  92310. if (this.sceneOptimizer) {
  92311. this.sceneOptimizer.stop();
  92312. this.sceneOptimizer.dispose();
  92313. }
  92314. if (this.scene.activeCamera) {
  92315. this.scene.activeCamera.detachControl(this.canvas);
  92316. }
  92317. this.scene.dispose();
  92318. this.engine.dispose();
  92319. this.templateManager.dispose();
  92320. };
  92321. AbstractViewer.prototype.onTemplatesLoaded = function () {
  92322. return Promise.resolve(this);
  92323. };
  92324. AbstractViewer.prototype._onTemplateLoaded = function () {
  92325. var _this = this;
  92326. return this.onTemplatesLoaded().then(function () {
  92327. var autoLoadModel = !!_this.configuration.model;
  92328. return _this.initEngine().then(function (engine) {
  92329. return _this.onEngineInitObservable.notifyObserversWithPromise(engine);
  92330. }).then(function () {
  92331. if (autoLoadModel) {
  92332. return _this.loadModel().then(function () { return _this.scene; });
  92333. }
  92334. else {
  92335. return _this.scene || _this.initScene();
  92336. }
  92337. }).then(function (scene) {
  92338. return _this.onSceneInitObservable.notifyObserversWithPromise(scene);
  92339. }).then(function () {
  92340. return _this.onInitDoneObservable.notifyObserversWithPromise(_this);
  92341. });
  92342. });
  92343. };
  92344. AbstractViewer.prototype.initEngine = function () {
  92345. this.injectCustomShaders();
  92346. var canvasElement = this.templateManager.getCanvas();
  92347. if (!canvasElement) {
  92348. return Promise.reject('Canvas element not found!');
  92349. }
  92350. var config = this.configuration.engine || {};
  92351. this.engine = new babylonjs_1.Engine(canvasElement, !!config.antialiasing, config.engineOptions);
  92352. babylonjs_1.Database.IDBStorageEnabled = false;
  92353. if (!config.disableResize) {
  92354. window.addEventListener('resize', this.resize);
  92355. }
  92356. this.engine.runRenderLoop(this.render);
  92357. if (this.configuration.engine && this.configuration.engine.adaptiveQuality) {
  92358. var scale = Math.max(0.5, 1 / (window.devicePixelRatio || 2));
  92359. this.engine.setHardwareScalingLevel(scale);
  92360. }
  92361. this.handleHardwareLimitations();
  92362. return Promise.resolve(this.engine);
  92363. };
  92364. AbstractViewer.prototype.initScene = function () {
  92365. if (this.scene) {
  92366. this.scene.dispose();
  92367. }
  92368. this.scene = new babylonjs_1.Scene(this.engine);
  92369. this.scene.createDefaultLight(true);
  92370. if (this.configuration.scene) {
  92371. this.configureScene(this.configuration.scene);
  92372. if (this.configuration.optimizer) {
  92373. this.configureOptimizer(this.configuration.optimizer);
  92374. }
  92375. }
  92376. return Promise.resolve(this.scene);
  92377. };
  92378. AbstractViewer.prototype.loadModel = function (modelConfig, clearScene) {
  92379. var _this = this;
  92380. if (modelConfig === void 0) { modelConfig = this.configuration.model; }
  92381. if (clearScene === void 0) { clearScene = true; }
  92382. var modelUrl = (typeof modelConfig === 'string') ? modelConfig : modelConfig.url;
  92383. if (!modelUrl) {
  92384. return Promise.reject("no model configuration found");
  92385. }
  92386. if (this.isLoading) {
  92387. return Promise.reject("sanother model is curently being loaded.");
  92388. }
  92389. this.isLoading = true;
  92390. if ((typeof modelConfig === 'string')) {
  92391. if (this.configuration.model && typeof this.configuration.model === 'object') {
  92392. this.configuration.model.url = modelConfig;
  92393. }
  92394. }
  92395. else {
  92396. if (this.configuration.model) {
  92397. deepmerge(this.configuration.model, modelConfig);
  92398. }
  92399. else {
  92400. this.configuration.model = modelConfig;
  92401. }
  92402. }
  92403. return Promise.resolve(this.scene).then(function (scene) {
  92404. if (!scene)
  92405. return _this.initScene();
  92406. if (clearScene) {
  92407. _this.models.forEach(function (m) { return m.dispose(); });
  92408. _this.models.length = 0;
  92409. }
  92410. return scene;
  92411. }).then(function () {
  92412. return new Promise(function (resolve, reject) {
  92413. var model = new viewerModel_1.ViewerModel(_this.configuration.model, _this.scene);
  92414. _this.models.push(model);
  92415. _this.lastUsedLoader = model.loader;
  92416. model.onLoadedObservable.add(function (model) {
  92417. resolve(model);
  92418. });
  92419. model.onLoadErrorObservable.add(function (errorObject) {
  92420. _this.onModelLoadErrorObservable.notifyObserversWithPromise(errorObject).then(function () {
  92421. reject(errorObject.exception);
  92422. });
  92423. });
  92424. model.onLoadProgressObservable.add(function (progressEvent) {
  92425. return _this.onModelLoadProgressObservable.notifyObserversWithPromise(progressEvent);
  92426. });
  92427. _this.onLoaderInitObservable.notifyObserversWithPromise(_this.lastUsedLoader);
  92428. });
  92429. }).then(function (model) {
  92430. return _this.onModelLoadedObservable.notifyObserversWithPromise(model)
  92431. .then(function () {
  92432. _this.configureModel(_this.configuration.model || modelConfig, model);
  92433. _this.configureLights(_this.configuration.lights);
  92434. if (_this.configuration.camera) {
  92435. _this.configureCamera(_this.configuration.camera, model);
  92436. }
  92437. return _this.initEnvironment(model);
  92438. }).then(function () {
  92439. _this.isLoading = false;
  92440. return model;
  92441. });
  92442. });
  92443. };
  92444. AbstractViewer.prototype.initEnvironment = function (model) {
  92445. this.configureEnvironment(this.configuration.skybox, this.configuration.ground);
  92446. return Promise.resolve(this.scene);
  92447. };
  92448. AbstractViewer.prototype.handleHardwareLimitations = function () {
  92449. var maxVaryingRows = this.engine.getCaps().maxVaryingVectors;
  92450. var maxFragmentSamplers = this.engine.getCaps().maxTexturesImageUnits;
  92451. if ((maxVaryingRows < 8) || (maxFragmentSamplers < 8)) {
  92452. this.maxShadows = 0;
  92453. }
  92454. else {
  92455. this.maxShadows = 3;
  92456. }
  92457. var caps = this.engine.getCaps();
  92458. var linearHalfFloatTargets = caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering;
  92459. var linearFloatTargets = caps.textureFloatRender && caps.textureFloatLinearFiltering;
  92460. this._hdrSupport = !!(linearFloatTargets || linearHalfFloatTargets);
  92461. if (linearHalfFloatTargets) {
  92462. this.defaultHighpTextureType = babylonjs_1.Engine.TEXTURETYPE_HALF_FLOAT;
  92463. this.shadowGeneratorBias = 0.002;
  92464. }
  92465. else if (linearFloatTargets) {
  92466. this.defaultHighpTextureType = babylonjs_1.Engine.TEXTURETYPE_FLOAT;
  92467. this.shadowGeneratorBias = 0.001;
  92468. }
  92469. else {
  92470. this.defaultHighpTextureType = babylonjs_1.Engine.TEXTURETYPE_UNSIGNED_INT;
  92471. this.shadowGeneratorBias = 0.001;
  92472. }
  92473. this.defaultPipelineTextureType = this._hdrSupport ? this.defaultHighpTextureType : babylonjs_1.Engine.TEXTURETYPE_UNSIGNED_INT;
  92474. };
  92475. AbstractViewer.prototype.injectCustomShaders = function () {
  92476. var customShaders = this.configuration.customShaders;
  92477. if (!customShaders) {
  92478. return;
  92479. }
  92480. if (customShaders.shaders) {
  92481. Object.keys(customShaders.shaders).forEach(function (key) {
  92482. babylonjs_1.Effect.ShadersStore[key] = customShaders.shaders[key];
  92483. });
  92484. }
  92485. if (customShaders.includes) {
  92486. Object.keys(customShaders.includes).forEach(function (key) {
  92487. babylonjs_1.Effect.IncludesShadersStore[key] = customShaders.includes[key];
  92488. });
  92489. }
  92490. };
  92491. AbstractViewer.prototype.extendClassWithConfig = function (object, config) {
  92492. var _this = this;
  92493. if (!config)
  92494. return;
  92495. Object.keys(config).forEach(function (key) {
  92496. if (key in object && typeof object[key] !== 'function') {
  92497. if (typeof object[key] === 'object') {
  92498. _this.extendClassWithConfig(object[key], config[key]);
  92499. }
  92500. else {
  92501. if (config[key] !== undefined) {
  92502. object[key] = config[key];
  92503. }
  92504. }
  92505. }
  92506. });
  92507. };
  92508. AbstractViewer.prototype.setCameraBehavior = function (behaviorConfig, payload) {
  92509. var behavior;
  92510. var type = (typeof behaviorConfig !== "object") ? behaviorConfig : behaviorConfig.type;
  92511. var config = (typeof behaviorConfig === "object") ? behaviorConfig : {};
  92512. switch (type) {
  92513. case 0:
  92514. this.camera.useAutoRotationBehavior = true;
  92515. behavior = this.camera.autoRotationBehavior;
  92516. break;
  92517. case 1:
  92518. this.camera.useBouncingBehavior = true;
  92519. behavior = this.camera.bouncingBehavior;
  92520. break;
  92521. case 2:
  92522. this.camera.useFramingBehavior = true;
  92523. behavior = this.camera.framingBehavior;
  92524. break;
  92525. default:
  92526. behavior = null;
  92527. break;
  92528. }
  92529. if (behavior) {
  92530. if (typeof behaviorConfig === "object") {
  92531. this.extendClassWithConfig(behavior, behaviorConfig);
  92532. }
  92533. }
  92534. switch (type) {
  92535. case 0:
  92536. break;
  92537. case 1:
  92538. break;
  92539. case 2:
  92540. if (config.zoomOnBoundingInfo) {
  92541. var meshes = payload;
  92542. var bounding = meshes[0].getHierarchyBoundingVectors();
  92543. behavior.zoomOnBoundingInfo(bounding.min, bounding.max);
  92544. }
  92545. break;
  92546. }
  92547. };
  92548. return AbstractViewer;
  92549. }());
  92550. exports.AbstractViewer = AbstractViewer;
  92551. /***/ }),
  92552. /* 6 */
  92553. /***/ (function(module, exports) {
  92554. module.exports = "<viewer></viewer> <loading-screen></loading-screen> <overlay></overlay>";
  92555. /***/ }),
  92556. /* 7 */
  92557. /***/ (function(module, exports) {
  92558. module.exports = "<style>loading-screen{position:absolute;left:0;z-index:100;opacity:1;pointer-events:none;display:flex;justify-content:center;align-items:center;-webkit-transition:opacity 2s ease;-moz-transition:opacity 2s ease;transition:opacity 2s ease}img.loading-image{-webkit-animation:spin 2s linear infinite;animation:spin 2s linear infinite}@-webkit-keyframes spin{0%{-webkit-transform:rotate(0)}100%{-webkit-transform:rotate(360deg)}}@keyframes spin{0%{transform:rotate(0)}100%{transform:rotate(360deg)}}</style> <img class=loading-image src={{loadingImage}}>";
  92559. /***/ }),
  92560. /* 8 */
  92561. /***/ (function(module, exports) {
  92562. module.exports = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAHgAAAB4CAYAAAA5ZDbSAAAStUlEQVR42uyaA7TrShiFn23btm3btm3btm3btm372LWd9+318nSRNk2mtz3trLXX5PbmZOafPT9nxmq1VmuKFggEZs1ms0uVSqUj8vn8Q/SP5nK5lRpMjFYLh8NTZTKZhSBxi2KxeDlEPgh+BQVrhKbfwDNgZf45QZ2J0mrxeHxGtHJRCDoUQm+FpLd4joKc5aKJaDbDNzxuZT3yyLg1FqPVWPip0un0PBCxMUScD+6wtTJr+dz49hdsmh14nMiAKK0WiUSmgbjFC4XCYSz2VeB9/p2wyaxJK9EY93set+dxwhYr1QU9U7B4s4CNIfMM+pvAzyBm1VFjPl+D3cDELdacyVy4kMsdLBMrX0kf4beM1QCt9Ff7hY14nGRpWiIHBgYmU+BDwLMRi3EMJN4KpJUBa5g05OlHthORc4amIJXgZ30EPtXWyiHITFtN0JBziDz6DB6nHtYEI+i04BZQtJqwIfcAOBXM0hCEdXR0TM1k5ydV2Iv+CLTyeXbqgWeeeeY4DmnMOGjxTrw/aDVpkxtirW7Bos09xkns6+ublAlNA3Gr4S+3JCe4ksk9YOeWsdH4nkcTicTMZfLVuXjvrQYmKS54/EZaRReqaQvzz7FrZUYXBocz8BV2tWcQpEDR5eR7mPjGTmP98ssvEyra5N1CnZNZBL+Dp9mUF7A2a0W7u6dlE8/E82Ve0zVlCHz3HhFtnGAmfJWPC5Nm4pfSO6YLWIdVee/bOiFTiz1A/zL9xSpJqjLmpGHJZHJW9sDlvB/yul7gHlze4sY0Wr7UQLrwierA5fJf7eISrcaE9jHuh/TXsLk3j0aj81dbepRbUkXND40Gz7Hx1/SdaIRcz9BCxjDHh/A4nlMAxvjbKa0wZGaDKmeCO5nLAQoQOzs7fa86pVKpOfj2lSDsdc60N5Reat380uD5DfuyZ5KBwGzOc0jNiWCvet1QfONH+ushcz/M6AoqIUojapgWzgauBTEfiP6QzS+ix/E0qW6CB9MFCL7/G5Pd1DGd+uyz8SHmKB0eVPC9KAvwA3iK56Py6fTasVhseoMnVuMrs6h0seWelFnI9PqgIG+DTT2dSSsFsgw3+1z1ZpUsyyzOMrz7+QgH77+CB9gAp/HTWqFQaEqZMMOp4hKMd7hN1DcgxfMzLiLfsZFlMf7mScngA9Gfqp7w3XffuSe6WCi8Y9WufUYwsUKZY0EVVA5FoB3wR3MZNquTg3mxMNvSXw0+Bn1OrgBcid+ds9IxkHc51ljWJuNDAPsb67I/j5O5EfKaGkeyaSZ5hEktdEhxZrGs3GqMfxKL9aYCPJCtYqET4BIep6zQzI9N1L20rIA02geiO5HhYKunZ5JKdtgpNThSCzGpt+2z3YN0N8rkOaoW1K7Iicy9Gfs2HeuBrM+ytWuh3WiULvQxn2d90uh2OmUIkzpp8MZ+ayj4lcFvl6ZiznRxbRKTEe0j3JdizPkYb3fGvUim1n1FzptG4XP3rjQQ03tgWeW/oFBlPv8s8h6tG6GO1tBOKYoeKkFt4HmdhbI7V+F7Rk9P2traJlKRoZTP6x7WOeAl5tFZJyXOt3Xm/eabb47nwkWuCl4YHQf8nheh4BkgQpfWGrjxwdOAlEsNvR/sh6ldsJbXShlrXDbSyfV8tmznse/SL+ZCrnGUSvJ3X/6toUAaeowIVbXNa1rQ78IcfaCc1s+bkWj+ijKvCvjoj6Sf0Mm/5jOZbXinrc4PLdJQfbdSKzeuxkjFTSdJbs43qw2QtFNtX7mrTmr+c1+5OMIYz5VLRfj/2XnvlQa4ypMBCi6nMW7hwmFdI553VDXpB1wQHKyEYL0DZrHvLJ8LXnbjK2WmdCb9iMOF88+cK2D1d8MD96Kqm5+ZAlgHKBZ5Q8rHml3i6VRJGlfJDUI7Oo/4UAG7tdx4mPhlHSpy9Ub0oA4/qvGryrsVlOmuG/37IDniiZy4HOkPC9nsTm4miXlcrZIJ4X82gaA/2zvneNmdHoz/bNu2bdu2bdu2bdu2bdu2fbz3zfe9+eOizelMs93uns7n08uz0+48nUzwJPnFyQO2QAZi/IXNwgGTdXlTgFrfMnH4P9mRS6m18GgWFio/7xFVWiJAS59aHu5Tj7MMBQyxbIktFo1d0kS86mmMtZsmNGYOlknB6wkCTA8mWS5EtPz888+cxXc6vfkPmAqYcsAMxbFUmvZX77wzlhF82SqU4Pf++++PmjeqhBg4OS1QYCldAs4NTgvzrTzDWuxY435wwPYtMweMNXdk3NjzYd8GTHRWyhyE1xboxUzaS47JLieHwhmcvb0oYIvJz35Z0nP4o14YNxcEznenGVXKCTAi5VYCC3CnrXOS//dKJiP4j7entxCk/Bzet1rJAL463D9h42K9LSdmnUhE3yuWSNFA/f6WQsROh9HoyAHbRz1glptzh/JkKdqAqFfrjZD5RFrtZ+3glcNlvX1mCIA3GvYegQ54TM85Ltg9YsNNZu0KAXmz8uzgrtMss0/W7z8v64YdvKQHwElaL1xiK4dJFv2RvPYrURe513dynfYtgXD/8Kj7YFM5BoG6xEs2kyXvx8k6IYFzWcRxEjIKt0/5eezgqSzxqYVRahFsymc06jKHIaJLCLC94zr//XcBXno3F3I/IbOxYHkMalnk2SzfMp4t68yBSmP5lTVH6HUB9VxscXljxzGwLDXA7DjJJZ7F6znVmTRsb1/+qTwA828Z+FjbWvYrGQcDShICFPLw10C9wSHDbrchbBqArR3HZtk2cL779aOmAnJ/1gnZjSbAtv16ouWDVc7WHvIzM1iaeCsDjIYduIOvyPLl9wh4wF0Tio1NEVCt5lZxYY5arzpZcovV5Zq8rAALlfZdi9pDFC3whdktyw7ekLWPnZBzNDDm+xxi12FXjkbylizKkfLnxwZgTy5R4h18fy9YvB8yn4j0DTMFkUkBzaLN4hjxyJTAr2x5ogwxPp0sws4Q/nCypzxzmQG+1yHjxNCJjBik/PDFGWT+fV6pMMpEWNPSsDUBey2lv3xoBhHKDzAb5AS7XEaQRdPz66+/Tpp5dzwnpK/u7p7HI0QMouWDyDf6scQXpn+Nj5fCmZSl38G7eWV94meIKB3YDwf9s4HsSgC+JeYLy+e+I7nK1iZbB2Ap/radEQGbP3Dt3o4uwZvmK64JFQd6pxcgmgg+Qh8BmO87vaFg7Ro41zl5CppN2dNT+96w43wA1vn6EMDTegX6SYTLaVeS61r7KQu7Um52pifAHW1tJ7cawCiIkn4ygbGDbwqcb+nsaBrnAmJ0EHblwoaLzQNg5tu6BQH+2DERoSbYLBiUfZDmK2Yi3j7/BTRF9Ip9CWAUTfn/DwLm+o30o6BkNHKG0/KP2jq6t+Kl0cmXcwT4b1HaxuoLAFPawTEODCtmhKD0TBK7RI0/PM3b1dnZvSM7OSFNggdcIfaLy73nbH2AbaqOUpjbA+Z6MCoZTQt0pXqXNCfojATTas5IdgZn+mJ9ZAefYYRLlwt8We4MhBfwOm8bIBd4rbSzuo00CUvEOAAiZZKWazWAKfriFc4kyz9XicP+jS+6Vg34rCvAYoot0GoAW1Qd6EeBO3iXGJNop0GZGAT4iwPY4Iq1AMBSI3Mhr0C/YDVvzA6eNYngJl4tRLI5cF/KGfO9IyBjtRLAOIgsogME/ZD5BJNpggHmQykP959c0+WqGGAHrTdtOYDDqTofhSTJx1CaACiVmaEPMJU3wPo2Ht/qAFvsR0zQkNojYFGXGpY8BEEIb4ApJ9jqAFtUHanDOXkIN7ynq+uaaIDxtvTyJn6QlqcrovYOLwcA+a5yr7+bGWCtoUU9MbrQLO4U6AeDs/Ls4LMy3OBjkrttdmY+gHGZQnZvNoAV1E9kjc6jQFyGemI4OZYOtIHXjQZYPnxQxrfoLbp9ebQKAGBb5JcZYC3P39PzBlWFtIDZUHVusbBEIQRxrVc1Ql8EWIn8b9IEC8J+niq6pO6EBGfylGTCVFoy8IvejPqfI4aL0X53MwDM4mrVm508a1ozp3e9svBsQ/umt5LhB98oCuD29rfKCrD65R+mRieZE57Vc2uSXgvHO6CuGEfjO5izeQCGm/tv6EJop7SZPQPhnZ0d9xcNcK3/+EELr64FqJ5FVXEmAaoIeM3E8DO37OGgvVJ63hFgRP5ZRQGsvQavFY12JepcOye+TUoNbfn9BUDNGZE6x+OBHi+eymJrl94Aaz3mD4hty6Kt4pkQp1ki0xLxYS0B1ZU473DoH9mqAJMNoHlYmDPh/ly7itDMslP3o/J8LlDt9N1V/FvftQDA+NFlvnm1iq3LoPEmJSQE1MPpy1iTUTyvOmLwlmTl+cr4yuGhO+67777R/AH2HzgxKFkhgB4TkAzn1joQgmJhre+0edW4ohG+m/fhP/3008kSCAg7lwFgCIk07+LokuvdRhRW0w42l7n1GeLNzLLznn766THFszKjgPyTt+gRE2XDRgGMKEf8yqIeX8RONepmP6/tDsb27g72cpaHkMJdU+nPL8Bb5gkw/1YkwLhdaXujlerfb9BORbt/n3omBmsj/yDCgRcnABjs1o1565oJYJwPKn5P1CZa3Q3s+X8Jz2Jo975Dazz2hACjBn1XmQHWvhLzyoIeS3y7iJ1q+LZvo8oBzTfrCqZBJTkzBBit93F22QBWX/lSBN8bulO1kRat6SS3aLzi0LSTwV8KAYa+wFqQNPMQhWr9pNL2eQCmtyANl2lxC1GtwU2z3tR48cwR+tDwHX//PXNAnDmcbSkPl9iSXTTotQ0x+EwA8W6HQed4/fXXJ470iZ+tjSl/LkT82r0GLxSrZIGYeDFVeeXIO1S1+Hvr3cp8Wbk6E2K5OxsPODH+3lgfqzg/EKse3VuKtldvr0mTENI7I9Z5XMS3xp07jIp2/ucxiWehzm91EX4bDnBxncod7dXdJHth7BgRLEfJalQBxFsVsj7u7VxpsBF4Y0Q8u//vpgXYtldPoK1cjM0NKY+MQ/oRZwgTLlOUZj0KpkXom6U1JNuaHWC1Vy+CXBdjr2rA/2BAlaun0CBDgEiZEgUiVHRQQcDol7tXWQFWe/VW+eMaFKAJPdrQRQTUrRDjkY2hvyq8NT5Bcs0+vCThv4c0amKekqTZtv377/Up93m3gabNk/Qb/O6778aNad9L02iZ4344bjnTXj50BS9gRx4u5XHvShFFU6SxHeQztw36JVLm4R6PNMBePepvsTtjzlWZY0FKAnva3dQQbQjAGN7yhu+SIloBcYyUlnej0kUzC5kMznRR9iolo2JEIbxo+iLXy0OGS3WIRo201Ayp1PIeIKa0vQO48eXBv2kQwCza/+3V7nh7dXL57E4yhw/nymZ5LjZE2YZU67lHF/LWNBebiMFZ8TYVBbDaq8/J7xvHdOZGwULRkjnuqHdzavQbuQ987JU0F7iBwwBGz7VT08jaND7my9QLYOxVje0eGGOv0otJRPeisCkwkQoIRKADHGk/a4kAZtRkiEZ5jGEbbk32QIoWfUZsa3WaZckf5yD4EXGuTq89nb50az5t94G6VV6khQs3h7zSUMnAs6q7S87xRoiiBH/2UYF+YMjra8ifR40IjeLc30vmeAlxXoAn7AV6L9r9K0oOcELVnhUD51k5w1mForNtjB8YjV4WeWOZ4yG52gryhF0K30uPraYciNZT076gXFPnSWfVanxvYK/WpElHxMs3IpXlWOgi4sQ8L1IBp4laFc0/iO/WZKR84c9EJE8WCrDaqxfI2z976FlFzhWfG4B7VSvIvj5ZpNaMTbpbbda/fLknDDv09Sz2p9JsbqPYKRptRCLd1Dhj5Pe3CgL1P7ke1V5UfL/WHXiy5HrFWAyAG763EGXwfYVmhANDbd6Ogsokfaahw6k0h7hvDNEQ58KZYcQ5r7HFbbBz/wbO+YJZkavri9o3hyzAyobZwULtmyPgMR9lhWx71d0Z8Q7FauTlnVB3azWIGxux4G4KoWYNcGiX0n1ELr7CZwssRXgpzAp1vVYjodv39cYCdspILRaGjUsf/gHJaAWdrW+QG0Rv/QrFbPHSBywngFzzDeiEkB2zovybktEch90C9wcI/zQjSelhUQ3DJTkpdrCxwD+IJroCvCdPXnMAg2PLfDU6qoF/eX6TZVl8Lclzax0dsyrVqBpO4pqAQHcDecz3EvxQwkI16kGkp9m0v2ljxoU/UGfElBUCxYCMK/HKejMj5LpRriWVx1yNIgfmhyz+83U4WzFvDsAZUa1yYwfcLAh4P3kwI+S6RMybBcrHjKg8XQshTiOZESR+bS+prONUK1niITtvezTcAGYEid2zasSpGUY1ekSztpgRcpHpsK5co1er1YRDu6DelsCMOL5d6DmVo78FBgRzcRy+pgTzFeiqVq1Ki43KZo0b/wP23paVqC/D3gAAAABJRU5ErkJggg=="
  92563. /***/ }),
  92564. /* 9 */
  92565. /***/ (function(module, exports) {
  92566. module.exports = "<style>viewer{position:relative;overflow:hidden;flex:1;z-index:1;justify-content:center;align-items:center;width:100%;height:100%}.babylonjs-canvas{flex:1;width:100%;height:100%;touch-action:none}</style> <canvas class=babylonjs-canvas id={{canvasId}}> </canvas> <nav-bar></nav-bar>";
  92567. /***/ }),
  92568. /* 10 */
  92569. /***/ (function(module, exports) {
  92570. module.exports = "<style>overlay{position:absolute;z-index:99;opacity:0;display:flex;justify-content:center;align-items:center;-webkit-transition:opacity 1s ease;-moz-transition:opacity 1s ease;transition:opacity 1s ease}.overlay-item{width:100%;height:100%;display:none;align-items:center;justify-content:center;background-color:rgba(121,121,121,.3)}error.overlay-item{background-color:rgba(121,121,121,1)}div#close-button{position:absolute;top:10px;right:10px;width:30px;height:30px;cursor:pointer}div#close-button img{width:100%}</style> <div id=close-button> <img src={{closeImage}} alt={{closeText}}> </div> <help class=overlay-item></help> <error class=overlay-item></error> <share class=overlay-item></share>";
  92571. /***/ }),
  92572. /* 11 */
  92573. /***/ (function(module, exports) {
  92574. module.exports = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAQAAAD9CzEMAAAAt0lEQVR42u2WAQbDQBBFQ9IbRtDcrrqK3LBbXrEH6OuHEPMBjPd2xHyZKtdNpcLMg11Pr7y4/YdvwIdd4jtw4BU0Rjrbz9mNzkjzgpU3wNhCvH5M3i1fKzzeK3K8V+R4r8jxTpHjlULhc0WOd8fU6e4I8y3y13tFjHel4GswwAvFSR/ZN6Zv2gjvmzbGhwqPzxUenys83is8Pld4vFac/9sy8/SVNrbgYJl8WGhsvkpoA1+pVK6ZLyLNXm2txsT5AAAAAElFTkSuQmCC"
  92575. /***/ }),
  92576. /* 12 */
  92577. /***/ (function(module, exports) {
  92578. module.exports = "Error loading the model";
  92579. /***/ }),
  92580. /* 13 */
  92581. /***/ (function(module, exports, __webpack_require__) {
  92582. (function (global, factory) {
  92583. true ? module.exports = factory() :
  92584. typeof define === 'function' && define.amd ? define(factory) :
  92585. (global.deepmerge = factory());
  92586. }(this, (function () { 'use strict';
  92587. var isMergeableObject = function isMergeableObject(value) {
  92588. return isNonNullObject(value)
  92589. && !isSpecial(value)
  92590. };
  92591. function isNonNullObject(value) {
  92592. return !!value && typeof value === 'object'
  92593. }
  92594. function isSpecial(value) {
  92595. var stringValue = Object.prototype.toString.call(value);
  92596. return stringValue === '[object RegExp]'
  92597. || stringValue === '[object Date]'
  92598. || isReactElement(value)
  92599. }
  92600. // see https://github.com/facebook/react/blob/b5ac963fb791d1298e7f396236383bc955f916c1/src/isomorphic/classic/element/ReactElement.js#L21-L25
  92601. var canUseSymbol = typeof Symbol === 'function' && Symbol.for;
  92602. var REACT_ELEMENT_TYPE = canUseSymbol ? Symbol.for('react.element') : 0xeac7;
  92603. function isReactElement(value) {
  92604. return value.$$typeof === REACT_ELEMENT_TYPE
  92605. }
  92606. function emptyTarget(val) {
  92607. return Array.isArray(val) ? [] : {}
  92608. }
  92609. function cloneUnlessOtherwiseSpecified(value, optionsArgument) {
  92610. var clone = !optionsArgument || optionsArgument.clone !== false;
  92611. return (clone && isMergeableObject(value))
  92612. ? deepmerge(emptyTarget(value), value, optionsArgument)
  92613. : value
  92614. }
  92615. function defaultArrayMerge(target, source, optionsArgument) {
  92616. return target.concat(source).map(function(element) {
  92617. return cloneUnlessOtherwiseSpecified(element, optionsArgument)
  92618. })
  92619. }
  92620. function mergeObject(target, source, optionsArgument) {
  92621. var destination = {};
  92622. if (isMergeableObject(target)) {
  92623. Object.keys(target).forEach(function(key) {
  92624. destination[key] = cloneUnlessOtherwiseSpecified(target[key], optionsArgument);
  92625. });
  92626. }
  92627. Object.keys(source).forEach(function(key) {
  92628. if (!isMergeableObject(source[key]) || !target[key]) {
  92629. destination[key] = cloneUnlessOtherwiseSpecified(source[key], optionsArgument);
  92630. } else {
  92631. destination[key] = deepmerge(target[key], source[key], optionsArgument);
  92632. }
  92633. });
  92634. return destination
  92635. }
  92636. function deepmerge(target, source, optionsArgument) {
  92637. var sourceIsArray = Array.isArray(source);
  92638. var targetIsArray = Array.isArray(target);
  92639. var options = optionsArgument || { arrayMerge: defaultArrayMerge };
  92640. var sourceAndTargetTypesMatch = sourceIsArray === targetIsArray;
  92641. if (!sourceAndTargetTypesMatch) {
  92642. return cloneUnlessOtherwiseSpecified(source, optionsArgument)
  92643. } else if (sourceIsArray) {
  92644. var arrayMerge = options.arrayMerge || defaultArrayMerge;
  92645. return arrayMerge(target, source, optionsArgument)
  92646. } else {
  92647. return mergeObject(target, source, optionsArgument)
  92648. }
  92649. }
  92650. deepmerge.all = function deepmergeAll(array, optionsArgument) {
  92651. if (!Array.isArray(array)) {
  92652. throw new Error('first argument should be an array')
  92653. }
  92654. return array.reduce(function(prev, next) {
  92655. return deepmerge(prev, next, optionsArgument)
  92656. }, {})
  92657. };
  92658. var deepmerge_1 = deepmerge;
  92659. return deepmerge_1;
  92660. })));
  92661. /***/ }),
  92662. /* 14 */
  92663. /***/ (function(module, exports, __webpack_require__) {
  92664. module.exports = __webpack_require__(15);
  92665. /***/ }),
  92666. /* 15 */
  92667. /***/ (function(module, exports, __webpack_require__) {
  92668. "use strict";
  92669. Object.defineProperty(exports, "__esModule", { value: true });
  92670. var mappers_1 = __webpack_require__(1);
  92671. exports.mapperManager = mappers_1.mapperManager;
  92672. var viewerManager_1 = __webpack_require__(3);
  92673. exports.viewerManager = viewerManager_1.viewerManager;
  92674. var defaultViewer_1 = __webpack_require__(4);
  92675. exports.DefaultViewer = defaultViewer_1.DefaultViewer;
  92676. var viewer_1 = __webpack_require__(5);
  92677. exports.AbstractViewer = viewer_1.AbstractViewer;
  92678. var babylonjs_1 = __webpack_require__(0);
  92679. __webpack_require__(32);
  92680. __webpack_require__(33);
  92681. var initializer_1 = __webpack_require__(34);
  92682. exports.InitTags = initializer_1.InitTags;
  92683. babylonjs_1.PromisePolyfill.Apply();
  92684. exports.disableInit = false;
  92685. document.addEventListener("DOMContentLoaded", function (event) {
  92686. if (exports.disableInit)
  92687. return;
  92688. initializer_1.InitTags();
  92689. });
  92690. /***/ }),
  92691. /* 16 */
  92692. /***/ (function(module, exports) {
  92693. var g;
  92694. // This works in non-strict mode
  92695. g = (function() {
  92696. return this;
  92697. })();
  92698. try {
  92699. // This works if eval is allowed (see CSP)
  92700. g = g || Function("return this")() || (1,eval)("this");
  92701. } catch(e) {
  92702. // This works if the window reference is available
  92703. if(typeof window === "object")
  92704. g = window;
  92705. }
  92706. // g can still be undefined, but nothing to do about it...
  92707. // We return undefined, instead of nothing here, so it's
  92708. // easier to handle this case. if(!global) { ...}
  92709. module.exports = g;
  92710. /***/ }),
  92711. /* 17 */
  92712. /***/ (function(module, exports) {
  92713. module.exports = cannon;
  92714. /***/ }),
  92715. /* 18 */
  92716. /***/ (function(module, exports, __webpack_require__) {
  92717. /**
  92718. * from OimoPhysics DEV 1.1.0a AS3
  92719. * @author Saharan / http://el-ement.com/
  92720. *
  92721. * to Oimo.js 2015 JAVASCRIPT
  92722. * @author LoTh / http://lo-th.github.io/labs/
  92723. */
  92724. var OIMO = {
  92725. REVISION: "1.2",
  92726. // Global identification of next shape.
  92727. // This will be incremented every time a shape is created.
  92728. nextID: 0,
  92729. proxyID: 0,
  92730. // BroadPhase
  92731. BR_NULL: 0,
  92732. BR_BRUTE_FORCE: 1,
  92733. BR_SWEEP_AND_PRUNE: 2,
  92734. BR_BOUNDING_VOLUME_TREE: 3,
  92735. // body type
  92736. BODY_NULL: 0,
  92737. BODY_DYNAMIC: 1,
  92738. BODY_STATIC: 2,
  92739. // shape type
  92740. SHAPE_NULL: 0,
  92741. SHAPE_SPHERE: 1,
  92742. SHAPE_BOX: 2,
  92743. SHAPE_CYLINDER: 3,
  92744. SHAPE_TETRA: 4,
  92745. // joint type
  92746. JOINT_NULL: 0,
  92747. JOINT_DISTANCE: 1,
  92748. JOINT_BALL_AND_SOCKET: 2,
  92749. JOINT_HINGE: 3,
  92750. JOINT_WHEEL: 4,
  92751. JOINT_SLIDER: 5,
  92752. JOINT_PRISMATIC: 6,
  92753. // this world scale defaut is 0.1 to 10 meters max for dynamique body
  92754. // scale all by 100 so object is between 10 to 10000 three unit.
  92755. WORLD_SCALE: 100,
  92756. INV_SCALE: 0.01,
  92757. // AABB aproximation
  92758. AABB_PROX: 0.005,
  92759. // Math function
  92760. sqrt: Math.sqrt,
  92761. abs: Math.abs,
  92762. floor: Math.floor,
  92763. cos: Math.cos,
  92764. sin: Math.sin,
  92765. acos: Math.acos,
  92766. asin: Math.asin,
  92767. atan2: Math.atan2,
  92768. round: Math.round,
  92769. pow: Math.pow,
  92770. max: Math.max,
  92771. min: Math.min,
  92772. random: Math.random,
  92773. lerp: function (a, b, percent) { return a + (b - a) * percent; },
  92774. rand: function (a, b) { return OIMO.lerp(a, b, OIMO.random()); },
  92775. randInt: function (a, b, n) { return OIMO.lerp(a, b, OIMO.random()).toFixed(n || 0) * 1; },
  92776. int: function (x) { return ~~x; },
  92777. fix: function (x, n) { return x.toFixed(n || 3, 10); },
  92778. clamp: function (value, min, max) { return OIMO.max(min, OIMO.min(max, value)); },
  92779. degtorad: 0.0174532925199432957,
  92780. radtodeg: 57.295779513082320876,
  92781. PI: 3.141592653589793,
  92782. TwoPI: 6.283185307179586,
  92783. PI90: 1.570796326794896,
  92784. PI270: 4.712388980384689,
  92785. CustomError: null,
  92786. Error: function (Class, Msg) {
  92787. if (OIMO.CustomError == null) console.error(Class, Msg);
  92788. else OIMO.CustomError.innerHTML += Class + " - " + Msg + '<br>';
  92789. }
  92790. };
  92791. var OIMO_ARRAY_TYPE;
  92792. if (!OIMO_ARRAY_TYPE) { OIMO_ARRAY_TYPE = typeof Float32Array !== 'undefined' ? Float32Array : Array; }
  92793. try {
  92794. (function (w) {
  92795. var perfNow;
  92796. var perfNowNames = ['now', 'webkitNow', 'msNow', 'mozNow'];
  92797. if (!!w['performance']) for (var i = 0; i < perfNowNames.length; ++i) {
  92798. var n = perfNowNames[i];
  92799. if (!!w['performance'][n]) {
  92800. perfNow = function () { return w['performance'][n]() };
  92801. break;
  92802. }
  92803. }
  92804. if (!perfNow) perfNow = Date.now;
  92805. //w.perfNow = perfNow;
  92806. OIMO.now = perfNow;
  92807. })(window);
  92808. } catch (e) { OIMO.now = function () { return 0; }; }
  92809. /**
  92810. * The class of physical computing world.
  92811. * You must be added to the world physical all computing objects
  92812. * @author saharan
  92813. * @author lo-th
  92814. */
  92815. OIMO.World = function (TimeStep, BroadPhaseType, Iterations, NoStat) {
  92816. // The time between each step
  92817. this.timeStep = TimeStep || 0.01666; // 1/60;
  92818. // The number of iterations for constraint solvers.
  92819. this.numIterations = Iterations || 8;
  92820. // It is a wide-area collision judgment that is used in order to reduce as much as possible a detailed collision judgment.
  92821. switch (BroadPhaseType || 2) {
  92822. case 1: this.broadPhase = new OIMO.BruteForceBroadPhase(); break;
  92823. case 2: default: this.broadPhase = new OIMO.SAPBroadPhase(); break;
  92824. case 3: this.broadPhase = new OIMO.DBVTBroadPhase(); break;
  92825. }
  92826. // This is the detailed information of the performance.
  92827. this.performance = null;
  92828. this.isNoStat = NoStat || false;
  92829. if (!this.isNoStat) this.performance = new OIMO.Performance(this);
  92830. // Whether the constraints randomizer is enabled or not.
  92831. this.enableRandomizer = true;
  92832. // The rigid body list
  92833. this.rigidBodies = null;
  92834. // number of rigid body
  92835. this.numRigidBodies = 0;
  92836. // The contact list
  92837. this.contacts = null;
  92838. this.unusedContacts = null;
  92839. // The number of contact
  92840. this.numContacts = 0;
  92841. // The number of contact points
  92842. this.numContactPoints = 0;
  92843. // The joint list
  92844. this.joints = null;
  92845. // The number of joints.
  92846. this.numJoints = 0;
  92847. // The number of simulation islands.
  92848. this.numIslands = 0;
  92849. // The gravity in the world.
  92850. this.gravity = new OIMO.Vec3(0, -9.80665, 0);
  92851. var numShapeTypes = 5;//4;//3;
  92852. this.detectors = [];
  92853. this.detectors.length = numShapeTypes;
  92854. var i = numShapeTypes;
  92855. while (i--) {
  92856. this.detectors[i] = [];
  92857. this.detectors[i].length = numShapeTypes;
  92858. }
  92859. this.detectors[OIMO.SHAPE_SPHERE][OIMO.SHAPE_SPHERE] = new OIMO.SphereSphereCollisionDetector();
  92860. this.detectors[OIMO.SHAPE_SPHERE][OIMO.SHAPE_BOX] = new OIMO.SphereBoxCollisionDetector(false);
  92861. this.detectors[OIMO.SHAPE_BOX][OIMO.SHAPE_SPHERE] = new OIMO.SphereBoxCollisionDetector(true);
  92862. this.detectors[OIMO.SHAPE_BOX][OIMO.SHAPE_BOX] = new OIMO.BoxBoxCollisionDetector();
  92863. // CYLINDER add
  92864. this.detectors[OIMO.SHAPE_CYLINDER][OIMO.SHAPE_CYLINDER] = new OIMO.CylinderCylinderCollisionDetector();
  92865. this.detectors[OIMO.SHAPE_CYLINDER][OIMO.SHAPE_BOX] = new OIMO.BoxCylinderCollisionDetector(true);
  92866. this.detectors[OIMO.SHAPE_BOX][OIMO.SHAPE_CYLINDER] = new OIMO.BoxCylinderCollisionDetector(false);
  92867. this.detectors[OIMO.SHAPE_CYLINDER][OIMO.SHAPE_SPHERE] = new OIMO.SphereCylinderCollisionDetector(true);
  92868. this.detectors[OIMO.SHAPE_SPHERE][OIMO.SHAPE_CYLINDER] = new OIMO.SphereCylinderCollisionDetector(false);
  92869. // TETRA add
  92870. this.detectors[OIMO.SHAPE_TETRA][OIMO.SHAPE_TETRA] = new OIMO.TetraTetraCollisionDetector();
  92871. this.randX = 65535;
  92872. this.randA = 98765;
  92873. this.randB = 123456789;
  92874. //this.maxIslandRigidBodies = 64;
  92875. this.islandRigidBodies = [];
  92876. //this.islandRigidBodies.length = this.maxIslandRigidBodies;
  92877. this.islandStack = [];
  92878. //this.islandStack.length = this.maxIslandRigidBodies;
  92879. //this.maxIslandConstraints = 128;
  92880. this.islandConstraints = [];
  92881. //this.islandConstraints.length = this.maxIslandConstraints;
  92882. };
  92883. OIMO.World.prototype = {
  92884. constructor: OIMO.World,
  92885. /**
  92886. * Reset the randomizer and remove all rigid bodies, shapes, joints and any object from the world.
  92887. */
  92888. clear: function () {
  92889. this.randX = 65535;
  92890. while (this.joints !== null) {
  92891. this.removeJoint(this.joints);
  92892. }
  92893. while (this.contacts !== null) {
  92894. this.removeContact(this.contacts);
  92895. }
  92896. while (this.rigidBodies !== null) {
  92897. this.removeRigidBody(this.rigidBodies);
  92898. }
  92899. OIMO.nextID = 0;
  92900. OIMO.proxyID = 0;
  92901. },
  92902. /**
  92903. * I'll add a rigid body to the world.
  92904. * Rigid body that has been added will be the operands of each step.
  92905. * @param rigidBody Rigid body that you want to add
  92906. */
  92907. addRigidBody: function (rigidBody) {
  92908. if (rigidBody.parent) {
  92909. OIMO.Error("World", "It is not possible to be added to more than one world one of the rigid body");
  92910. }
  92911. rigidBody.parent = this;
  92912. rigidBody.awake();
  92913. for (var shape = rigidBody.shapes; shape !== null; shape = shape.next) {
  92914. this.addShape(shape);
  92915. }
  92916. if (this.rigidBodies !== null) (this.rigidBodies.prev = rigidBody).next = this.rigidBodies;
  92917. this.rigidBodies = rigidBody;
  92918. this.numRigidBodies++;
  92919. },
  92920. /**
  92921. * I will remove the rigid body from the world.
  92922. * Rigid body that has been deleted is excluded from the calculation on a step-by-step basis.
  92923. * @param rigidBody Rigid body to be removed
  92924. */
  92925. removeRigidBody: function (rigidBody) {
  92926. var remove = rigidBody;
  92927. if (remove.parent !== this) return;
  92928. remove.awake();
  92929. var js = remove.jointLink;
  92930. while (js != null) {
  92931. var joint = js.joint;
  92932. js = js.next;
  92933. this.removeJoint(joint);
  92934. }
  92935. for (var shape = rigidBody.shapes; shape !== null; shape = shape.next) {
  92936. this.removeShape(shape);
  92937. }
  92938. var prev = remove.prev;
  92939. var next = remove.next;
  92940. if (prev !== null) prev.next = next;
  92941. if (next !== null) next.prev = prev;
  92942. if (this.rigidBodies == remove) this.rigidBodies = next;
  92943. remove.prev = null;
  92944. remove.next = null;
  92945. remove.parent = null;
  92946. this.numRigidBodies--;
  92947. },
  92948. getByName: function (name) {
  92949. var result = null;
  92950. var body = this.rigidBodies;
  92951. while (body !== null) {
  92952. if (body.name !== " " && body.name === name) result = body;
  92953. body = body.next;
  92954. }
  92955. var joint = this.joints;
  92956. while (joint !== null) {
  92957. if (joint.name !== "" && joint.name === name) result = joint;
  92958. joint = joint.next;
  92959. }
  92960. return result;
  92961. },
  92962. /**
  92963. * I'll add a shape to the world..
  92964. * Add to the rigid world, and if you add a shape to a rigid body that has been added to the world,
  92965. * Shape will be added to the world automatically, please do not call from outside this method.
  92966. * @param shape Shape you want to add
  92967. */
  92968. addShape: function (shape) {
  92969. if (!shape.parent || !shape.parent.parent) {
  92970. OIMO.Error("World", "It is not possible to be added alone to shape world");
  92971. }
  92972. shape.proxy = this.broadPhase.createProxy(shape);
  92973. shape.updateProxy();
  92974. this.broadPhase.addProxy(shape.proxy);
  92975. },
  92976. /**
  92977. * I will remove the shape from the world.
  92978. * Add to the rigid world, and if you add a shape to a rigid body that has been added to the world,
  92979. * Shape will be added to the world automatically, please do not call from outside this method.
  92980. * @param shape Shape you want to delete
  92981. */
  92982. removeShape: function (shape) {
  92983. this.broadPhase.removeProxy(shape.proxy);
  92984. shape.proxy = null;
  92985. },
  92986. /**
  92987. * I'll add a joint to the world.
  92988. * Joint that has been added will be the operands of each step.
  92989. * @param shape Joint to be added
  92990. */
  92991. addJoint: function (joint) {
  92992. if (joint.parent) {
  92993. OIMO.Error("World", "It is not possible to be added to more than one world one of the joint");
  92994. }
  92995. if (this.joints != null) (this.joints.prev = joint).next = this.joints;
  92996. this.joints = joint;
  92997. joint.parent = this;
  92998. this.numJoints++;
  92999. joint.awake();
  93000. joint.attach();
  93001. },
  93002. /**
  93003. * I will remove the joint from the world.
  93004. * Joint that has been added will be the operands of each step.
  93005. * @param shape Joint to be deleted
  93006. */
  93007. removeJoint: function (joint) {
  93008. var remove = joint;
  93009. var prev = remove.prev;
  93010. var next = remove.next;
  93011. if (prev !== null) prev.next = next;
  93012. if (next !== null) next.prev = prev;
  93013. if (this.joints == remove) this.joints = next;
  93014. remove.prev = null;
  93015. remove.next = null;
  93016. this.numJoints--;
  93017. remove.awake();
  93018. remove.detach();
  93019. remove.parent = null;
  93020. },
  93021. worldscale: function (scale) {
  93022. OIMO.WORLD_SCALE = scale || 100;
  93023. OIMO.INV_SCALE = 1 / OIMO.WORLD_SCALE;
  93024. },
  93025. addContact: function (s1, s2) {
  93026. var newContact;
  93027. if (this.unusedContacts !== null) {
  93028. newContact = this.unusedContacts;
  93029. this.unusedContacts = this.unusedContacts.next;
  93030. } else {
  93031. newContact = new OIMO.Contact();
  93032. }
  93033. newContact.attach(s1, s2);
  93034. newContact.detector = this.detectors[s1.type][s2.type];
  93035. if (this.contacts) (this.contacts.prev = newContact).next = this.contacts;
  93036. this.contacts = newContact;
  93037. this.numContacts++;
  93038. },
  93039. removeContact: function (contact) {
  93040. var prev = contact.prev;
  93041. var next = contact.next;
  93042. if (next) next.prev = prev;
  93043. if (prev) prev.next = next;
  93044. if (this.contacts == contact) this.contacts = next;
  93045. contact.prev = null;
  93046. contact.next = null;
  93047. contact.detach();
  93048. contact.next = this.unusedContacts;
  93049. this.unusedContacts = contact;
  93050. this.numContacts--;
  93051. },
  93052. checkContact: function (name1, name2) {
  93053. var n1, n2;
  93054. var contact = this.contacts;
  93055. while (contact !== null) {
  93056. n1 = contact.body1.name || ' ';
  93057. n2 = contact.body2.name || ' ';
  93058. if ((n1 == name1 && n2 == name2) || (n2 == name1 && n1 == name2)) { if (contact.touching) return true; else return false; }
  93059. else contact = contact.next;
  93060. }
  93061. return false;
  93062. },
  93063. callSleep: function (body) {
  93064. if (!body.allowSleep) return false;
  93065. if (body.linearVelocity.lengthSq() > 0.04) return false;
  93066. if (body.angularVelocity.lengthSq() > 0.25) return false;
  93067. return true;
  93068. },
  93069. /**
  93070. * I will proceed only time step seconds time of World.
  93071. */
  93072. step: function () {
  93073. var time0, time1, time2, time3;
  93074. var stat = !this.isNoStat ? true : false;
  93075. if (stat) time0 = OIMO.now();
  93076. var body = this.rigidBodies;
  93077. while (body !== null) {
  93078. body.addedToIsland = false;
  93079. if (body.sleeping) {
  93080. if (
  93081. body.linearVelocity.testZero() ||
  93082. body.angularVelocity.testZero() ||
  93083. body.position.testDiff(body.sleepPosition) ||
  93084. body.orientation.testDiff(body.sleepOrientation)
  93085. ) body.awake(); // awake the body
  93086. }
  93087. body = body.next;
  93088. }
  93089. //------------------------------------------------------
  93090. // UPDATE CONTACT
  93091. //------------------------------------------------------
  93092. // broad phase
  93093. if (stat) time1 = OIMO.now();
  93094. this.broadPhase.detectPairs();
  93095. var pairs = this.broadPhase.pairs;
  93096. var i = this.broadPhase.numPairs;
  93097. //do{
  93098. while (i--) {
  93099. //for(var i=0, l=numPairs; i<l; i++){
  93100. var pair = pairs[i];
  93101. var s1;
  93102. var s2;
  93103. if (pair.shape1.id < pair.shape2.id) {
  93104. s1 = pair.shape1;
  93105. s2 = pair.shape2;
  93106. } else {
  93107. s1 = pair.shape2;
  93108. s2 = pair.shape1;
  93109. }
  93110. var link;
  93111. if (s1.numContacts < s2.numContacts) link = s1.contactLink;
  93112. else link = s2.contactLink;
  93113. var exists = false;
  93114. while (link) {
  93115. var contact = link.contact;
  93116. if (contact.shape1 == s1 && contact.shape2 == s2) {
  93117. contact.persisting = true;
  93118. exists = true;// contact already exists
  93119. break;
  93120. }
  93121. link = link.next;
  93122. }
  93123. if (!exists) {
  93124. this.addContact(s1, s2);
  93125. }
  93126. }// while(i-- >0);
  93127. if (stat) {
  93128. time2 = OIMO.now();
  93129. this.performance.broadPhaseTime = time2 - time1;
  93130. }
  93131. // update & narrow phase
  93132. this.numContactPoints = 0;
  93133. contact = this.contacts;
  93134. while (contact !== null) {
  93135. if (!contact.persisting) {
  93136. if (contact.shape1.aabb.intersectTest(contact.shape2.aabb)) {
  93137. /*var aabb1=contact.shape1.aabb;
  93138. var aabb2=contact.shape2.aabb;
  93139. if(
  93140. aabb1.minX>aabb2.maxX || aabb1.maxX<aabb2.minX ||
  93141. aabb1.minY>aabb2.maxY || aabb1.maxY<aabb2.minY ||
  93142. aabb1.minZ>aabb2.maxZ || aabb1.maxZ<aabb2.minZ
  93143. ){*/
  93144. var next = contact.next;
  93145. this.removeContact(contact);
  93146. contact = next;
  93147. continue;
  93148. }
  93149. }
  93150. var b1 = contact.body1;
  93151. var b2 = contact.body2;
  93152. if (b1.isDynamic && !b1.sleeping || b2.isDynamic && !b2.sleeping) {
  93153. contact.updateManifold();
  93154. }
  93155. this.numContactPoints += contact.manifold.numPoints;
  93156. contact.persisting = false;
  93157. contact.constraint.addedToIsland = false;
  93158. contact = contact.next;
  93159. }
  93160. if (stat) {
  93161. time3 = OIMO.now();
  93162. this.performance.narrowPhaseTime = time3 - time2;
  93163. }
  93164. //------------------------------------------------------
  93165. // SOLVE ISLANDS
  93166. //------------------------------------------------------
  93167. var invTimeStep = 1 / this.timeStep;
  93168. //var body;
  93169. var joint;
  93170. var constraint;
  93171. //var num;
  93172. for (joint = this.joints; joint !== null; joint = joint.next) {
  93173. joint.addedToIsland = false;
  93174. }
  93175. // clear old island array
  93176. this.islandRigidBodies = [];
  93177. this.islandConstraints = [];
  93178. this.islandStack = [];
  93179. // expand island buffers
  93180. /*if(this.maxIslandRigidBodies<this.numRigidBodies){
  93181. this.maxIslandRigidBodies=this.numRigidBodies<<1;
  93182. //this.maxIslandRigidBodies=this.numRigidBodies*2;
  93183. this.islandRigidBodies=[];
  93184. this.islandStack=[];
  93185. this.islandRigidBodies.length = this.maxIslandRigidBodies;
  93186. this.islandStack.length = this.maxIslandRigidBodies;
  93187. }
  93188. var numConstraints=this.numJoints+this.numContacts;
  93189. if(this.maxIslandConstraints<numConstraints){
  93190. this.maxIslandConstraints=numConstraints<<1;
  93191. //this.maxIslandConstraints=numConstraints*2;
  93192. this.islandConstraints=[];
  93193. this.islandConstraints.length = this.maxIslandConstraints;
  93194. }*/
  93195. time1 = OIMO.now();
  93196. this.numIslands = 0;
  93197. // build and solve simulation islands
  93198. for (var base = this.rigidBodies; base !== null; base = base.next) {
  93199. if (base.addedToIsland || base.isStatic || base.sleeping) continue;// ignore
  93200. if (base.isLonely()) {// update single body
  93201. if (base.isDynamic) {
  93202. base.linearVelocity.addTime(this.gravity, this.timeStep);
  93203. /*base.linearVelocity.x+=this.gravity.x*this.timeStep;
  93204. base.linearVelocity.y+=this.gravity.y*this.timeStep;
  93205. base.linearVelocity.z+=this.gravity.z*this.timeStep;*/
  93206. }
  93207. if (this.callSleep(base)) {
  93208. base.sleepTime += this.timeStep;
  93209. if (base.sleepTime > 0.5) base.sleep();
  93210. else base.updatePosition(this.timeStep);
  93211. } else {
  93212. base.sleepTime = 0;
  93213. base.updatePosition(this.timeStep);
  93214. }
  93215. this.numIslands++;
  93216. continue;
  93217. }
  93218. var islandNumRigidBodies = 0;
  93219. var islandNumConstraints = 0;
  93220. var stackCount = 1;
  93221. // add rigid body to stack
  93222. this.islandStack[0] = base;
  93223. base.addedToIsland = true;
  93224. // build an island
  93225. do {
  93226. // get rigid body from stack
  93227. body = this.islandStack[--stackCount];
  93228. this.islandStack[stackCount] = null;
  93229. body.sleeping = false;
  93230. // add rigid body to the island
  93231. this.islandRigidBodies[islandNumRigidBodies++] = body;
  93232. if (body.isStatic) continue;
  93233. // search connections
  93234. for (var cs = body.contactLink; cs !== null; cs = cs.next) {
  93235. var contact = cs.contact;
  93236. constraint = contact.constraint;
  93237. if (constraint.addedToIsland || !contact.touching) continue;// ignore
  93238. // add constraint to the island
  93239. this.islandConstraints[islandNumConstraints++] = constraint;
  93240. constraint.addedToIsland = true;
  93241. var next = cs.body;
  93242. if (next.addedToIsland) continue;
  93243. // add rigid body to stack
  93244. this.islandStack[stackCount++] = next;
  93245. next.addedToIsland = true;
  93246. }
  93247. for (var js = body.jointLink; js !== null; js = js.next) {
  93248. constraint = js.joint;
  93249. if (constraint.addedToIsland) continue;// ignore
  93250. // add constraint to the island
  93251. this.islandConstraints[islandNumConstraints++] = constraint;
  93252. constraint.addedToIsland = true;
  93253. next = js.body;
  93254. if (next.addedToIsland || !next.isDynamic) continue;
  93255. // add rigid body to stack
  93256. this.islandStack[stackCount++] = next;
  93257. next.addedToIsland = true;
  93258. }
  93259. } while (stackCount != 0);
  93260. // update velocities
  93261. var gVel = new OIMO.Vec3().addTime(this.gravity, this.timeStep);
  93262. /*var gx=this.gravity.x*this.timeStep;
  93263. var gy=this.gravity.y*this.timeStep;
  93264. var gz=this.gravity.z*this.timeStep;*/
  93265. var j = islandNumRigidBodies;
  93266. while (j--) {
  93267. //or(var j=0, l=islandNumRigidBodies; j<l; j++){
  93268. body = this.islandRigidBodies[j];
  93269. if (body.isDynamic) {
  93270. body.linearVelocity.addEqual(gVel);
  93271. /*body.linearVelocity.x+=gx;
  93272. body.linearVelocity.y+=gy;
  93273. body.linearVelocity.z+=gz;*/
  93274. }
  93275. }
  93276. // randomizing order
  93277. if (this.enableRandomizer) {
  93278. //for(var j=1, l=islandNumConstraints; j<l; j++){
  93279. j = islandNumConstraints;
  93280. while (j--) {
  93281. if (j !== 0) {
  93282. var swap = (this.randX = (this.randX * this.randA + this.randB & 0x7fffffff)) / 2147483648.0 * j | 0;
  93283. constraint = this.islandConstraints[j];
  93284. this.islandConstraints[j] = this.islandConstraints[swap];
  93285. this.islandConstraints[swap] = constraint;
  93286. }
  93287. }
  93288. }
  93289. // solve contraints
  93290. j = islandNumConstraints;
  93291. while (j--) {
  93292. //for(j=0, l=islandNumConstraints; j<l; j++){
  93293. this.islandConstraints[j].preSolve(this.timeStep, invTimeStep);// pre-solve
  93294. }
  93295. var k = this.numIterations;
  93296. while (k--) {
  93297. //for(var k=0, l=this.numIterations; k<l; k++){
  93298. j = islandNumConstraints;
  93299. while (j--) {
  93300. //for(j=0, m=islandNumConstraints; j<m; j++){
  93301. this.islandConstraints[j].solve();// main-solve
  93302. }
  93303. }
  93304. j = islandNumConstraints;
  93305. while (j--) {
  93306. //for(j=0, l=islandNumConstraints; j<l; j++){
  93307. this.islandConstraints[j].postSolve();// post-solve
  93308. this.islandConstraints[j] = null;// gc
  93309. }
  93310. // sleeping check
  93311. var sleepTime = 10;
  93312. j = islandNumRigidBodies;
  93313. while (j--) {
  93314. //for(j=0, l=islandNumRigidBodies;j<l;j++){
  93315. body = this.islandRigidBodies[j];
  93316. if (this.callSleep(body)) {
  93317. body.sleepTime += this.timeStep;
  93318. if (body.sleepTime < sleepTime) sleepTime = body.sleepTime;
  93319. } else {
  93320. body.sleepTime = 0;
  93321. sleepTime = 0;
  93322. continue;
  93323. }
  93324. }
  93325. if (sleepTime > 0.5) {
  93326. // sleep the island
  93327. j = islandNumRigidBodies;
  93328. while (j--) {
  93329. //for(j=0, l=islandNumRigidBodies;j<l;j++){
  93330. this.islandRigidBodies[j].sleep();
  93331. this.islandRigidBodies[j] = null;// gc
  93332. }
  93333. } else {
  93334. // update positions
  93335. j = islandNumRigidBodies;
  93336. while (j--) {
  93337. //for(j=0, l=islandNumRigidBodies;j<l;j++){
  93338. this.islandRigidBodies[j].updatePosition(this.timeStep);
  93339. this.islandRigidBodies[j] = null;// gc
  93340. }
  93341. }
  93342. this.numIslands++;
  93343. }
  93344. if (stat) {
  93345. time2 = OIMO.now();
  93346. this.performance.solvingTime = time2 - time1;
  93347. //------------------------------------------------------
  93348. // END SIMULATION
  93349. //------------------------------------------------------
  93350. time2 = OIMO.now();
  93351. // fps update
  93352. this.performance.upfps();
  93353. this.performance.totalTime = time2 - time0;
  93354. }
  93355. }
  93356. }
  93357. /**
  93358. * The class of rigid body.
  93359. * Rigid body has the shape of a single or multiple collision processing,
  93360. * I can set the parameters individually.
  93361. * @author saharan
  93362. */
  93363. OIMO.RigidBody = function (x, y, z, rad, ax, ay, az) {
  93364. this.name = " ";
  93365. // The maximum number of shapes that can be added to a one rigid.
  93366. this.MAX_SHAPES = 64;//64;
  93367. this.prev = null;
  93368. this.next = null;
  93369. // I represent the kind of rigid body.
  93370. // Please do not change from the outside this variable.
  93371. // If you want to change the type of rigid body, always
  93372. // Please specify the type you want to set the arguments of setupMass method.
  93373. this.type = OIMO.BODY_NULL;
  93374. this.massInfo = new OIMO.MassInfo();
  93375. // It is the world coordinate of the center of gravity.
  93376. this.position = new OIMO.Vec3(x, y, z);
  93377. this.orientation = this.rotationAxisToQuad(rad || 0, ax || 0, ay || 0, az || 0);
  93378. this.newPosition = new OIMO.Vec3();
  93379. this.controlPos = false;
  93380. this.newOrientation = new OIMO.Quat();
  93381. this.newRotation = new OIMO.Vec3();
  93382. this.currentRotation = new OIMO.Vec3();
  93383. this.controlRot = false;
  93384. this.controlRotInTime = false;
  93385. // Is the translational velocity.
  93386. this.linearVelocity = new OIMO.Vec3();
  93387. // Is the angular velocity.
  93388. this.angularVelocity = new OIMO.Vec3();
  93389. // return matrix for three.js
  93390. this.matrix = new OIMO.Mat44();
  93391. //--------------------------------------------
  93392. // Please do not change from the outside this variables.
  93393. //--------------------------------------------
  93394. // It is a world that rigid body has been added.
  93395. this.parent = null;
  93396. this.contactLink = null;
  93397. this.numContacts = 0;
  93398. // An array of shapes that are included in the rigid body.
  93399. this.shapes = null;
  93400. // The number of shapes that are included in the rigid body.
  93401. this.numShapes = 0;
  93402. // It is the link array of joint that is connected to the rigid body.
  93403. this.jointLink = null;
  93404. // The number of joints that are connected to the rigid body.
  93405. this.numJoints = 0;
  93406. // It is the world coordinate of the center of gravity in the sleep just before.
  93407. this.sleepPosition = new OIMO.Vec3();
  93408. // It is a quaternion that represents the attitude of sleep just before.
  93409. this.sleepOrientation = new OIMO.Quat();
  93410. // I will show this rigid body to determine whether it is a rigid body static.
  93411. this.isStatic = false;
  93412. // I indicates that this rigid body to determine whether it is a rigid body dynamic.
  93413. this.isDynamic = false;
  93414. // It is a rotation matrix representing the orientation.
  93415. this.rotation = new OIMO.Mat33();
  93416. //--------------------------------------------
  93417. // It will be recalculated automatically from the shape, which is included.
  93418. //--------------------------------------------
  93419. // This is the weight.
  93420. this.mass = NaN;
  93421. // It is the reciprocal of the mass.
  93422. this.inverseMass = NaN;
  93423. // It is the inverse of the inertia tensor in the world system.
  93424. this.inverseInertia = new OIMO.Mat33();
  93425. // It is the inertia tensor in the initial state.
  93426. this.localInertia = new OIMO.Mat33();
  93427. // It is the inverse of the inertia tensor in the initial state.
  93428. this.inverseLocalInertia = new OIMO.Mat33();
  93429. // I indicates rigid body whether it has been added to the simulation Island.
  93430. this.addedToIsland = false;
  93431. // It shows how to sleep rigid body.
  93432. this.allowSleep = true;
  93433. // This is the time from when the rigid body at rest.
  93434. this.sleepTime = 0;
  93435. // I shows rigid body to determine whether it is a sleep state.
  93436. this.sleeping = false;
  93437. };
  93438. OIMO.RigidBody.prototype = {
  93439. constructor: OIMO.RigidBody,
  93440. /**
  93441. * I'll add a shape to rigid body.
  93442. * If you add a shape, please call the setupMass method to step up to the start of the next.
  93443. * @param shape shape to Add
  93444. */
  93445. addShape: function (shape) {
  93446. if (shape.parent) OIMO.Error("RigidBody", "It is not possible that you add to the multi-rigid body the shape of one");
  93447. if (this.shapes != null) (this.shapes.prev = shape).next = this.shapes;
  93448. this.shapes = shape;
  93449. shape.parent = this;
  93450. if (this.parent) this.parent.addShape(shape);
  93451. this.numShapes++;
  93452. },
  93453. /**
  93454. * I will delete the shape from the rigid body.
  93455. * If you delete a shape, please call the setupMass method to step up to the start of the next.
  93456. * @param shape shape to Delete
  93457. */
  93458. removeShape: function (shape) {
  93459. var remove = shape;
  93460. if (remove.parent != this) return;
  93461. var prev = remove.prev;
  93462. var next = remove.next;
  93463. if (prev != null) prev.next = next;
  93464. if (next != null) next.prev = prev;
  93465. if (this.shapes == remove) this.shapes = next;
  93466. remove.prev = null;
  93467. remove.next = null;
  93468. remove.parent = null;
  93469. if (this.parent) this.parent.removeShape(remove);
  93470. this.numShapes--;
  93471. },
  93472. remove: function () {
  93473. this.dispose();
  93474. },
  93475. dispose: function () {
  93476. this.parent.removeRigidBody(this);
  93477. },
  93478. checkContact: function (name) {
  93479. this.parent.checkContact(this.name, name);
  93480. },
  93481. /**
  93482. * Calulates mass datas(center of gravity, mass, moment inertia, etc...).
  93483. * If the parameter type is set to BODY_STATIC, the rigid body will be fixed to the space.
  93484. * If the parameter adjustPosition is set to true, the shapes' relative positions and
  93485. * the rigid body's position will be adjusted to the center of gravity.
  93486. * @param type
  93487. * @param adjustPosition
  93488. */
  93489. setupMass: function (type, AdjustPosition) {
  93490. var adjustPosition = (AdjustPosition !== undefined) ? AdjustPosition : true;
  93491. this.type = type || OIMO.BODY_DYNAMIC;
  93492. this.isDynamic = this.type == OIMO.BODY_DYNAMIC;
  93493. this.isStatic = this.type == OIMO.BODY_STATIC;
  93494. this.mass = 0;
  93495. this.localInertia.set(0, 0, 0, 0, 0, 0, 0, 0, 0);
  93496. var te = this.localInertia.elements;
  93497. //
  93498. var tmpM = new OIMO.Mat33();
  93499. var tmpV = new OIMO.Vec3();
  93500. for (var shape = this.shapes; shape != null; shape = shape.next) {
  93501. shape.calculateMassInfo(this.massInfo);
  93502. var shapeMass = this.massInfo.mass;
  93503. var relX = shape.relativePosition.x;
  93504. var relY = shape.relativePosition.y;
  93505. var relZ = shape.relativePosition.z;
  93506. /*tmpV.x+=relX*shapeMass;
  93507. tmpV.y+=relY*shapeMass;
  93508. tmpV.z+=relZ*shapeMass;*/
  93509. tmpV.addScale(shape.relativePosition, shapeMass);
  93510. this.mass += shapeMass;
  93511. this.rotateInertia(shape.relativeRotation, this.massInfo.inertia, tmpM);
  93512. this.localInertia.addEqual(tmpM);
  93513. // add offset inertia
  93514. te[0] += shapeMass * (relY * relY + relZ * relZ);
  93515. te[4] += shapeMass * (relX * relX + relZ * relZ);
  93516. te[8] += shapeMass * (relX * relX + relY * relY);
  93517. var xy = shapeMass * relX * relY;
  93518. var yz = shapeMass * relY * relZ;
  93519. var zx = shapeMass * relZ * relX;
  93520. te[1] -= xy;
  93521. te[3] -= xy;
  93522. te[2] -= yz;
  93523. te[6] -= yz;
  93524. te[5] -= zx;
  93525. te[7] -= zx;
  93526. }
  93527. this.inverseMass = 1 / this.mass;
  93528. tmpV.scaleEqual(this.inverseMass);
  93529. if (adjustPosition) {
  93530. this.position.addEqual(tmpV);
  93531. for (shape = this.shapes; shape != null; shape = shape.next) {
  93532. shape.relativePosition.subEqual(tmpV);
  93533. }
  93534. // subtract offset inertia
  93535. relX = tmpV.x;
  93536. relY = tmpV.y;
  93537. relZ = tmpV.z;
  93538. //var te = this.localInertia.elements;
  93539. te[0] -= this.mass * (relY * relY + relZ * relZ);
  93540. te[4] -= this.mass * (relX * relX + relZ * relZ);
  93541. te[8] -= this.mass * (relX * relX + relY * relY);
  93542. xy = this.mass * relX * relY;
  93543. yz = this.mass * relY * relZ;
  93544. zx = this.mass * relZ * relX;
  93545. te[1] += xy;
  93546. te[3] += xy;
  93547. te[2] += yz;
  93548. te[6] += yz;
  93549. te[5] += zx;
  93550. te[7] += zx;
  93551. }
  93552. this.inverseLocalInertia.invert(this.localInertia);
  93553. if (this.type == OIMO.BODY_STATIC) {
  93554. this.inverseMass = 0;
  93555. this.inverseLocalInertia.set(0, 0, 0, 0, 0, 0, 0, 0, 0);
  93556. }
  93557. this.syncShapes();
  93558. this.awake();
  93559. },
  93560. /**
  93561. * Awake the rigid body.
  93562. */
  93563. awake: function () {
  93564. if (!this.allowSleep || !this.sleeping) return;
  93565. this.sleeping = false;
  93566. this.sleepTime = 0;
  93567. // awake connected constraints
  93568. var cs = this.contactLink;
  93569. while (cs != null) {
  93570. cs.body.sleepTime = 0;
  93571. cs.body.sleeping = false;
  93572. cs = cs.next;
  93573. }
  93574. var js = this.jointLink;
  93575. while (js != null) {
  93576. js.body.sleepTime = 0;
  93577. js.body.sleeping = false;
  93578. js = js.next;
  93579. }
  93580. for (var shape = this.shapes; shape != null; shape = shape.next) {
  93581. shape.updateProxy();
  93582. }
  93583. },
  93584. /**
  93585. * Sleep the rigid body.
  93586. */
  93587. sleep: function () {
  93588. if (!this.allowSleep || this.sleeping) return;
  93589. this.linearVelocity.set(0, 0, 0);
  93590. this.angularVelocity.set(0, 0, 0);
  93591. this.sleepPosition.copy(this.position);
  93592. this.sleepOrientation.copy(this.orientation);
  93593. /*this.linearVelocity.x=0;
  93594. this.linearVelocity.y=0;
  93595. this.linearVelocity.z=0;
  93596. this.angularVelocity.x=0;
  93597. this.angularVelocity.y=0;
  93598. this.angularVelocity.z=0;
  93599. this.sleepPosition.x=this.position.x;
  93600. this.sleepPosition.y=this.position.y;
  93601. this.sleepPosition.z=this.position.z;*/
  93602. /*this.sleepOrientation.s=this.orientation.s;
  93603. this.sleepOrientation.x=this.orientation.x;
  93604. this.sleepOrientation.y=this.orientation.y;
  93605. this.sleepOrientation.z=this.orientation.z;*/
  93606. this.sleepTime = 0;
  93607. this.sleeping = true;
  93608. for (var shape = this.shapes; shape != null; shape = shape.next) {
  93609. shape.updateProxy();
  93610. }
  93611. },
  93612. /**
  93613. * Get whether the rigid body has not any connection with others.
  93614. * @return
  93615. */
  93616. isLonely: function () {
  93617. return this.numJoints == 0 && this.numContacts == 0;
  93618. },
  93619. /**
  93620. * The time integration of the motion of a rigid body, you can update the information such as the shape.
  93621. * This method is invoked automatically when calling the step of the World,
  93622. * There is no need to call from outside usually.
  93623. * @param timeStep time
  93624. */
  93625. updatePosition: function (timeStep) {
  93626. switch (this.type) {
  93627. case OIMO.BODY_STATIC:
  93628. this.linearVelocity.set(0, 0, 0);
  93629. this.angularVelocity.set(0, 0, 0);
  93630. // ONLY FOR TEST
  93631. if (this.controlPos) {
  93632. this.position.copy(this.newPosition);
  93633. this.controlPos = false;
  93634. }
  93635. if (this.controlRot) {
  93636. this.orientation.copy(this.newOrientation);
  93637. this.controlRot = false;
  93638. }
  93639. /*this.linearVelocity.x=0;
  93640. this.linearVelocity.y=0;
  93641. this.linearVelocity.z=0;
  93642. this.angularVelocity.x=0;
  93643. this.angularVelocity.y=0;
  93644. this.angularVelocity.z=0;*/
  93645. break;
  93646. case OIMO.BODY_DYNAMIC:
  93647. if (this.controlPos) {
  93648. this.angularVelocity.set(0, 0, 0);
  93649. this.linearVelocity.set(0, 0, 0);
  93650. this.linearVelocity.x = (this.newPosition.x - this.position.x) / timeStep;
  93651. this.linearVelocity.y = (this.newPosition.y - this.position.y) / timeStep;
  93652. this.linearVelocity.z = (this.newPosition.z - this.position.z) / timeStep;
  93653. this.controlPos = false;
  93654. }
  93655. if (this.controlRot) {
  93656. this.angularVelocity.set(0, 0, 0);
  93657. this.orientation.copy(this.newOrientation);
  93658. //var t=timeStep//*0.5;
  93659. //var q = new OIMO.Quat();
  93660. //q.sub(this.newOrientation, this.orientation);
  93661. //q.normalize(q);
  93662. /*q.s = (this.newOrientation.s - this.orientation.s)/t;
  93663. q.x = (this.newOrientation.x - this.orientation.x)/t;
  93664. q.y = (this.newOrientation.y - this.orientation.y)/t;
  93665. q.z = (this.newOrientation.z - this.orientation.z)/t;*/
  93666. //this.angularVelocity.applyQuaternion(q);
  93667. //this.angularVelocity.x = this.angularVelocity.x/t;
  93668. //this.angularVelocity.y = this.angularVelocity.y/t;
  93669. //this.angularVelocity.z = this.angularVelocity.z/t;
  93670. this.controlRot = false;
  93671. }
  93672. this.position.addTime(this.linearVelocity, timeStep);
  93673. this.orientation.addTime(this.angularVelocity, timeStep);
  93674. break;
  93675. default: OIMO.Error("RigidBody", "Invalid type.");
  93676. }
  93677. this.syncShapes();
  93678. },
  93679. rotateInertia: function (rot, inertia, out) {
  93680. var tm1 = rot.elements;
  93681. var tm2 = inertia.elements;
  93682. var a0 = tm1[0], a3 = tm1[3], a6 = tm1[6];
  93683. var a1 = tm1[1], a4 = tm1[4], a7 = tm1[7];
  93684. var a2 = tm1[2], a5 = tm1[5], a8 = tm1[8];
  93685. var b0 = tm2[0], b3 = tm2[3], b6 = tm2[6];
  93686. var b1 = tm2[1], b4 = tm2[4], b7 = tm2[7];
  93687. var b2 = tm2[2], b5 = tm2[5], b8 = tm2[8];
  93688. var e00 = a0 * b0 + a1 * b3 + a2 * b6;
  93689. var e01 = a0 * b1 + a1 * b4 + a2 * b7;
  93690. var e02 = a0 * b2 + a1 * b5 + a2 * b8;
  93691. var e10 = a3 * b0 + a4 * b3 + a5 * b6;
  93692. var e11 = a3 * b1 + a4 * b4 + a5 * b7;
  93693. var e12 = a3 * b2 + a4 * b5 + a5 * b8;
  93694. var e20 = a6 * b0 + a7 * b3 + a8 * b6;
  93695. var e21 = a6 * b1 + a7 * b4 + a8 * b7;
  93696. var e22 = a6 * b2 + a7 * b5 + a8 * b8;
  93697. var oe = out.elements;
  93698. oe[0] = e00 * a0 + e01 * a1 + e02 * a2;
  93699. oe[1] = e00 * a3 + e01 * a4 + e02 * a5;
  93700. oe[2] = e00 * a6 + e01 * a7 + e02 * a8;
  93701. oe[3] = e10 * a0 + e11 * a1 + e12 * a2;
  93702. oe[4] = e10 * a3 + e11 * a4 + e12 * a5;
  93703. oe[5] = e10 * a6 + e11 * a7 + e12 * a8;
  93704. oe[6] = e20 * a0 + e21 * a1 + e22 * a2;
  93705. oe[7] = e20 * a3 + e21 * a4 + e22 * a5;
  93706. oe[8] = e20 * a6 + e21 * a7 + e22 * a8;
  93707. },
  93708. syncShapes: function () {
  93709. var s = this.orientation.s;
  93710. var x = this.orientation.x;
  93711. var y = this.orientation.y;
  93712. var z = this.orientation.z;
  93713. var x2 = 2 * x;
  93714. var y2 = 2 * y;
  93715. var z2 = 2 * z;
  93716. var xx = x * x2;
  93717. var yy = y * y2;
  93718. var zz = z * z2;
  93719. var xy = x * y2;
  93720. var yz = y * z2;
  93721. var xz = x * z2;
  93722. var sx = s * x2;
  93723. var sy = s * y2;
  93724. var sz = s * z2;
  93725. var tr = this.rotation.elements;
  93726. tr[0] = 1 - yy - zz;
  93727. tr[1] = xy - sz;
  93728. tr[2] = xz + sy;
  93729. tr[3] = xy + sz;
  93730. tr[4] = 1 - xx - zz;
  93731. tr[5] = yz - sx;
  93732. tr[6] = xz - sy;
  93733. tr[7] = yz + sx;
  93734. tr[8] = 1 - xx - yy;
  93735. this.rotateInertia(this.rotation, this.inverseLocalInertia, this.inverseInertia);
  93736. for (var shape = this.shapes; shape != null; shape = shape.next) {
  93737. //var relPos=shape.relativePosition;
  93738. //var relRot=shape.relativeRotation;
  93739. //var rot=shape.rotation;
  93740. /*var lx=relPos.x;
  93741. var ly=relPos.y;
  93742. var lz=relPos.z;
  93743. shape.position.x=this.position.x+lx*tr[0]+ly*tr[1]+lz*tr[2];
  93744. shape.position.y=this.position.y+lx*tr[3]+ly*tr[4]+lz*tr[5];
  93745. shape.position.z=this.position.z+lx*tr[6]+ly*tr[7]+lz*tr[8];*/
  93746. shape.position.mul(this.position, shape.relativePosition, this.rotation);
  93747. //shape.rotation.mul(shape.relativeRotation,this.rotation);
  93748. // add by QuaziKb
  93749. shape.rotation.mul(this.rotation, shape.relativeRotation);
  93750. shape.updateProxy();
  93751. }
  93752. },
  93753. applyImpulse: function (position, force) {
  93754. this.linearVelocity.addScale(force, this.inverseMass);
  93755. /*this.linearVelocity.x+=force.x*this.inverseMass;
  93756. this.linearVelocity.y+=force.y*this.inverseMass;
  93757. this.linearVelocity.z+=force.z*this.inverseMass;*/
  93758. var rel = new OIMO.Vec3();
  93759. rel.sub(position, this.position).cross(rel, force).mulMat(this.inverseInertia, rel);
  93760. this.angularVelocity.addEqual(rel);
  93761. /*this.angularVelocity.x+=rel.x;
  93762. this.angularVelocity.y+=rel.y;
  93763. this.angularVelocity.z+=rel.z;*/
  93764. },
  93765. //---------------------------------------------
  93766. //
  93767. // FOR THREE JS
  93768. //
  93769. //---------------------------------------------
  93770. rotationVectToQuad: function (rot) {
  93771. var r = OIMO.EulerToAxis(rot.x * OIMO.degtorad, rot.y * OIMO.degtorad, rot.z * OIMO.degtorad);
  93772. return this.rotationAxisToQuad(r[0], r[1], r[2], r[3]);
  93773. },
  93774. rotationAxisToQuad: function (rad, ax, ay, az) { // in radian
  93775. var len = ax * ax + ay * ay + az * az;
  93776. if (len > 0) {
  93777. len = 1 / OIMO.sqrt(len);
  93778. ax *= len;
  93779. ay *= len;
  93780. az *= len;
  93781. }
  93782. var sin = OIMO.sin(rad * 0.5);
  93783. var cos = OIMO.cos(rad * 0.5);
  93784. return new OIMO.Quat(cos, sin * ax, sin * ay, sin * az);
  93785. },
  93786. //---------------------------------------------
  93787. // SET DYNAMIQUE POSITION AND ROTATION
  93788. //---------------------------------------------
  93789. setPosition: function (pos) {
  93790. this.newPosition.copy(pos).multiplyScalar(OIMO.INV_SCALE);
  93791. //this.newPosition.set(pos.x*OIMO.INV_SCALE,pos.y*OIMO.INV_SCALE,pos.z*OIMO.INV_SCALE);
  93792. this.controlPos = true;
  93793. },
  93794. setQuaternion: function (q) {
  93795. //if(this.type == this.BODY_STATIC)this.orientation.init(q.w,q.x,q.y,q.z);
  93796. this.newOrientation.set(q.x, q.y, q.z, q.w);
  93797. this.controlRot = true;
  93798. },
  93799. setRotation: function (rot) {
  93800. this.newOrientation = this.rotationVectToQuad(rot);
  93801. this.controlRot = true;
  93802. },
  93803. //---------------------------------------------
  93804. // RESET DYNAMIQUE POSITION AND ROTATION
  93805. //---------------------------------------------
  93806. resetPosition: function (x, y, z) {
  93807. this.linearVelocity.set(0, 0, 0);
  93808. this.angularVelocity.set(0, 0, 0);
  93809. this.position.set(x, y, z).multiplyScalar(OIMO.INV_SCALE);
  93810. //this.position.set( x*OIMO.INV_SCALE, y*OIMO.INV_SCALE, z*OIMO.INV_SCALE );
  93811. this.awake();
  93812. },
  93813. resetQuaternion: function (q) {
  93814. this.angularVelocity.set(0, 0, 0);
  93815. this.orientation = new OIMO.Quat(q.w, q.x, q.y, q.z);
  93816. this.awake();
  93817. },
  93818. resetRotation: function (x, y, z) {
  93819. this.angularVelocity.set(0, 0, 0);
  93820. this.orientation = this.rotationVectToQuad(new OIMO.Vec3(x, y, z));
  93821. this.awake();
  93822. },
  93823. //---------------------------------------------
  93824. // GET POSITION AND ROTATION
  93825. //---------------------------------------------
  93826. getPosition: function () {
  93827. return new OIMO.Vec3().scale(this.position, OIMO.WORLD_SCALE);
  93828. },
  93829. getRotation: function () {
  93830. return new OIMO.Euler().setFromRotationMatrix(this.rotation);
  93831. },
  93832. getQuaternion: function () {
  93833. return new OIMO.Quaternion().setFromRotationMatrix(this.rotation);
  93834. },
  93835. getMatrix: function () {
  93836. var m = this.matrix.elements;
  93837. var r, p;
  93838. if (!this.sleeping) {
  93839. // rotation matrix
  93840. r = this.rotation.elements;
  93841. m[0] = r[0]; m[1] = r[3]; m[2] = r[6]; m[3] = 0;
  93842. m[4] = r[1]; m[5] = r[4]; m[6] = r[7]; m[7] = 0;
  93843. m[8] = r[2]; m[9] = r[5]; m[10] = r[8]; m[11] = 0;
  93844. // position matrix
  93845. p = this.position;
  93846. m[12] = p.x * OIMO.WORLD_SCALE;
  93847. m[13] = p.y * OIMO.WORLD_SCALE;
  93848. m[14] = p.z * OIMO.WORLD_SCALE;
  93849. // sleep or not ?
  93850. m[15] = 0;
  93851. } else {
  93852. m[15] = 1;
  93853. }
  93854. return m;
  93855. }
  93856. };
  93857. /**
  93858. * The main class of body.
  93859. * is for simplify creation process and data access of rigidRody
  93860. * Rigid body has the shape of a single or multiple collision processing,
  93861. * all setting in object
  93862. *
  93863. * @author loth
  93864. */
  93865. OIMO.Body = function (Obj) {
  93866. var obj = Obj || {};
  93867. if (!obj.world) return;
  93868. if (obj.type === undefined) obj.type = "box";
  93869. this.name = obj.name || '';
  93870. // obsolete use world.add(obj)
  93871. this.body = obj.world.add(obj);
  93872. /*
  93873. // the world where i am
  93874. this.parent = obj.world;
  93875. // Yep my name
  93876. this.name = obj.name || '';
  93877. // I'm dynamique or not
  93878. var move = obj.move || false;
  93879. // I can sleep or not
  93880. var noSleep = obj.noSleep || false;
  93881. // My start position
  93882. var p = obj.pos || [0,0,0];
  93883. p = p.map(function(x) { return x * OIMO.INV_SCALE; });
  93884. // My size
  93885. var s = obj.size || [1,1,1];
  93886. s = s.map(function(x) { return x * OIMO.INV_SCALE; });
  93887. // My rotation in degre
  93888. var rot = obj.rot || [0,0,0];
  93889. rot = rot.map(function(x) { return x * OIMO.TO_RAD; });
  93890. var r = [];
  93891. for (var i=0; i<rot.length/3; i++){
  93892. var tmp = OIMO.EulerToAxis(rot[i+0], rot[i+1], rot[i+2]);
  93893. r.push(tmp[0]); r.push(tmp[1]); r.push(tmp[2]); r.push(tmp[3]);
  93894. }
  93895. // My physics setting
  93896. var sc = obj.sc || new OIMO.ShapeConfig();
  93897. if(obj.config){
  93898. // The density of the shape.
  93899. sc.density = obj.config[0] || 1;
  93900. // The coefficient of friction of the shape.
  93901. sc.friction = obj.config[1] || 0.4;
  93902. // The coefficient of restitution of the shape.
  93903. sc.restitution = obj.config[2] || 0.2;
  93904. // The bits of the collision groups to which the shape belongs.
  93905. sc.belongsTo = obj.config[3] || 1;
  93906. // The bits of the collision groups with which the shape collides.
  93907. sc.collidesWith = obj.config[4] || 0xffffffff;
  93908. }
  93909. if(obj.massPos){
  93910. obj.massPos = obj.massPos.map(function(x) { return x * OIMO.INV_SCALE; });
  93911. sc.relativePosition.init(obj.massPos[0], obj.massPos[1], obj.massPos[2]);
  93912. }
  93913. if(obj.massRot){
  93914. obj.massRot = obj.massRot.map(function(x) { return x * OIMO.TO_RAD; });
  93915. sc.relativeRotation = OIMO.EulerToMatrix(obj.massRot[0], obj.massRot[1], obj.massRot[2]);
  93916. }
  93917. // My rigidbody
  93918. this.body = new OIMO.RigidBody(p[0], p[1], p[2], r[0], r[1], r[2], r[3]);
  93919. // My shapes
  93920. var shapes = [];
  93921. var type = obj.type || "box";
  93922. if( typeof type === 'string' ) type = [type];// single shape
  93923. var n, n2;
  93924. for(var i=0; i<type.length; i++){
  93925. n = i*3;
  93926. n2 = i*4;
  93927. switch(type[i]){
  93928. case "sphere": shapes[i] = new OIMO.SphereShape(sc, s[n+0]); break;
  93929. case "cylinder": shapes[i] = new OIMO.BoxShape(sc, s[n+0], s[n+1], s[n+2]); break; // fake cylinder
  93930. case "box": shapes[i] = new OIMO.BoxShape(sc, s[n+0], s[n+1], s[n+2]); break;
  93931. }
  93932. this.body.addShape(shapes[i]);
  93933. if(i>0){
  93934. //shapes[i].position.init(p[0]+p[n+0], p[1]+p[n+1], p[2]+p[n+2] );
  93935. shapes[i].relativePosition = new OIMO.Vec3( p[n+0], p[n+1], p[n+2] );
  93936. if(r[n2+0]) shapes[i].relativeRotation = [ r[n2+0], r[n2+1], r[n2+2], r[n2+3] ];
  93937. }
  93938. }
  93939. // I'm static or i move
  93940. if(move){
  93941. if(obj.massPos || obj.massRot)this.body.setupMass(0x1, false);
  93942. else this.body.setupMass(0x1, true);
  93943. if(noSleep) this.body.allowSleep = false;
  93944. else this.body.allowSleep = true;
  93945. } else {
  93946. this.body.setupMass(0x2);
  93947. }
  93948. this.body.name = this.name;
  93949. this.sleeping = this.body.sleeping;
  93950. // finaly add to physics world
  93951. this.parent.addRigidBody(this.body);*/
  93952. }
  93953. OIMO.Body.prototype = {
  93954. constructor: OIMO.Body,
  93955. // SET
  93956. setPosition: function (pos) {
  93957. this.body.setPosition(pos);
  93958. },
  93959. setQuaternion: function (q) {
  93960. this.body.setQuaternion(q);
  93961. },
  93962. setRotation: function (rot) {
  93963. this.body.setRotation(rot);
  93964. },
  93965. // GET
  93966. getPosition: function () {
  93967. return this.body.getPosition();
  93968. },
  93969. getRotation: function () {
  93970. return this.body.getRotation();
  93971. },
  93972. getQuaternion: function () {
  93973. return this.body.getQuaternion();
  93974. },
  93975. getMatrix: function () {
  93976. return this.body.getMatrix();
  93977. },
  93978. getSleep: function () {
  93979. return this.body.sleeping;
  93980. },
  93981. // RESET
  93982. resetPosition: function (x, y, z) {
  93983. this.body.resetPosition(x, y, z);
  93984. },
  93985. resetRotation: function (x, y, z) {
  93986. this.body.resetRotation(x, y, z);
  93987. },
  93988. // force wakeup
  93989. awake: function () {
  93990. this.body.awake();
  93991. },
  93992. // remove rigidbody
  93993. remove: function () {
  93994. this.body.dispose();
  93995. //this.parent.removeRigidBody(this.body);
  93996. },
  93997. // test if this object hit another
  93998. checkContact: function (name) {
  93999. this.body.checkContact(name);
  94000. //this.parent.checkContact(this.name, name);
  94001. }
  94002. }
  94003. /**
  94004. * The main class of link.
  94005. * is for simplify creation process and data access of Joint
  94006. * all setting in object
  94007. *
  94008. * @author loth
  94009. */
  94010. OIMO.Link = function (Obj) {
  94011. var obj = Obj || {};
  94012. if (!obj.world) return;
  94013. if (obj.type === undefined) obj.type = "jointHinge";
  94014. this.name = obj.name || '';
  94015. // obsolete use world.add(obj)
  94016. this.joint = obj.world.add(obj);
  94017. // the world where i am
  94018. /*this.parent = obj.world;
  94019. this.name = obj.name || '';
  94020. var type = obj.type || "jointHinge";
  94021. var axe1 = obj.axe1 || [1,0,0];
  94022. var axe2 = obj.axe2 || [1,0,0];
  94023. var pos1 = obj.pos1 || [0,0,0];
  94024. var pos2 = obj.pos2 || [0,0,0];
  94025. pos1 = pos1.map(function(x){ return x * OIMO.INV_SCALE; });
  94026. pos2 = pos2.map(function(x){ return x * OIMO.INV_SCALE; });
  94027. var min, max;
  94028. if(type==="jointDistance"){
  94029. min = obj.min || 0;
  94030. max = obj.max || 10;
  94031. min = min*OIMO.INV_SCALE;
  94032. max = max*OIMO.INV_SCALE;
  94033. }else{
  94034. min = obj.min || 57.29578;
  94035. max = obj.max || 0;
  94036. min = min*OIMO.TO_RAD;
  94037. max = max*OIMO.TO_RAD;
  94038. }
  94039. var limit = obj.limit || null;
  94040. var spring = obj.spring || null;
  94041. var motor = obj.motor || null;
  94042. // joint setting
  94043. var jc = new OIMO.JointConfig();
  94044. jc.allowCollision = obj.collision || false;;
  94045. jc.localAxis1.init(axe1[0], axe1[1], axe1[2]);
  94046. jc.localAxis2.init(axe2[0], axe2[1], axe2[2]);
  94047. jc.localAnchorPoint1.init(pos1[0], pos1[1], pos1[2]);
  94048. jc.localAnchorPoint2.init(pos2[0], pos2[1], pos2[2]);
  94049. if (typeof obj.body1 == 'string' || obj.body1 instanceof String) obj.body1 = obj.world.getByName(obj.body1);
  94050. if (typeof obj.body2 == 'string' || obj.body2 instanceof String) obj.body2 = obj.world.getByName(obj.body2);
  94051. jc.body1 = obj.body1;
  94052. jc.body2 = obj.body2;
  94053. switch(type){
  94054. case "jointDistance": this.joint = new OIMO.DistanceJoint(jc, min, max);
  94055. if(spring !== null) this.joint.limitMotor.setSpring(spring[0], spring[1]);
  94056. if(motor !== null) this.joint.limitMotor.setSpring(motor[0], motor[1]);
  94057. break;
  94058. case "jointHinge": this.joint = new OIMO.HingeJoint(jc, min, max);
  94059. if(spring !== null) this.joint.limitMotor.setSpring(spring[0], spring[1]);// soften the joint ex: 100, 0.2
  94060. if(motor !== null) this.joint.limitMotor.setSpring(motor[0], motor[1]);
  94061. break;
  94062. case "jointPrisme": this.joint = new OIMO.PrismaticJoint(jc, min, max); break;
  94063. case "jointSlide": this.joint = new OIMO.SliderJoint(jc, min, max); break;
  94064. case "jointBall": this.joint = new OIMO.BallAndSocketJoint(jc); break;
  94065. case "jointWheel": this.joint = new OIMO.WheelJoint(jc);
  94066. if(limit !== null) this.joint.rotationalLimitMotor1.setLimit(limit[0], limit[1]);
  94067. if(spring !== null) this.joint.rotationalLimitMotor1.setSpring(spring[0], spring[1]);
  94068. if(motor !== null) this.joint.rotationalLimitMotor1.setSpring(motor[0], motor[1]);
  94069. break;
  94070. }
  94071. this.joint.name = this.name;
  94072. // finaly add to physics world
  94073. this.parent.addJoint(this.joint);*/
  94074. }
  94075. OIMO.Link.prototype = {
  94076. constructor: OIMO.Link,
  94077. getPosition: function () {
  94078. // array of two vect3 [point1, point2]
  94079. return this.joint.getPosition();
  94080. },
  94081. getMatrix: function () {
  94082. return this.joint.getMatrix();
  94083. },
  94084. // remove joint
  94085. remove: function () {
  94086. this.joint.dispose();
  94087. //this.parent.removeJoint(this.joint);
  94088. },
  94089. // force wakeup linked body
  94090. awake: function () {
  94091. this.joint.awake();
  94092. }
  94093. }
  94094. /**
  94095. * The Dictionary class for testing
  94096. * @author lo-th
  94097. */
  94098. OIMO.Dictionary = function () {
  94099. this.data = {};
  94100. this.keys = [];
  94101. };
  94102. OIMO.Dictionary.prototype = {
  94103. constructor: OIMO.Dictionary,
  94104. set: function (value) {
  94105. var key = value.id;
  94106. if (!this.get[key]) this.keys.push(key);
  94107. this.data[key] = value;
  94108. },
  94109. get: function (id) {
  94110. return this.data[id];
  94111. },
  94112. del: function (value) {
  94113. var k = this.keys;
  94114. var n = k.indexOf(value.id);
  94115. if (n > -1) {
  94116. delete this.data[k[n]];
  94117. k.splice(n, 1);
  94118. }
  94119. },
  94120. reset: function () {
  94121. var data = this.data, keys = this.keys, key;
  94122. while (keys.length > 0) {
  94123. key = keys.pop();
  94124. delete data[key];
  94125. }
  94126. }
  94127. };
  94128. OIMO.Performance = function (world) {
  94129. this.parent = world;
  94130. this.infos = new OIMO_ARRAY_TYPE(13);
  94131. this.f = [0, 0, 0];
  94132. this.types = ['None', 'BruteForce', 'Sweep & Prune', 'Bounding Volume Tree'];
  94133. this.broadPhase = this.types[this.parent.broadPhase.types];
  94134. this.version = OIMO.REVISION;
  94135. this.fps = 0;
  94136. this.broadPhaseTime = 0;
  94137. this.narrowPhaseTime = 0;
  94138. this.solvingTime = 0;
  94139. //this.updatingTime = 0;
  94140. this.totalTime = 0;
  94141. };
  94142. OIMO.Performance.prototype = {
  94143. upfps: function () {
  94144. this.f[1] = Date.now();
  94145. if (this.f[1] - 1000 > this.f[0]) { this.f[0] = this.f[1]; this.fps = this.f[2]; this.f[2] = 0; } this.f[2]++;
  94146. },
  94147. updatingTime: function () {
  94148. return OIMO.fix(this.totalTime - (this.broadPhaseTime + this.narrowPhaseTime + this.solvingTime));
  94149. },
  94150. show: function () {
  94151. var info = [
  94152. "Oimo.js " + this.version + "<br>",
  94153. this.broadPhase + "<br><br>",
  94154. "FPS: " + this.fps + " fps<br><br>",
  94155. "rigidbody " + this.parent.numRigidBodies + "<br>",
  94156. "contact &nbsp;&nbsp;" + this.parent.numContacts + "<br>",
  94157. "ct-point &nbsp;" + this.parent.numContactPoints + "<br>",
  94158. "paircheck " + this.parent.broadPhase.numPairChecks + "<br>",
  94159. "island &nbsp;&nbsp;&nbsp;" + this.parent.numIslands + "<br><br>",
  94160. "Time in milliseconde<br><br>",
  94161. "broad-phase &nbsp;" + OIMO.fix(this.broadPhaseTime) + "<br>",
  94162. "narrow-phase " + OIMO.fix(this.narrowPhaseTime) + "<br>",
  94163. "solving &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" + OIMO.fix(this.solvingTime) + "<br>",
  94164. "total &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" + OIMO.fix(this.totalTime) + "<br>",
  94165. "updating &nbsp;&nbsp;&nbsp;&nbsp;" + this.updatingTime() + "<br>"
  94166. ].join("\n");
  94167. return info;
  94168. },
  94169. toArray: function () {
  94170. this.infos[0] = this.parent.broadPhase.types;
  94171. this.infos[1] = this.parent.numRigidBodies;
  94172. this.infos[2] = this.parent.numContacts;
  94173. this.infos[3] = this.parent.broadPhase.numPairChecks;
  94174. this.infos[4] = this.parent.numContactPoints;
  94175. this.infos[5] = this.parent.numIslands;
  94176. this.infos[6] = this.broadPhaseTime;
  94177. this.infos[7] = this.narrowPhaseTime;
  94178. this.infos[8] = this.solvingTime;
  94179. this.infos[9] = this.updatingTime();
  94180. this.infos[10] = this.totalTime;
  94181. this.infos[11] = this.fps;
  94182. return this.infos;
  94183. }
  94184. };
  94185. OIMO.Mat44 = function (n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44) {
  94186. this.elements = new OIMO_ARRAY_TYPE(16);
  94187. var te = this.elements;
  94188. te[0] = (n11 !== undefined) ? n11 : 1; te[4] = n12 || 0; te[8] = n13 || 0; te[12] = n14 || 0;
  94189. te[1] = n21 || 0; te[5] = (n22 !== undefined) ? n22 : 1; te[9] = n23 || 0; te[13] = n24 || 0;
  94190. te[2] = n31 || 0; te[6] = n32 || 0; te[10] = (n33 !== undefined) ? n33 : 1; te[14] = n34 || 0;
  94191. te[3] = n41 || 0; te[7] = n42 || 0; te[11] = n43 || 0; te[15] = (n44 !== undefined) ? n44 : 1;
  94192. };
  94193. OIMO.Mat44.prototype = {
  94194. constructor: OIMO.Mat44,
  94195. set: function (n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44) {
  94196. var te = this.elements;
  94197. te[0] = n11; te[4] = n12; te[8] = n13; te[12] = n14;
  94198. te[1] = n21; te[5] = n22; te[9] = n23; te[13] = n24;
  94199. te[2] = n31; te[6] = n32; te[10] = n33; te[14] = n34;
  94200. te[3] = n41; te[7] = n42; te[11] = n43; te[15] = n44;
  94201. return this;
  94202. }/*,
  94203. extractRotation: function () {
  94204. var v1 = new THREE.Vector3();
  94205. return function ( m ) {
  94206. var te = this.elements;
  94207. var me = m.elements;
  94208. var scaleX = 1 / v1.set( me[ 0 ], me[ 1 ], me[ 2 ] ).length();
  94209. var scaleY = 1 / v1.set( me[ 4 ], me[ 5 ], me[ 6 ] ).length();
  94210. var scaleZ = 1 / v1.set( me[ 8 ], me[ 9 ], me[ 10 ] ).length();
  94211. te[ 0 ] = me[ 0 ] * scaleX;
  94212. te[ 1 ] = me[ 1 ] * scaleX;
  94213. te[ 2 ] = me[ 2 ] * scaleX;
  94214. te[ 4 ] = me[ 4 ] * scaleY;
  94215. te[ 5 ] = me[ 5 ] * scaleY;
  94216. te[ 6 ] = me[ 6 ] * scaleY;
  94217. te[ 8 ] = me[ 8 ] * scaleZ;
  94218. te[ 9 ] = me[ 9 ] * scaleZ;
  94219. te[ 10 ] = me[ 10 ] * scaleZ;
  94220. return this;
  94221. };
  94222. }() */
  94223. }
  94224. OIMO.Mat33 = function (e00, e01, e02, e10, e11, e12, e20, e21, e22) {
  94225. this.elements = new OIMO_ARRAY_TYPE(9);
  94226. var te = this.elements;
  94227. this.init(
  94228. (e00 !== undefined) ? e00 : 1, e01 || 0, e02 || 0,
  94229. e10 || 0, (e11 !== undefined) ? e11 : 1, e12 || 0,
  94230. e20 || 0, e21 || 0, (e22 !== undefined) ? e22 : 1
  94231. );
  94232. };
  94233. OIMO.Mat33.prototype = {
  94234. constructor: OIMO.Mat33,
  94235. set: function (e00, e01, e02, e10, e11, e12, e20, e21, e22) {
  94236. var te = this.elements;
  94237. te[0] = e00; te[1] = e01; te[2] = e02;
  94238. te[3] = e10; te[4] = e11; te[5] = e12;
  94239. te[6] = e20; te[7] = e21; te[8] = e22;
  94240. return this;
  94241. },
  94242. init: function (e00, e01, e02, e10, e11, e12, e20, e21, e22) {
  94243. var te = this.elements;
  94244. te[0] = e00; te[1] = e01; te[2] = e02;
  94245. te[3] = e10; te[4] = e11; te[5] = e12;
  94246. te[6] = e20; te[7] = e21; te[8] = e22;
  94247. return this;
  94248. },
  94249. multiply: function (s) {
  94250. var te = this.elements;
  94251. te[0] *= s; te[1] *= s; te[2] *= s;
  94252. te[3] *= s; te[4] *= s; te[5] *= s;
  94253. te[6] *= s; te[7] *= s; te[8] *= s;
  94254. return this;
  94255. },
  94256. add: function (m1, m2) {
  94257. var te = this.elements, tem1 = m1.elements, tem2 = m2.elements;
  94258. te[0] = tem1[0] + tem2[0]; te[1] = tem1[1] + tem2[1]; te[2] = tem1[2] + tem2[2];
  94259. te[3] = tem1[3] + tem2[3]; te[4] = tem1[4] + tem2[4]; te[5] = tem1[5] + tem2[5];
  94260. te[6] = tem1[6] + tem2[6]; te[7] = tem1[7] + tem2[7]; te[8] = tem1[8] + tem2[8];
  94261. return this;
  94262. },
  94263. addEqual: function (m) {
  94264. var te = this.elements, tem = m.elements;
  94265. te[0] += tem[0]; te[1] += tem[1]; te[2] += tem[2];
  94266. te[3] += tem[3]; te[4] += tem[4]; te[5] += tem[5];
  94267. te[6] += tem[6]; te[7] += tem[7]; te[8] += tem[8];
  94268. return this;
  94269. },
  94270. sub: function (m1, m2) {
  94271. var te = this.elements, tem1 = m1.elements, tem2 = m2.elements;
  94272. te[0] = tem1[0] - tem2[0]; te[1] = tem1[1] - tem2[1]; te[2] = tem1[2] - tem2[2];
  94273. te[3] = tem1[3] - tem2[3]; te[4] = tem1[4] - tem2[4]; te[5] = tem1[5] - tem2[5];
  94274. te[6] = tem1[6] - tem2[6]; te[7] = tem1[7] - tem2[7]; te[8] = tem1[8] - tem2[8];
  94275. return this;
  94276. },
  94277. subEqual: function (m) {
  94278. var te = this.elements, tem = m.elements;
  94279. te[0] -= tem[0]; te[1] -= tem[1]; te[2] -= tem[2];
  94280. te[3] -= tem[3]; te[4] -= tem[4]; te[5] -= tem[5];
  94281. te[6] -= tem[6]; te[7] -= tem[7]; te[8] -= tem[8];
  94282. return this;
  94283. },
  94284. scale: function (m, s) {
  94285. var te = this.elements, tm = m.elements;
  94286. te[0] = tm[0] * s; te[1] = tm[1] * s; te[2] = tm[2] * s;
  94287. te[3] = tm[3] * s; te[4] = tm[4] * s; te[5] = tm[5] * s;
  94288. te[6] = tm[6] * s; te[7] = tm[7] * s; te[8] = tm[8] * s;
  94289. return this;
  94290. },
  94291. scaleEqual: function (s) {
  94292. var te = this.elements;
  94293. te[0] *= s; te[1] *= s; te[2] *= s;
  94294. te[3] *= s; te[4] *= s; te[5] *= s;
  94295. te[6] *= s; te[7] *= s; te[8] *= s;
  94296. return this;
  94297. },
  94298. mul: function (m1, m2) {
  94299. var te = this.elements, tm1 = m1.elements, tm2 = m2.elements,
  94300. a0 = tm1[0], a3 = tm1[3], a6 = tm1[6],
  94301. a1 = tm1[1], a4 = tm1[4], a7 = tm1[7],
  94302. a2 = tm1[2], a5 = tm1[5], a8 = tm1[8],
  94303. b0 = tm2[0], b3 = tm2[3], b6 = tm2[6],
  94304. b1 = tm2[1], b4 = tm2[4], b7 = tm2[7],
  94305. b2 = tm2[2], b5 = tm2[5], b8 = tm2[8];
  94306. te[0] = a0 * b0 + a1 * b3 + a2 * b6;
  94307. te[1] = a0 * b1 + a1 * b4 + a2 * b7;
  94308. te[2] = a0 * b2 + a1 * b5 + a2 * b8;
  94309. te[3] = a3 * b0 + a4 * b3 + a5 * b6;
  94310. te[4] = a3 * b1 + a4 * b4 + a5 * b7;
  94311. te[5] = a3 * b2 + a4 * b5 + a5 * b8;
  94312. te[6] = a6 * b0 + a7 * b3 + a8 * b6;
  94313. te[7] = a6 * b1 + a7 * b4 + a8 * b7;
  94314. te[8] = a6 * b2 + a7 * b5 + a8 * b8;
  94315. return this;
  94316. },
  94317. mulScale: function (m, sx, sy, sz, Prepend) {
  94318. var prepend = Prepend || false;
  94319. var te = this.elements, tm = m.elements;
  94320. if (prepend) {
  94321. te[0] = sx * tm[0]; te[1] = sx * tm[1]; te[2] = sx * tm[2];
  94322. te[3] = sy * tm[3]; te[4] = sy * tm[4]; te[5] = sy * tm[5];
  94323. te[6] = sz * tm[6]; te[7] = sz * tm[7]; te[8] = sz * tm[8];
  94324. } else {
  94325. te[0] = tm[0] * sx; te[1] = tm[1] * sy; te[2] = tm[2] * sz;
  94326. te[3] = tm[3] * sx; te[4] = tm[4] * sy; te[5] = tm[5] * sz;
  94327. te[6] = tm[6] * sx; te[7] = tm[7] * sy; te[8] = tm[8] * sz;
  94328. }
  94329. return this;
  94330. },
  94331. mulRotate: function (m, rad, ax, ay, az, Prepend) {
  94332. var prepend = Prepend || false;
  94333. var s = OIMO.sin(rad);
  94334. var c = OIMO.cos(rad);
  94335. var c1 = 1 - c;
  94336. var r00 = ax * ax * c1 + c;
  94337. var r01 = ax * ay * c1 - az * s;
  94338. var r02 = ax * az * c1 + ay * s;
  94339. var r10 = ay * ax * c1 + az * s;
  94340. var r11 = ay * ay * c1 + c;
  94341. var r12 = ay * az * c1 - ax * s;
  94342. var r20 = az * ax * c1 - ay * s;
  94343. var r21 = az * ay * c1 + ax * s;
  94344. var r22 = az * az * c1 + c;
  94345. var tm = m.elements;
  94346. var a0 = tm[0], a3 = tm[3], a6 = tm[6];
  94347. var a1 = tm[1], a4 = tm[4], a7 = tm[7];
  94348. var a2 = tm[2], a5 = tm[5], a8 = tm[8];
  94349. var te = this.elements;
  94350. if (prepend) {
  94351. te[0] = r00 * a0 + r01 * a3 + r02 * a6;
  94352. te[1] = r00 * a1 + r01 * a4 + r02 * a7;
  94353. te[2] = r00 * a2 + r01 * a5 + r02 * a8;
  94354. te[3] = r10 * a0 + r11 * a3 + r12 * a6;
  94355. te[4] = r10 * a1 + r11 * a4 + r12 * a7;
  94356. te[5] = r10 * a2 + r11 * a5 + r12 * a8;
  94357. te[6] = r20 * a0 + r21 * a3 + r22 * a6;
  94358. te[7] = r20 * a1 + r21 * a4 + r22 * a7;
  94359. te[8] = r20 * a2 + r21 * a5 + r22 * a8;
  94360. } else {
  94361. te[0] = a0 * r00 + a1 * r10 + a2 * r20;
  94362. te[1] = a0 * r01 + a1 * r11 + a2 * r21;
  94363. te[2] = a0 * r02 + a1 * r12 + a2 * r22;
  94364. te[3] = a3 * r00 + a4 * r10 + a5 * r20;
  94365. te[4] = a3 * r01 + a4 * r11 + a5 * r21;
  94366. te[5] = a3 * r02 + a4 * r12 + a5 * r22;
  94367. te[6] = a6 * r00 + a7 * r10 + a8 * r20;
  94368. te[7] = a6 * r01 + a7 * r11 + a8 * r21;
  94369. te[8] = a6 * r02 + a7 * r12 + a8 * r22;
  94370. }
  94371. return this;
  94372. },
  94373. transpose: function (m) {
  94374. var te = this.elements, tm = m.elements;
  94375. te[0] = tm[0]; te[1] = tm[3]; te[2] = tm[6];
  94376. te[3] = tm[1]; te[4] = tm[4]; te[5] = tm[7];
  94377. te[6] = tm[2]; te[7] = tm[5]; te[8] = tm[8];
  94378. return this;
  94379. },
  94380. setQuat: function (q) {
  94381. var te = this.elements,
  94382. x2 = 2 * q.x, y2 = 2 * q.y, z2 = 2 * q.z,
  94383. xx = q.x * x2, yy = q.y * y2, zz = q.z * z2,
  94384. xy = q.x * y2, yz = q.y * z2, xz = q.x * z2,
  94385. sx = q.s * x2, sy = q.s * y2, sz = q.s * z2;
  94386. te[0] = 1 - yy - zz;
  94387. te[1] = xy - sz;
  94388. te[2] = xz + sy;
  94389. te[3] = xy + sz;
  94390. te[4] = 1 - xx - zz;
  94391. te[5] = yz - sx;
  94392. te[6] = xz - sy;
  94393. te[7] = yz + sx;
  94394. te[8] = 1 - xx - yy;
  94395. return this;
  94396. },
  94397. invert: function (m) {
  94398. var te = this.elements, tm = m.elements,
  94399. a0 = tm[0], a3 = tm[3], a6 = tm[6],
  94400. a1 = tm[1], a4 = tm[4], a7 = tm[7],
  94401. a2 = tm[2], a5 = tm[5], a8 = tm[8],
  94402. b01 = a4 * a8 - a7 * a5,
  94403. b11 = a7 * a2 - a1 * a8,
  94404. b21 = a1 * a5 - a4 * a2,
  94405. dt = a0 * (b01) + a3 * (b11) + a6 * (b21);
  94406. if (dt != 0) { dt = 1.0 / dt; }
  94407. te[0] = dt * b01;//(a4*a8 - a5*a7);
  94408. te[1] = dt * b11;//(a2*a7 - a1*a8);
  94409. te[2] = dt * b21;//(a1*a5 - a2*a4);
  94410. te[3] = dt * (a5 * a6 - a3 * a8);
  94411. te[4] = dt * (a0 * a8 - a2 * a6);
  94412. te[5] = dt * (a2 * a3 - a0 * a5);
  94413. te[6] = dt * (a3 * a7 - a4 * a6);
  94414. te[7] = dt * (a1 * a6 - a0 * a7);
  94415. te[8] = dt * (a0 * a4 - a1 * a3);
  94416. return this;
  94417. },
  94418. /*copy: function(m){
  94419. var te = this.elements, tem = m.elements;
  94420. te[0] = tem[0]; te[1] = tem[1]; te[2] = tem[2];
  94421. te[3] = tem[3]; te[4] = tem[4]; te[5] = tem[5];
  94422. te[6] = tem[6]; te[7] = tem[7]; te[8] = tem[8];
  94423. return this;
  94424. },*/
  94425. toEuler: function () { // not work !!
  94426. function clamp(x) {
  94427. return OIMO.min(OIMO.max(x, -1), 1);
  94428. }
  94429. var te = this.elements;
  94430. var m11 = te[0], m12 = te[3], m13 = te[6];
  94431. var m21 = te[1], m22 = te[4], m23 = te[7];
  94432. var m31 = te[2], m32 = te[5], m33 = te[8];
  94433. var p = new OIMO.Vec3();
  94434. var d = new OIMO.Quat();
  94435. var s;
  94436. p.y = OIMO.asin(clamp(m13));
  94437. if (OIMO.abs(m13) < 0.99999) {
  94438. p.x = OIMO.atan2(-m23, m33);
  94439. p.z = OIMO.atan2(-m12, m11);
  94440. } else {
  94441. p.x = OIMO.atan2(m32, m22);
  94442. p.z = 0;
  94443. }
  94444. return p;
  94445. },
  94446. /*clone: function(){
  94447. var te = this.elements;
  94448. return new OIMO.Mat33(
  94449. te[0], te[1], te[2],
  94450. te[3], te[4], te[5],
  94451. te[6], te[7], te[8]
  94452. );
  94453. },*/
  94454. toString: function () {
  94455. var te = this.elements;
  94456. var text =
  94457. "Mat33|" + te[0].toFixed(4) + ", " + te[1].toFixed(4) + ", " + te[2].toFixed(4) + "|\n" +
  94458. " |" + te[3].toFixed(4) + ", " + te[4].toFixed(4) + ", " + te[5].toFixed(4) + "|\n" +
  94459. " |" + te[6].toFixed(4) + ", " + te[7].toFixed(4) + ", " + te[8].toFixed(4) + "|";
  94460. return text;
  94461. },
  94462. // OK
  94463. multiplyScalar: function (s) {
  94464. var te = this.elements;
  94465. te[0] *= s; te[3] *= s; te[6] *= s;
  94466. te[1] *= s; te[4] *= s; te[7] *= s;
  94467. te[2] *= s; te[5] *= s; te[8] *= s;
  94468. return this;
  94469. },
  94470. identity: function () {
  94471. this.set(1, 0, 0, 0, 1, 0, 0, 0, 1);
  94472. return this;
  94473. },
  94474. clone: function () {
  94475. return new this.constructor().fromArray(this.elements);
  94476. },
  94477. copy: function (m) {
  94478. var me = m.elements;
  94479. this.set(
  94480. me[0], me[3], me[6],
  94481. me[1], me[4], me[7],
  94482. me[2], me[5], me[8]
  94483. );
  94484. return this;
  94485. },
  94486. fromArray: function (array) {
  94487. this.elements.set(array);
  94488. return this;
  94489. },
  94490. toArray: function () {
  94491. var te = this.elements;
  94492. return [
  94493. te[0], te[1], te[2],
  94494. te[3], te[4], te[5],
  94495. te[6], te[7], te[8]
  94496. ];
  94497. }
  94498. };
  94499. OIMO.Quat = function (s, x, y, z) {
  94500. this.s = (s !== undefined) ? s : 1;
  94501. this.x = x || 0;
  94502. this.y = y || 0;
  94503. this.z = z || 0;
  94504. };
  94505. OIMO.Quat.prototype = {
  94506. constructor: OIMO.Quat,
  94507. set: function (x, y, z, w) {
  94508. this.x = x;
  94509. this.y = y;
  94510. this.z = z;
  94511. this.s = w;
  94512. return this;
  94513. },
  94514. init: function (s, x, y, z) {
  94515. this.s = (s !== undefined) ? s : 1;
  94516. this.x = x || 0;
  94517. this.y = y || 0;
  94518. this.z = z || 0;
  94519. return this;
  94520. },
  94521. add: function (q1, q2) {
  94522. this.s = q1.s + q2.s;
  94523. this.x = q1.x + q2.x;
  94524. this.y = q1.y + q2.y;
  94525. this.z = q1.z + q2.z;
  94526. return this;
  94527. },
  94528. addTime: function (v, t) {
  94529. var x = v.x;
  94530. var y = v.y;
  94531. var z = v.z;
  94532. var qs = this.s;
  94533. var qx = this.x;
  94534. var qy = this.y;
  94535. var qz = this.z;
  94536. t *= 0.5;
  94537. var ns = (-x * qx - y * qy - z * qz) * t;
  94538. var nx = (x * qs + y * qz - z * qy) * t;
  94539. var ny = (-x * qz + y * qs + z * qx) * t;
  94540. var nz = (x * qy - y * qx + z * qs) * t;
  94541. qs += ns;
  94542. qx += nx;
  94543. qy += ny;
  94544. qz += nz;
  94545. var s = 1 / OIMO.sqrt(qs * qs + qx * qx + qy * qy + qz * qz);
  94546. this.s = qs * s;
  94547. this.x = qx * s;
  94548. this.y = qy * s;
  94549. this.z = qz * s;
  94550. return this;
  94551. },
  94552. sub: function (q1, q2) {
  94553. this.s = q1.s - q2.s;
  94554. this.x = q1.x - q2.x;
  94555. this.y = q1.y - q2.y;
  94556. this.z = q1.z - q2.z;
  94557. return this;
  94558. },
  94559. scale: function (q, s) {
  94560. this.s = q.s * s;
  94561. this.x = q.x * s;
  94562. this.y = q.y * s;
  94563. this.z = q.z * s;
  94564. return this;
  94565. },
  94566. mul: function (q1, q2) {
  94567. var ax = q1.x, ay = q1.y, az = q1.z, as = q1.s,
  94568. bx = q2.x, by = q2.y, bz = q2.z, bs = q2.s;
  94569. this.x = ax * bs + as * bx + ay * bz - az * by;
  94570. this.y = ay * bs + as * by + az * bx - ax * bz;
  94571. this.z = az * bs + as * bz + ax * by - ay * bx;
  94572. this.s = as * bs - ax * bx - ay * by - az * bz;
  94573. return this;
  94574. },
  94575. arc: function (v1, v2) {
  94576. var x1 = v1.x;
  94577. var y1 = v1.y;
  94578. var z1 = v1.z;
  94579. var x2 = v2.x;
  94580. var y2 = v2.y;
  94581. var z2 = v2.z;
  94582. var d = x1 * x2 + y1 * y2 + z1 * z2;
  94583. if (d == -1) {
  94584. x2 = y1 * x1 - z1 * z1;
  94585. y2 = -z1 * y1 - x1 * x1;
  94586. z2 = x1 * z1 + y1 * y1;
  94587. d = 1 / OIMO.sqrt(x2 * x2 + y2 * y2 + z2 * z2);
  94588. this.s = 0;
  94589. this.x = x2 * d;
  94590. this.y = y2 * d;
  94591. this.z = z2 * d;
  94592. return this;
  94593. }
  94594. var cx = y1 * z2 - z1 * y2;
  94595. var cy = z1 * x2 - x1 * z2;
  94596. var cz = x1 * y2 - y1 * x2;
  94597. this.s = OIMO.sqrt((1 + d) * 0.5);
  94598. d = 0.5 / this.s;
  94599. this.x = cx * d;
  94600. this.y = cy * d;
  94601. this.z = cz * d;
  94602. return this;
  94603. },
  94604. normalize: function (q) {
  94605. var len = OIMO.sqrt(q.s * q.s + q.x * q.x + q.y * q.y + q.z * q.z);
  94606. if (len > 0) { len = 1 / len; }
  94607. this.s = q.s * len;
  94608. this.x = q.x * len;
  94609. this.y = q.y * len;
  94610. this.z = q.z * len;
  94611. return this;
  94612. },
  94613. invert: function (q) {
  94614. this.s = q.s;
  94615. this.x = -q.x;
  94616. this.y = -q.y;
  94617. this.z = -q.z;
  94618. return this;
  94619. },
  94620. length: function () {
  94621. return OIMO.sqrt(this.s * this.s + this.x * this.x + this.y * this.y + this.z * this.z);
  94622. },
  94623. copy: function (q) {
  94624. this.s = q.s;
  94625. this.x = q.x;
  94626. this.y = q.y;
  94627. this.z = q.z;
  94628. return this;
  94629. },
  94630. testDiff: function (q) {
  94631. if (this.s !== q.s || this.x !== q.x || this.y !== q.y || this.z !== q.z) return true;
  94632. else return false;
  94633. },
  94634. clone: function (q) {
  94635. return new OIMO.Quat(this.s, this.x, this.y, this.z);
  94636. },
  94637. toString: function () {
  94638. return "Quat[" + this.s.toFixed(4) + ", (" + this.x.toFixed(4) + ", " + this.y.toFixed(4) + ", " + this.z.toFixed(4) + ")]";
  94639. }
  94640. }
  94641. // for three easy export
  94642. OIMO.Quaternion = function (x, y, z, w) {
  94643. this.x = x || 0;
  94644. this.y = y || 0;
  94645. this.z = z || 0;
  94646. this.w = (w !== undefined) ? w : 1;
  94647. };
  94648. OIMO.Quaternion.prototype = {
  94649. constructor: OIMO.Quaternion,
  94650. setFromRotationMatrix: function (m) {
  94651. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  94652. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  94653. var te = m.elements,
  94654. m11 = te[0], m12 = te[1], m13 = te[2],
  94655. m21 = te[3], m22 = te[4], m23 = te[5],
  94656. m31 = te[6], m32 = te[7], m33 = te[8],
  94657. trace = m11 + m22 + m33,
  94658. s;
  94659. if (trace > 0) {
  94660. s = 0.5 / OIMO.sqrt(trace + 1.0);
  94661. this.w = 0.25 / s;
  94662. this.x = (m32 - m23) * s;
  94663. this.y = (m13 - m31) * s;
  94664. this.z = (m21 - m12) * s;
  94665. } else if (m11 > m22 && m11 > m33) {
  94666. s = 2.0 * OIMO.sqrt(1.0 + m11 - m22 - m33);
  94667. this.w = (m32 - m23) / s;
  94668. this.x = 0.25 * s;
  94669. this.y = (m12 + m21) / s;
  94670. this.z = (m13 + m31) / s;
  94671. } else if (m22 > m33) {
  94672. s = 2.0 * OIMO.sqrt(1.0 + m22 - m11 - m33);
  94673. this.w = (m13 - m31) / s;
  94674. this.x = (m12 + m21) / s;
  94675. this.y = 0.25 * s;
  94676. this.z = (m23 + m32) / s;
  94677. } else {
  94678. s = 2.0 * OIMO.sqrt(1.0 + m33 - m11 - m22);
  94679. this.w = (m21 - m12) / s;
  94680. this.x = (m13 + m31) / s;
  94681. this.y = (m23 + m32) / s;
  94682. this.z = 0.25 * s;
  94683. }
  94684. //this.onChangeCallback();
  94685. return this;
  94686. }
  94687. }
  94688. OIMO.Vec3 = function (x, y, z) {
  94689. this.x = x || 0;
  94690. this.y = y || 0;
  94691. this.z = z || 0;
  94692. };
  94693. OIMO.Vec3.prototype = {
  94694. constructor: OIMO.Vec3,
  94695. init: function (x, y, z) {
  94696. this.x = x || 0;
  94697. this.y = y || 0;
  94698. this.z = z || 0;
  94699. return this;
  94700. },
  94701. set: function (x, y, z) {
  94702. this.x = x;
  94703. this.y = y;
  94704. this.z = z;
  94705. return this;
  94706. },
  94707. add: function (v1, v2) {
  94708. this.x = v1.x + v2.x;
  94709. this.y = v1.y + v2.y;
  94710. this.z = v1.z + v2.z;
  94711. return this;
  94712. },
  94713. addEqual: function (v) {
  94714. this.x += v.x;
  94715. this.y += v.y;
  94716. this.z += v.z;
  94717. return this;
  94718. },
  94719. addTime: function (v, t) {
  94720. this.x += v.x * t;
  94721. this.y += v.y * t;
  94722. this.z += v.z * t;
  94723. return this;
  94724. },
  94725. sub: function (v1, v2) {
  94726. this.x = v1.x - v2.x;
  94727. this.y = v1.y - v2.y;
  94728. this.z = v1.z - v2.z;
  94729. return this;
  94730. },
  94731. subEqual: function (v) {
  94732. this.x -= v.x;
  94733. this.y -= v.y;
  94734. this.z -= v.z;
  94735. return this;
  94736. },
  94737. addScale: function (v, s) {
  94738. this.x += v.x * s;
  94739. this.y += v.y * s;
  94740. this.z += v.z * s;
  94741. return this;
  94742. },
  94743. scale: function (v, s) {
  94744. this.x = v.x * s;
  94745. this.y = v.y * s;
  94746. this.z = v.z * s;
  94747. return this;
  94748. },
  94749. scaleEqual: function (s) {
  94750. this.x *= s;
  94751. this.y *= s;
  94752. this.z *= s;
  94753. return this;
  94754. },
  94755. /*dot: function(v){
  94756. return this.x*v.x+this.y*v.y+this.z*v.z;
  94757. },*/
  94758. cross: function (v1, v2) {
  94759. var ax = v1.x, ay = v1.y, az = v1.z,
  94760. bx = v2.x, by = v2.y, bz = v2.z;
  94761. this.x = ay * bz - az * by;
  94762. this.y = az * bx - ax * bz;
  94763. this.z = ax * by - ay * bx;
  94764. return this;
  94765. },
  94766. mul: function (o, v, m) {
  94767. var te = m.elements;
  94768. this.x = o.x + v.x * te[0] + v.y * te[1] + v.z * te[2];
  94769. this.y = o.y + v.x * te[3] + v.y * te[4] + v.z * te[5];
  94770. this.z = o.z + v.x * te[6] + v.y * te[7] + v.z * te[8];
  94771. return this;
  94772. },
  94773. mulMat: function (m, v) {
  94774. var te = m.elements;
  94775. this.x = te[0] * v.x + te[1] * v.y + te[2] * v.z;
  94776. this.y = te[3] * v.x + te[4] * v.y + te[5] * v.z;
  94777. this.z = te[6] * v.x + te[7] * v.y + te[8] * v.z;
  94778. return this;
  94779. },
  94780. normalize: function (v) {
  94781. var x = v.x, y = v.y, z = v.z;
  94782. var l = x * x + y * y + z * z;
  94783. if (l > 0) {
  94784. l = 1 / OIMO.sqrt(l);
  94785. this.x = x * l;
  94786. this.y = y * l;
  94787. this.z = z * l;
  94788. }
  94789. return this;
  94790. },
  94791. /*norm: function(){
  94792. var x = this.x, y = this.y, z = this.z;
  94793. var l = x*x + y*y + z*z;
  94794. if (l > 0) {
  94795. l = 1 / OIMO.sqrt(l);
  94796. this.x = x*l;
  94797. this.y = y*l;
  94798. this.z = z*l;
  94799. }
  94800. return this;
  94801. },*/
  94802. invert: function (v) {
  94803. this.x = -v.x;
  94804. this.y = -v.y;
  94805. this.z = -v.z;
  94806. return this;
  94807. },
  94808. /*length: function(){
  94809. var x = this.x, y = this.y, z = this.z;
  94810. return OIMO.sqrt(x*x + y*y + z*z);
  94811. },*/
  94812. negate: function () {
  94813. this.x = -this.x;
  94814. this.y = -this.y;
  94815. this.z = -this.z;
  94816. return this;
  94817. },
  94818. dot: function (v) {
  94819. return this.x * v.x + this.y * v.y + this.z * v.z;
  94820. },
  94821. lengthSq: function () {
  94822. return this.x * this.x + this.y * this.y + this.z * this.z;
  94823. },
  94824. length: function () {
  94825. return OIMO.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  94826. },
  94827. /*len: function(){
  94828. var x = this.x, y = this.y, z = this.z;
  94829. return x*x + y*y + z*z;
  94830. },*/
  94831. copy: function (v) {
  94832. this.x = v.x;
  94833. this.y = v.y;
  94834. this.z = v.z;
  94835. return this;
  94836. },
  94837. applyQuaternion: function (q) {
  94838. var x = this.x;
  94839. var y = this.y;
  94840. var z = this.z;
  94841. var qx = q.x;
  94842. var qy = q.y;
  94843. var qz = q.z;
  94844. var qs = q.s;
  94845. // calculate quat * vector
  94846. var ix = qs * x + qy * z - qz * y;
  94847. var iy = qs * y + qz * x - qx * z;
  94848. var iz = qs * z + qx * y - qy * x;
  94849. var iw = -qx * x - qy * y - qz * z;
  94850. // calculate result * inverse quat
  94851. this.x = ix * qs + iw * -qx + iy * -qz - iz * -qy;
  94852. this.y = iy * qs + iw * -qy + iz * -qx - ix * -qz;
  94853. this.z = iz * qs + iw * -qz + ix * -qy - iy * -qx;
  94854. return this;
  94855. },
  94856. testZero: function () {
  94857. if (this.x !== 0 || this.y !== 0 || this.z !== 0) return true;
  94858. else return false;
  94859. },
  94860. testDiff: function (v) {
  94861. return ((v.x !== this.x) || (v.y !== this.y) || (v.z !== this.z));
  94862. //if(this.x!==v.x || this.y!==v.y || this.z!==v.z) return true;
  94863. //else return false;
  94864. },
  94865. equals: function (v) {
  94866. return ((v.x === this.x) && (v.y === this.y) && (v.z === this.z));
  94867. },
  94868. clone: function () {
  94869. return new this.constructor(this.x, this.y, this.z);
  94870. },
  94871. toString: function () {
  94872. return "Vec3[" + this.x.toFixed(4) + ", " + this.y.toFixed(4) + ", " + this.z.toFixed(4) + "]";
  94873. },
  94874. multiplyScalar: function (scalar) {
  94875. if (isFinite(scalar)) {
  94876. this.x *= scalar;
  94877. this.y *= scalar;
  94878. this.z *= scalar;
  94879. } else {
  94880. this.x = 0;
  94881. this.y = 0;
  94882. this.z = 0;
  94883. }
  94884. return this;
  94885. },
  94886. divideScalar: function (scalar) {
  94887. return this.multiplyScalar(1 / scalar);
  94888. },
  94889. // TODO rename to normalize
  94890. norm: function () {
  94891. return this.divideScalar(this.length());
  94892. },
  94893. }
  94894. OIMO.Euler = function (x, y, z, order) {
  94895. this._x = x || 0;
  94896. this._y = y || 0;
  94897. this._z = z || 0;
  94898. this._order = order || OIMO.Euler.DefaultOrder;
  94899. };
  94900. OIMO.Euler.RotationOrders = ['XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX'];
  94901. OIMO.Euler.DefaultOrder = 'XYZ';
  94902. OIMO.clamp = function (x, a, b) {
  94903. return (x < a) ? a : ((x > b) ? b : x);
  94904. }
  94905. OIMO.Euler.prototype = {
  94906. constructor: OIMO.Euler,
  94907. _x: 0, _y: 0, _z: 0, _order: OIMO.Euler.DefaultOrder,
  94908. get x() {
  94909. return this._x;
  94910. },
  94911. set x(value) {
  94912. this._x = value;
  94913. this.onChangeCallback();
  94914. },
  94915. get y() {
  94916. return this._y;
  94917. },
  94918. set y(value) {
  94919. this._y = value;
  94920. this.onChangeCallback();
  94921. },
  94922. get z() {
  94923. return this._z;
  94924. },
  94925. set z(value) {
  94926. this._z = value;
  94927. this.onChangeCallback();
  94928. },
  94929. get order() {
  94930. return this._order;
  94931. },
  94932. set order(value) {
  94933. this._order = value;
  94934. this.onChangeCallback();
  94935. },
  94936. set: function (x, y, z, order) {
  94937. this._x = x;
  94938. this._y = y;
  94939. this._z = z;
  94940. this._order = order || this._order;
  94941. this.onChangeCallback();
  94942. return this;
  94943. },
  94944. copy: function (euler) {
  94945. this._x = euler._x;
  94946. this._y = euler._y;
  94947. this._z = euler._z;
  94948. this._order = euler._order;
  94949. this.onChangeCallback();
  94950. return this;
  94951. },
  94952. setFromRotationMatrix: function (m, order) {
  94953. var clamp = OIMO.clamp;
  94954. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  94955. var te = m.elements;
  94956. /*var m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ];
  94957. var m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ];
  94958. var m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];*/
  94959. var m11 = te[0], m12 = te[1], m13 = te[2],
  94960. m21 = te[3], m22 = te[4], m23 = te[5],
  94961. m31 = te[6], m32 = te[7], m33 = te[8];
  94962. order = order || this._order;
  94963. if (order === 'XYZ') {
  94964. this._y = OIMO.asin(clamp(m13, -1, 1));
  94965. if (OIMO.abs(m13) < 0.99999) {
  94966. this._x = OIMO.atan2(-m23, m33);
  94967. this._z = OIMO.atan2(-m12, m11);
  94968. } else {
  94969. this._x = OIMO.atan2(m32, m22);
  94970. this._z = 0;
  94971. }
  94972. } else if (order === 'YXZ') {
  94973. this._x = OIMO.asin(-clamp(m23, -1, 1));
  94974. if (OIMO.abs(m23) < 0.99999) {
  94975. this._y = OIMO.atan2(m13, m33);
  94976. this._z = OIMO.atan2(m21, m22);
  94977. } else {
  94978. this._y = OIMO.atan2(-m31, m11);
  94979. this._z = 0;
  94980. }
  94981. } else if (order === 'ZXY') {
  94982. this._x = OIMO.asin(clamp(m32, -1, 1));
  94983. if (OIMO.abs(m32) < 0.99999) {
  94984. this._y = OIMO.atan2(-m31, m33);
  94985. this._z = OIMO.atan2(-m12, m22);
  94986. } else {
  94987. this._y = 0;
  94988. this._z = OIMO.atan2(m21, m11);
  94989. }
  94990. } else if (order === 'ZYX') {
  94991. this._y = OIMO.asin(-clamp(m31, -1, 1));
  94992. if (OIMO.abs(m31) < 0.99999) {
  94993. this._x = OIMO.atan2(m32, m33);
  94994. this._z = OIMO.atan2(m21, m11);
  94995. } else {
  94996. this._x = 0;
  94997. this._z = OIMO.atan2(-m12, m22);
  94998. }
  94999. } else if (order === 'YZX') {
  95000. this._z = OIMO.asin(clamp(m21, -1, 1));
  95001. if (OIMO.abs(m21) < 0.99999) {
  95002. this._x = OIMO.atan2(-m23, m22);
  95003. this._y = OIMO.atan2(-m31, m11);
  95004. } else {
  95005. this._x = 0;
  95006. this._y = OIMO.atan2(m13, m33);
  95007. }
  95008. } else if (order === 'XZY') {
  95009. this._z = OIMO.asin(-clamp(m12, -1, 1));
  95010. if (OIMO.abs(m12) < 0.99999) {
  95011. this._x = OIMO.atan2(m32, m22);
  95012. this._y = OIMO.atan2(m13, m11);
  95013. } else {
  95014. this._x = OIMO.atan2(-m23, m33);
  95015. this._y = 0;
  95016. }
  95017. } else {
  95018. console.warn('THREE.Euler: .setFromRotationMatrix() given unsupported order: ' + order)
  95019. }
  95020. this._order = order;
  95021. this.onChangeCallback();
  95022. return this;
  95023. },
  95024. setFromQuaternion: function (q, order, update) {
  95025. var clamp = OIMO.clamp;
  95026. // q is assumed to be normalized
  95027. // http://www.mathworks.com/matlabcentral/fileexchange/20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/content/SpinCalc.m
  95028. var sqx = q.x * q.x;
  95029. var sqy = q.y * q.y;
  95030. var sqz = q.z * q.z;
  95031. var sqw = q.s * q.s;
  95032. order = order || this._order;
  95033. if (order === 'XYZ') {
  95034. this._x = OIMO.atan2(2 * (q.x * q.s - q.y * q.z), (sqw - sqx - sqy + sqz));
  95035. this._y = OIMO.asin(clamp(2 * (q.x * q.z + q.y * q.s), -1, 1));
  95036. this._z = OIMO.atan2(2 * (q.z * q.s - q.x * q.y), (sqw + sqx - sqy - sqz));
  95037. } else if (order === 'YXZ') {
  95038. this._x = OIMO.asin(clamp(2 * (q.x * q.s - q.y * q.z), -1, 1));
  95039. this._y = OIMO.atan2(2 * (q.x * q.z + q.y * q.s), (sqw - sqx - sqy + sqz));
  95040. this._z = OIMO.atan2(2 * (q.x * q.y + q.z * q.s), (sqw - sqx + sqy - sqz));
  95041. } else if (order === 'ZXY') {
  95042. this._x = OIMO.asin(clamp(2 * (q.x * q.s + q.y * q.z), -1, 1));
  95043. this._y = OIMO.atan2(2 * (q.y * q.s - q.z * q.x), (sqw - sqx - sqy + sqz));
  95044. this._z = OIMO.atan2(2 * (q.z * q.s - q.x * q.y), (sqw - sqx + sqy - sqz));
  95045. } else if (order === 'ZYX') {
  95046. this._x = OIMO.atan2(2 * (q.x * q.s + q.z * q.y), (sqw - sqx - sqy + sqz));
  95047. this._y = OIMO.asin(clamp(2 * (q.y * q.s - q.x * q.z), -1, 1));
  95048. this._z = OIMO.atan2(2 * (q.x * q.y + q.z * q.s), (sqw + sqx - sqy - sqz));
  95049. } else if (order === 'YZX') {
  95050. this._x = OIMO.atan2(2 * (q.x * q.s - q.z * q.y), (sqw - sqx + sqy - sqz));
  95051. this._y = OIMO.atan2(2 * (q.y * q.s - q.x * q.z), (sqw + sqx - sqy - sqz));
  95052. this._z = OIMO.asin(clamp(2 * (q.x * q.y + q.z * q.s), -1, 1));
  95053. } else if (order === 'XZY') {
  95054. this._x = OIMO.atan2(2 * (q.x * q.s + q.y * q.z), (sqw - sqx + sqy - sqz));
  95055. this._y = OIMO.atan2(2 * (q.x * q.z + q.y * q.s), (sqw + sqx - sqy - sqz));
  95056. this._z = OIMO.asin(clamp(2 * (q.z * q.s - q.x * q.y), -1, 1));
  95057. } else {
  95058. console.warn('OIMO.Euler: .setFromQuaternion() given unsupported order: ' + order)
  95059. }
  95060. this._order = order;
  95061. if (update !== false) this.onChangeCallback();
  95062. return this;
  95063. },
  95064. reorder: function () {
  95065. // WARNING: this discards revolution information -bhouston
  95066. var q = new OIMO.Quat();
  95067. return function (newOrder) {
  95068. q.setFromEuler(this);
  95069. this.setFromQuaternion(q, newOrder);
  95070. };
  95071. }(),
  95072. equals: function (euler) {
  95073. return (euler._x === this._x) && (euler._y === this._y) && (euler._z === this._z) && (euler._order === this._order);
  95074. },
  95075. fromArray: function (array) {
  95076. this._x = array[0];
  95077. this._y = array[1];
  95078. this._z = array[2];
  95079. if (array[3] !== undefined) this._order = array[3];
  95080. this.onChangeCallback();
  95081. return this;
  95082. },
  95083. toArray: function () {
  95084. return [this._x, this._y, this._z, this._order];
  95085. },
  95086. onChange: function (callback) {
  95087. this.onChangeCallback = callback;
  95088. return this;
  95089. },
  95090. onChangeCallback: function () { },
  95091. clone: function () {
  95092. return new OIMO.Euler(this._x, this._y, this._z, this._order);
  95093. }
  95094. };
  95095. OIMO.EulerToAxis = function (ox, oy, oz) {// angles in radians
  95096. var c1 = OIMO.cos(oy * 0.5);//heading
  95097. var s1 = OIMO.sin(oy * 0.5);
  95098. var c2 = OIMO.cos(oz * 0.5);//altitude
  95099. var s2 = OIMO.sin(oz * 0.5);
  95100. var c3 = OIMO.cos(ox * 0.5);//bank
  95101. var s3 = OIMO.sin(ox * 0.5);
  95102. var c1c2 = c1 * c2;
  95103. var s1s2 = s1 * s2;
  95104. var w = c1c2 * c3 - s1s2 * s3;
  95105. var x = c1c2 * s3 + s1s2 * c3;
  95106. var y = s1 * c2 * c3 + c1 * s2 * s3;
  95107. var z = c1 * s2 * c3 - s1 * c2 * s3;
  95108. var angle = 2 * OIMO.acos(w);
  95109. var norm = x * x + y * y + z * z;
  95110. if (norm < 0.001) {
  95111. x = 1;
  95112. y = z = 0;
  95113. } else {
  95114. norm = OIMO.sqrt(norm);
  95115. x /= norm;
  95116. y /= norm;
  95117. z /= norm;
  95118. }
  95119. return [angle, x, y, z];
  95120. }
  95121. OIMO.EulerToMatrix = function (ox, oy, oz) {// angles in radians
  95122. var ch = OIMO.cos(oy);//heading
  95123. var sh = OIMO.sin(oy);
  95124. var ca = OIMO.cos(oz);//altitude
  95125. var sa = OIMO.sin(oz);
  95126. var cb = OIMO.cos(ox);//bank
  95127. var sb = OIMO.sin(ox);
  95128. var mtx = new OIMO.Mat33();
  95129. var te = mtx.elements;
  95130. te[0] = ch * ca;
  95131. te[1] = sh * sb - ch * sa * cb;
  95132. te[2] = ch * sa * sb + sh * cb;
  95133. te[3] = sa;
  95134. te[4] = ca * cb;
  95135. te[5] = -ca * sb;
  95136. te[6] = -sh * ca;
  95137. te[7] = sh * sa * cb + ch * sb;
  95138. te[8] = -sh * sa * sb + ch * cb;
  95139. return mtx;
  95140. }
  95141. OIMO.MatrixToEuler = function (mtx) {// angles in radians
  95142. var te = mtx.elements;
  95143. var x, y, z;
  95144. if (te[3] > 0.998) { // singularity at north pole
  95145. y = OIMO.atan2(te[2], te[8]);
  95146. z = OIMO.PI / 2;
  95147. x = 0;
  95148. } else if (te[3] < -0.998) { // singularity at south pole
  95149. y = OIMO.atan2(te[2], te[8]);
  95150. z = -OIMO.PI / 2;
  95151. x = 0;
  95152. } else {
  95153. y = OIMO.atan2(-te[6], te[0]);
  95154. x = OIMO.atan2(-te[5], te[4]);
  95155. z = OIMO.asin(te[3]);
  95156. }
  95157. return [x, y, z];
  95158. }
  95159. OIMO.unwrapDegrees = function (r) {
  95160. r = r % 360;
  95161. if (r > 180) r -= 360;
  95162. if (r < -180) r += 360;
  95163. return r;
  95164. }
  95165. OIMO.unwrapRadian = function (r) {
  95166. r = r % OIMO.TwoPI;
  95167. if (r > OIMO.PI) r -= OIMO.TwoPI;
  95168. if (r < -OIMO.PI) r += OIMO.TwoPI;
  95169. return r;
  95170. }
  95171. OIMO.Distance3d = function (p1, p2) {
  95172. var xd = p2[0] - p1[0];
  95173. var yd = p2[1] - p1[1];
  95174. var zd = p2[2] - p1[2];
  95175. return OIMO.sqrt(xd * xd + yd * yd + zd * zd);
  95176. }
  95177. /**
  95178. * The base class of all type of the constraints.
  95179. * @author saharan
  95180. */
  95181. OIMO.Constraint = function () {
  95182. // The parent world of the constraint.
  95183. this.parent = null;
  95184. // The first body of the constraint.
  95185. this.body1 = null;
  95186. // The second body of the constraint.
  95187. this.body2 = null;
  95188. // Internal
  95189. this.addedToIsland = false;
  95190. }
  95191. OIMO.Constraint.prototype = {
  95192. constructor: OIMO.Constraint,
  95193. /**
  95194. * Prepare for solving the constraint.
  95195. * @param timeStep
  95196. * @param invTimeStep
  95197. */
  95198. preSolve: function (timeStep, invTimeStep) {
  95199. OIMO.Error("Constraint", "Inheritance error.");
  95200. },
  95201. /**
  95202. * Solve the constraint.
  95203. * This is usually called iteratively.
  95204. */
  95205. solve: function () {
  95206. OIMO.Error("Constraint", "Inheritance error.");
  95207. },
  95208. /**
  95209. * Do the post-processing.
  95210. */
  95211. postSolve: function () {
  95212. OIMO.Error("Constraint", "Inheritance error.");
  95213. }
  95214. }
  95215. /**
  95216. * Joints are used to constrain the motion between two rigid bodies.
  95217. * @author saharan
  95218. * @author lo-th
  95219. */
  95220. OIMO.Joint = function (config) {
  95221. OIMO.Constraint.call(this);
  95222. // joint name
  95223. this.name = "";
  95224. // The type of the joint.
  95225. this.type = OIMO.JOINT_NULL;
  95226. // The previous joint in the world.
  95227. this.prev = null;
  95228. // The next joint in the world.
  95229. this.next = null;
  95230. this.body1 = config.body1;
  95231. this.body2 = config.body2;
  95232. // The anchor point on the first rigid body in local coordinate system.
  95233. this.localAnchorPoint1 = new OIMO.Vec3().copy(config.localAnchorPoint1);
  95234. // The anchor point on the second rigid body in local coordinate system.
  95235. this.localAnchorPoint2 = new OIMO.Vec3().copy(config.localAnchorPoint2);
  95236. // The anchor point on the first rigid body in world coordinate system relative to the body's origin.
  95237. this.relativeAnchorPoint1 = new OIMO.Vec3();
  95238. // The anchor point on the second rigid body in world coordinate system relative to the body's origin.
  95239. this.relativeAnchorPoint2 = new OIMO.Vec3();
  95240. // The anchor point on the first rigid body in world coordinate system.
  95241. this.anchorPoint1 = new OIMO.Vec3();
  95242. // The anchor point on the second rigid body in world coordinate system.
  95243. this.anchorPoint2 = new OIMO.Vec3();
  95244. // Whether allow collision between connected rigid bodies or not.
  95245. this.allowCollision = config.allowCollision;
  95246. this.b1Link = new OIMO.JointLink(this);
  95247. this.b2Link = new OIMO.JointLink(this);
  95248. this.matrix = new OIMO.Mat44();
  95249. };
  95250. OIMO.Joint.prototype = Object.create(OIMO.Constraint.prototype);
  95251. OIMO.Joint.prototype.constructor = OIMO.Joint;
  95252. // Update all the anchor points.
  95253. OIMO.Joint.prototype.updateAnchorPoints = function () {
  95254. this.relativeAnchorPoint1.mulMat(this.body1.rotation, this.localAnchorPoint1);
  95255. this.relativeAnchorPoint2.mulMat(this.body2.rotation, this.localAnchorPoint2);
  95256. this.anchorPoint1.add(this.relativeAnchorPoint1, this.body1.position);
  95257. this.anchorPoint2.add(this.relativeAnchorPoint2, this.body2.position);
  95258. };
  95259. // Attach the joint from the bodies.
  95260. OIMO.Joint.prototype.attach = function () {
  95261. this.b1Link.body = this.body2;
  95262. this.b2Link.body = this.body1;
  95263. if (this.body1.jointLink != null) (this.b1Link.next = this.body1.jointLink).prev = this.b1Link;
  95264. else this.b1Link.next = null;
  95265. this.body1.jointLink = this.b1Link;
  95266. this.body1.numJoints++;
  95267. if (this.body2.jointLink != null) (this.b2Link.next = this.body2.jointLink).prev = this.b2Link;
  95268. else this.b2Link.next = null;
  95269. this.body2.jointLink = this.b2Link;
  95270. this.body2.numJoints++;
  95271. };
  95272. // Detach the joint from the bodies.
  95273. OIMO.Joint.prototype.detach = function () {
  95274. var prev = this.b1Link.prev;
  95275. var next = this.b1Link.next;
  95276. if (prev != null) prev.next = next;
  95277. if (next != null) next.prev = prev;
  95278. if (this.body1.jointLink == this.b1Link) this.body1.jointLink = next;
  95279. this.b1Link.prev = null;
  95280. this.b1Link.next = null;
  95281. this.b1Link.body = null;
  95282. this.body1.numJoints--;
  95283. prev = this.b2Link.prev;
  95284. next = this.b2Link.next;
  95285. if (prev != null) prev.next = next;
  95286. if (next != null) next.prev = prev;
  95287. if (this.body2.jointLink == this.b2Link) this.body2.jointLink = next;
  95288. this.b2Link.prev = null;
  95289. this.b2Link.next = null;
  95290. this.b2Link.body = null;
  95291. this.body2.numJoints--;
  95292. this.b1Link.body = null;
  95293. this.b2Link.body = null;
  95294. };
  95295. // Awake the bodies.
  95296. OIMO.Joint.prototype.awake = function () {
  95297. this.body1.awake();
  95298. this.body2.awake();
  95299. };
  95300. // calculation function
  95301. OIMO.Joint.prototype.preSolve = function (timeStep, invTimeStep) {
  95302. };
  95303. OIMO.Joint.prototype.solve = function () {
  95304. };
  95305. OIMO.Joint.prototype.postSolve = function () {
  95306. };
  95307. // Delete process
  95308. OIMO.Joint.prototype.remove = function () {
  95309. this.dispose();
  95310. };
  95311. OIMO.Joint.prototype.dispose = function () {
  95312. this.parent.removeJoint(this);
  95313. };
  95314. // Three js add
  95315. OIMO.Joint.prototype.getPosition = function () {
  95316. var p1 = new OIMO.Vec3().scale(this.anchorPoint1, OIMO.WORLD_SCALE);
  95317. var p2 = new OIMO.Vec3().scale(this.anchorPoint2, OIMO.WORLD_SCALE);
  95318. return [p1, p2];
  95319. };
  95320. OIMO.Joint.prototype.getMatrix = function () {
  95321. var m = this.matrix.elements;
  95322. var p1 = this.anchorPoint1;
  95323. var p2 = this.anchorPoint2;
  95324. m[0] = p1.x * OIMO.WORLD_SCALE;
  95325. m[1] = p1.y * OIMO.WORLD_SCALE;
  95326. m[2] = p1.z * OIMO.WORLD_SCALE;
  95327. m[3] = 0;
  95328. m[4] = p2.x * OIMO.WORLD_SCALE;
  95329. m[5] = p2.y * OIMO.WORLD_SCALE;
  95330. m[6] = p2.z * OIMO.WORLD_SCALE;
  95331. m[7] = 0;
  95332. return m;
  95333. };
  95334. /**
  95335. * A joint configuration holds all configuration data for constructing a joint.
  95336. * Joint configurations can be reused safely.
  95337. * @author saharan
  95338. */
  95339. OIMO.JointConfig = function () {
  95340. // The first rigid body of the joint.
  95341. this.body1 = null;
  95342. // The second rigid body of the joint.
  95343. this.body2 = null;
  95344. // The anchor point on the first rigid body in local coordinate system.
  95345. this.localAnchorPoint1 = new OIMO.Vec3();
  95346. // The anchor point on the second rigid body in local coordinate system.
  95347. this.localAnchorPoint2 = new OIMO.Vec3();
  95348. // The axis in the first body's coordinate system.
  95349. // his property is available in some joints.
  95350. this.localAxis1 = new OIMO.Vec3();
  95351. // The axis in the second body's coordinate system.
  95352. // This property is available in some joints.
  95353. this.localAxis2 = new OIMO.Vec3();
  95354. // Whether allow collision between connected rigid bodies or not.
  95355. this.allowCollision = false;
  95356. };
  95357. /**
  95358. * A link list of joints.
  95359. * @author saharan
  95360. */
  95361. OIMO.JointLink = function (joint) {
  95362. // The previous joint link.
  95363. this.prev = null;
  95364. // The next joint link.
  95365. this.next = null;
  95366. // The other rigid body connected to the joint.
  95367. this.body = null;
  95368. // The joint of the link.
  95369. this.joint = joint;
  95370. };
  95371. /**
  95372. * An information of limit and motor.
  95373. * @author saharan
  95374. */
  95375. OIMO.LimitMotor = function (axis, fixed) {
  95376. fixed = fixed || false;
  95377. // The axis of the constraint.
  95378. this.axis = axis;
  95379. // The current angle for rotational constraints.
  95380. this.angle = 0;
  95381. // The lower limit. Set lower > upper to disable
  95382. this.lowerLimit = fixed ? 0 : 1;
  95383. //if(fixed)this.lowerLimit = 0;
  95384. //else this.lowerLimit = 1;
  95385. // The upper limit. Set lower > upper to disable.
  95386. this.upperLimit = 0;
  95387. // The target motor speed.
  95388. this.motorSpeed = 0;
  95389. // The maximum motor force or torque. Set 0 to disable.
  95390. this.maxMotorForce = 0;
  95391. // The frequency of the spring. Set 0 to disable.
  95392. this.frequency = 0;
  95393. // The damping ratio of the spring. Set 0 for no damping, 1 for critical damping.
  95394. this.dampingRatio = 0;
  95395. };
  95396. OIMO.LimitMotor.prototype = {
  95397. constructor: OIMO.LimitMotor,
  95398. /**
  95399. * Set limit data into this constraint.
  95400. * @param lowerLimit
  95401. * @param upperLimit
  95402. */
  95403. setLimit: function (lowerLimit, upperLimit) {
  95404. this.lowerLimit = lowerLimit;
  95405. this.upperLimit = upperLimit;
  95406. },
  95407. /**
  95408. * Set motor data into this constraint.
  95409. * @param motorSpeed
  95410. * @param maxMotorForce
  95411. */
  95412. setMotor: function (motorSpeed, maxMotorForce) {
  95413. this.motorSpeed = motorSpeed;
  95414. this.maxMotorForce = maxMotorForce;
  95415. },
  95416. /**
  95417. * Set spring data into this constraint.
  95418. * @param frequency
  95419. * @param dampingRatio
  95420. */
  95421. setSpring: function (frequency, dampingRatio) {
  95422. this.frequency = frequency;
  95423. this.dampingRatio = dampingRatio;
  95424. }
  95425. };
  95426. /**
  95427. * A ball-and-socket joint limits relative translation on two anchor points on rigid bodies.
  95428. * @author saharan
  95429. * @author lo-th
  95430. */
  95431. OIMO.BallAndSocketJoint = function (config) {
  95432. OIMO.Joint.call(this, config);
  95433. this.type = OIMO.JOINT_BALL_AND_SOCKET;
  95434. this.lc = new OIMO.LinearConstraint(this);
  95435. };
  95436. OIMO.BallAndSocketJoint.prototype = Object.create(OIMO.Joint.prototype);
  95437. OIMO.BallAndSocketJoint.prototype.constructor = OIMO.BallAndSocketJoint;
  95438. OIMO.BallAndSocketJoint.prototype.preSolve = function (timeStep, invTimeStep) {
  95439. this.updateAnchorPoints();
  95440. this.lc.preSolve(timeStep, invTimeStep);
  95441. };
  95442. OIMO.BallAndSocketJoint.prototype.solve = function () {
  95443. this.lc.solve();
  95444. };
  95445. OIMO.BallAndSocketJoint.prototype.postSolve = function () {
  95446. };
  95447. /**
  95448. * A distance joint limits the distance between two anchor points on rigid bodies.
  95449. * @author saharan
  95450. * @author lo-th
  95451. */
  95452. OIMO.DistanceJoint = function (config, minDistance, maxDistance) {
  95453. OIMO.Joint.call(this, config);
  95454. this.type = OIMO.JOINT_DISTANCE;
  95455. this.normal = new OIMO.Vec3();
  95456. this.nr = new OIMO.Vec3();
  95457. // The limit and motor information of the joint.
  95458. this.limitMotor = new OIMO.LimitMotor(this.normal, true);
  95459. this.limitMotor.lowerLimit = minDistance;
  95460. this.limitMotor.upperLimit = maxDistance;
  95461. this.t = new OIMO.TranslationalConstraint(this, this.limitMotor);
  95462. };
  95463. OIMO.DistanceJoint.prototype = Object.create(OIMO.Joint.prototype);
  95464. OIMO.DistanceJoint.prototype.constructor = OIMO.DistanceJoint;
  95465. OIMO.DistanceJoint.prototype.preSolve = function (timeStep, invTimeStep) {
  95466. this.updateAnchorPoints();
  95467. //var nr = this.nr;
  95468. this.nr.sub(this.anchorPoint2, this.anchorPoint1);
  95469. //var len = OIMO.sqrt( nr.x*nr.x + nr.y*nr.y + nr.z*nr.z );
  95470. //if(len>0) len = 1/len;
  95471. //this.normal.scale( nr, len );
  95472. this.normal.normalize(this.nr);
  95473. this.t.preSolve(timeStep, invTimeStep);
  95474. };
  95475. OIMO.DistanceJoint.prototype.solve = function () {
  95476. this.t.solve();
  95477. };
  95478. OIMO.DistanceJoint.prototype.postSolve = function () {
  95479. };
  95480. /**
  95481. * A hinge joint allows only for relative rotation of rigid bodies along the axis.
  95482. * @author saharan
  95483. * @author lo-th
  95484. */
  95485. OIMO.HingeJoint = function (config, lowerAngleLimit, upperAngleLimit) {
  95486. OIMO.Joint.call(this, config);
  95487. this.type = OIMO.JOINT_HINGE;
  95488. // The axis in the first body's coordinate system.
  95489. this.localAxis1 = config.localAxis1.clone().norm();
  95490. // The axis in the second body's coordinate system.
  95491. this.localAxis2 = config.localAxis2.clone().norm();
  95492. // make angle axis 1
  95493. this.localAngle1 = new OIMO.Vec3(
  95494. this.localAxis1.y * this.localAxis1.x - this.localAxis1.z * this.localAxis1.z,
  95495. -this.localAxis1.z * this.localAxis1.y - this.localAxis1.x * this.localAxis1.x,
  95496. this.localAxis1.x * this.localAxis1.z + this.localAxis1.y * this.localAxis1.y
  95497. ).norm();
  95498. // make angle axis 2
  95499. var arc = new OIMO.Mat33().setQuat(new OIMO.Quat().arc(this.localAxis1, this.localAxis2));
  95500. this.localAngle2 = new OIMO.Vec3().mulMat(arc, this.localAngle1);
  95501. this.nor = new OIMO.Vec3();
  95502. this.tan = new OIMO.Vec3();
  95503. this.bin = new OIMO.Vec3();
  95504. this.ax1 = new OIMO.Vec3();
  95505. this.ax2 = new OIMO.Vec3();
  95506. this.an1 = new OIMO.Vec3();
  95507. this.an2 = new OIMO.Vec3();
  95508. // The rotational limit and motor information of the joint.
  95509. this.limitMotor = new OIMO.LimitMotor(this.nor, false);
  95510. this.limitMotor.lowerLimit = lowerAngleLimit;
  95511. this.limitMotor.upperLimit = upperAngleLimit;
  95512. this.lc = new OIMO.LinearConstraint(this);
  95513. this.r3 = new OIMO.Rotational3Constraint(this, this.limitMotor, new OIMO.LimitMotor(this.tan, true), new OIMO.LimitMotor(this.bin, true));
  95514. };
  95515. OIMO.HingeJoint.prototype = Object.create(OIMO.Joint.prototype);
  95516. OIMO.HingeJoint.prototype.constructor = OIMO.HingeJoint;
  95517. OIMO.HingeJoint.prototype.preSolve = function (timeStep, invTimeStep) {
  95518. var tmp1X, tmp1Y, tmp1Z, limite;//, nx, ny, nz, tx, ty, tz, bx, by, bz;
  95519. this.updateAnchorPoints();
  95520. this.ax1.mulMat(this.body1.rotation, this.localAxis1);
  95521. this.ax2.mulMat(this.body2.rotation, this.localAxis2);
  95522. this.an1.mulMat(this.body1.rotation, this.localAngle1);
  95523. this.an2.mulMat(this.body2.rotation, this.localAngle2);
  95524. this.nor.set(
  95525. this.ax1.x * this.body2.inverseMass + this.ax2.x * this.body1.inverseMass,
  95526. this.ax1.y * this.body2.inverseMass + this.ax2.y * this.body1.inverseMass,
  95527. this.ax1.z * this.body2.inverseMass + this.ax2.z * this.body1.inverseMass
  95528. ).norm();
  95529. this.tan.set(
  95530. this.nor.y * this.nor.x - this.nor.z * this.nor.z,
  95531. -this.nor.z * this.nor.y - this.nor.x * this.nor.x,
  95532. this.nor.x * this.nor.z + this.nor.y * this.nor.y
  95533. ).norm();
  95534. this.bin.set(
  95535. this.nor.y * this.tan.z - this.nor.z * this.tan.y,
  95536. this.nor.z * this.tan.x - this.nor.x * this.tan.z,
  95537. this.nor.x * this.tan.y - this.nor.y * this.tan.x
  95538. );
  95539. // calculate hinge angle
  95540. limite = this.acosClamp(this.an1.x * this.an2.x + this.an1.y * this.an2.y + this.an1.z * this.an2.z)
  95541. if (
  95542. this.nor.x * (this.an1.y * this.an2.z - this.an1.z * this.an2.y) +
  95543. this.nor.y * (this.an1.z * this.an2.x - this.an1.x * this.an2.z) +
  95544. this.nor.z * (this.an1.x * this.an2.y - this.an1.y * this.an2.x) < 0
  95545. ) {
  95546. this.limitMotor.angle = -limite;
  95547. } else {
  95548. this.limitMotor.angle = limite;
  95549. }
  95550. tmp1X = this.ax1.y * this.ax2.z - this.ax1.z * this.ax2.y;
  95551. tmp1Y = this.ax1.z * this.ax2.x - this.ax1.x * this.ax2.z;
  95552. tmp1Z = this.ax1.x * this.ax2.y - this.ax1.y * this.ax2.x;
  95553. this.r3.limitMotor2.angle = this.tan.x * tmp1X + this.tan.y * tmp1Y + this.tan.z * tmp1Z;
  95554. this.r3.limitMotor3.angle = this.bin.x * tmp1X + this.bin.y * tmp1Y + this.bin.z * tmp1Z;
  95555. this.r3.preSolve(timeStep, invTimeStep);
  95556. this.lc.preSolve(timeStep, invTimeStep);
  95557. };
  95558. OIMO.HingeJoint.prototype.solve = function () {
  95559. this.r3.solve();
  95560. this.lc.solve();
  95561. };
  95562. OIMO.HingeJoint.prototype.postSolve = function () {
  95563. };
  95564. OIMO.HingeJoint.prototype.acosClamp = function (cos) {
  95565. if (cos > 1) return 0;
  95566. else if (cos < -1) return OIMO.PI;
  95567. else return OIMO.acos(cos);
  95568. };
  95569. /**
  95570. * A prismatic joint allows only for relative translation of rigid bodies along the axis.
  95571. * @author saharan
  95572. * @author lo-th
  95573. */
  95574. OIMO.PrismaticJoint = function (config, lowerTranslation, upperTranslation) {
  95575. OIMO.Joint.call(this, config);
  95576. this.type = OIMO.JOINT_PRISMATIC;
  95577. // The axis in the first body's coordinate system.
  95578. this.localAxis1 = new OIMO.Vec3().normalize(config.localAxis1);
  95579. // The axis in the second body's coordinate system.
  95580. this.localAxis2 = new OIMO.Vec3().normalize(config.localAxis2);
  95581. this.localAxis1X = this.localAxis1.x;
  95582. this.localAxis1Y = this.localAxis1.y;
  95583. this.localAxis1Z = this.localAxis1.z;
  95584. this.localAxis2X = this.localAxis2.x;
  95585. this.localAxis2Y = this.localAxis2.y;
  95586. this.localAxis2Z = this.localAxis2.z;
  95587. this.nor = new OIMO.Vec3();
  95588. this.tan = new OIMO.Vec3();
  95589. this.bin = new OIMO.Vec3();
  95590. this.ac = new OIMO.AngularConstraint(this, new OIMO.Quat().arc(this.localAxis1, this.localAxis2));
  95591. // The translational limit and motor information of the joint.
  95592. this.limitMotor = new OIMO.LimitMotor(this.nor, true);
  95593. this.limitMotor.lowerLimit = lowerTranslation;
  95594. this.limitMotor.upperLimit = upperTranslation;
  95595. this.t3 = new OIMO.Translational3Constraint(this, this.limitMotor, new OIMO.LimitMotor(this.tan, true), new OIMO.LimitMotor(this.bin, true));
  95596. };
  95597. OIMO.PrismaticJoint.prototype = Object.create(OIMO.Joint.prototype);
  95598. OIMO.PrismaticJoint.prototype.constructor = OIMO.PrismaticJoint;
  95599. OIMO.PrismaticJoint.prototype.preSolve = function (timeStep, invTimeStep) {
  95600. var tmpM;
  95601. var tmp1X;
  95602. var tmp1Y;
  95603. var tmp1Z;
  95604. this.updateAnchorPoints();
  95605. tmpM = this.body1.rotation.elements;
  95606. var axis1X = this.localAxis1X * tmpM[0] + this.localAxis1Y * tmpM[1] + this.localAxis1Z * tmpM[2];
  95607. var axis1Y = this.localAxis1X * tmpM[3] + this.localAxis1Y * tmpM[4] + this.localAxis1Z * tmpM[5];
  95608. var axis1Z = this.localAxis1X * tmpM[6] + this.localAxis1Y * tmpM[7] + this.localAxis1Z * tmpM[8];
  95609. tmpM = this.body2.rotation.elements;
  95610. var axis2X = this.localAxis2X * tmpM[0] + this.localAxis2Y * tmpM[1] + this.localAxis2Z * tmpM[2];
  95611. var axis2Y = this.localAxis2X * tmpM[3] + this.localAxis2Y * tmpM[4] + this.localAxis2Z * tmpM[5];
  95612. var axis2Z = this.localAxis2X * tmpM[6] + this.localAxis2Y * tmpM[7] + this.localAxis2Z * tmpM[8];
  95613. var nx = axis1X * this.body2.inverseMass + axis2X * this.body1.inverseMass;
  95614. var ny = axis1Y * this.body2.inverseMass + axis2Y * this.body1.inverseMass;
  95615. var nz = axis1Z * this.body2.inverseMass + axis2Z * this.body1.inverseMass;
  95616. tmp1X = OIMO.sqrt(nx * nx + ny * ny + nz * nz);
  95617. if (tmp1X > 0) tmp1X = 1 / tmp1X;
  95618. nx *= tmp1X;
  95619. ny *= tmp1X;
  95620. nz *= tmp1X;
  95621. var tx = ny * nx - nz * nz;
  95622. var ty = -nz * ny - nx * nx;
  95623. var tz = nx * nz + ny * ny;
  95624. tmp1X = 1 / OIMO.sqrt(tx * tx + ty * ty + tz * tz);
  95625. tx *= tmp1X;
  95626. ty *= tmp1X;
  95627. tz *= tmp1X;
  95628. var bx = ny * tz - nz * ty;
  95629. var by = nz * tx - nx * tz;
  95630. var bz = nx * ty - ny * tx;
  95631. this.nor.init(nx, ny, nz);
  95632. this.tan.init(tx, ty, tz);
  95633. this.bin.init(bx, by, bz);
  95634. this.ac.preSolve(timeStep, invTimeStep);
  95635. this.t3.preSolve(timeStep, invTimeStep);
  95636. };
  95637. OIMO.PrismaticJoint.prototype.solve = function () {
  95638. this.ac.solve();
  95639. this.t3.solve();
  95640. };
  95641. OIMO.PrismaticJoint.prototype.postSolve = function () {
  95642. };
  95643. /**
  95644. * A slider joint allows for relative translation and relative rotation between two rigid bodies along the axis.
  95645. * @author saharan
  95646. * @author lo-th
  95647. */
  95648. OIMO.SliderJoint = function (config, lowerTranslation, upperTranslation) {
  95649. OIMO.Joint.call(this, config);
  95650. this.type = OIMO.JOINT_SLIDER;
  95651. // The first axis in local coordinate system.
  95652. this.localAxis1 = new OIMO.Vec3().normalize(config.localAxis1);
  95653. // The second axis in local coordinate system.
  95654. this.localAxis2 = new OIMO.Vec3().normalize(config.localAxis2);
  95655. var len;
  95656. this.localAxis1X = this.localAxis1.x;
  95657. this.localAxis1Y = this.localAxis1.y;
  95658. this.localAxis1Z = this.localAxis1.z;
  95659. this.localAngAxis1X = this.localAxis1Y * this.localAxis1X - this.localAxis1Z * this.localAxis1Z;
  95660. this.localAngAxis1Y = -this.localAxis1Z * this.localAxis1Y - this.localAxis1X * this.localAxis1X;
  95661. this.localAngAxis1Z = this.localAxis1X * this.localAxis1Z + this.localAxis1Y * this.localAxis1Y;
  95662. len = 1 / OIMO.sqrt(this.localAngAxis1X * this.localAngAxis1X + this.localAngAxis1Y * this.localAngAxis1Y + this.localAngAxis1Z * this.localAngAxis1Z);
  95663. this.localAngAxis1X *= len;
  95664. this.localAngAxis1Y *= len;
  95665. this.localAngAxis1Z *= len;
  95666. this.localAxis2X = this.localAxis2.x;
  95667. this.localAxis2Y = this.localAxis2.y;
  95668. this.localAxis2Z = this.localAxis2.z;
  95669. // make angle axis 2
  95670. var arc = new OIMO.Mat33().setQuat(new OIMO.Quat().arc(this.localAxis1, this.localAxis2));
  95671. var tarc = arc.elements;
  95672. this.localAngAxis2X = this.localAngAxis1X * tarc[0] + this.localAngAxis1Y * tarc[1] + this.localAngAxis1Z * tarc[2];
  95673. this.localAngAxis2Y = this.localAngAxis1X * tarc[3] + this.localAngAxis1Y * tarc[4] + this.localAngAxis1Z * tarc[5];
  95674. this.localAngAxis2Z = this.localAngAxis1X * tarc[6] + this.localAngAxis1Y * tarc[7] + this.localAngAxis1Z * tarc[8];
  95675. this.nor = new OIMO.Vec3();
  95676. this.tan = new OIMO.Vec3();
  95677. this.bin = new OIMO.Vec3();
  95678. // The limit and motor for the rotation
  95679. this.rotationalLimitMotor = new OIMO.LimitMotor(this.nor, false);
  95680. this.r3 = new OIMO.Rotational3Constraint(this, this.rotationalLimitMotor, new OIMO.LimitMotor(this.tan, true), new OIMO.LimitMotor(this.bin, true));
  95681. // The limit and motor for the translation.
  95682. this.translationalLimitMotor = new OIMO.LimitMotor(this.nor, true);
  95683. this.translationalLimitMotor.lowerLimit = lowerTranslation;
  95684. this.translationalLimitMotor.upperLimit = upperTranslation;
  95685. this.t3 = new OIMO.Translational3Constraint(this, this.translationalLimitMotor, new OIMO.LimitMotor(this.tan, true), new OIMO.LimitMotor(this.bin, true));
  95686. };
  95687. OIMO.SliderJoint.prototype = Object.create(OIMO.Joint.prototype);
  95688. OIMO.SliderJoint.prototype.constructor = OIMO.SliderJoint;
  95689. OIMO.SliderJoint.prototype.preSolve = function (timeStep, invTimeStep) {
  95690. var tmpM;
  95691. var tmp1X;
  95692. var tmp1Y;
  95693. var tmp1Z;
  95694. this.updateAnchorPoints();
  95695. tmpM = this.body1.rotation.elements;
  95696. var axis1X = this.localAxis1X * tmpM[0] + this.localAxis1Y * tmpM[1] + this.localAxis1Z * tmpM[2];
  95697. var axis1Y = this.localAxis1X * tmpM[3] + this.localAxis1Y * tmpM[4] + this.localAxis1Z * tmpM[5];
  95698. var axis1Z = this.localAxis1X * tmpM[6] + this.localAxis1Y * tmpM[7] + this.localAxis1Z * tmpM[8];
  95699. var angAxis1X = this.localAngAxis1X * tmpM[0] + this.localAngAxis1Y * tmpM[1] + this.localAngAxis1Z * tmpM[2];
  95700. var angAxis1Y = this.localAngAxis1X * tmpM[3] + this.localAngAxis1Y * tmpM[4] + this.localAngAxis1Z * tmpM[5];
  95701. var angAxis1Z = this.localAngAxis1X * tmpM[6] + this.localAngAxis1Y * tmpM[7] + this.localAngAxis1Z * tmpM[8];
  95702. tmpM = this.body2.rotation.elements;
  95703. var axis2X = this.localAxis2X * tmpM[0] + this.localAxis2Y * tmpM[1] + this.localAxis2Z * tmpM[2];
  95704. var axis2Y = this.localAxis2X * tmpM[3] + this.localAxis2Y * tmpM[4] + this.localAxis2Z * tmpM[5];
  95705. var axis2Z = this.localAxis2X * tmpM[6] + this.localAxis2Y * tmpM[7] + this.localAxis2Z * tmpM[8];
  95706. var angAxis2X = this.localAngAxis2X * tmpM[0] + this.localAngAxis2Y * tmpM[1] + this.localAngAxis2Z * tmpM[2];
  95707. var angAxis2Y = this.localAngAxis2X * tmpM[3] + this.localAngAxis2Y * tmpM[4] + this.localAngAxis2Z * tmpM[5];
  95708. var angAxis2Z = this.localAngAxis2X * tmpM[6] + this.localAngAxis2Y * tmpM[7] + this.localAngAxis2Z * tmpM[8];
  95709. var nx = axis1X * this.body2.inverseMass + axis2X * this.body1.inverseMass;
  95710. var ny = axis1Y * this.body2.inverseMass + axis2Y * this.body1.inverseMass;
  95711. var nz = axis1Z * this.body2.inverseMass + axis2Z * this.body1.inverseMass;
  95712. tmp1X = OIMO.sqrt(nx * nx + ny * ny + nz * nz);
  95713. if (tmp1X > 0) tmp1X = 1 / tmp1X;
  95714. nx *= tmp1X;
  95715. ny *= tmp1X;
  95716. nz *= tmp1X;
  95717. var tx = ny * nx - nz * nz;
  95718. var ty = -nz * ny - nx * nx;
  95719. var tz = nx * nz + ny * ny;
  95720. tmp1X = 1 / OIMO.sqrt(tx * tx + ty * ty + tz * tz);
  95721. tx *= tmp1X;
  95722. ty *= tmp1X;
  95723. tz *= tmp1X;
  95724. var bx = ny * tz - nz * ty;
  95725. var by = nz * tx - nx * tz;
  95726. var bz = nx * ty - ny * tx;
  95727. this.nor.init(nx, ny, nz);
  95728. this.tan.init(tx, ty, tz);
  95729. this.bin.init(bx, by, bz);
  95730. // ----------------------------------------------
  95731. // calculate hinge angle
  95732. // ----------------------------------------------
  95733. if (
  95734. nx * (angAxis1Y * angAxis2Z - angAxis1Z * angAxis2Y) +
  95735. ny * (angAxis1Z * angAxis2X - angAxis1X * angAxis2Z) +
  95736. nz * (angAxis1X * angAxis2Y - angAxis1Y * angAxis2X) < 0
  95737. ) {
  95738. this.rotationalLimitMotor.angle = -this.acosClamp(angAxis1X * angAxis2X + angAxis1Y * angAxis2Y + angAxis1Z * angAxis2Z);
  95739. } else {
  95740. this.rotationalLimitMotor.angle = this.acosClamp(angAxis1X * angAxis2X + angAxis1Y * angAxis2Y + angAxis1Z * angAxis2Z);
  95741. }
  95742. // angular error
  95743. tmp1X = axis1Y * axis2Z - axis1Z * axis2Y;
  95744. tmp1Y = axis1Z * axis2X - axis1X * axis2Z;
  95745. tmp1Z = axis1X * axis2Y - axis1Y * axis2X;
  95746. this.r3.limitMotor2.angle = tx * tmp1X + ty * tmp1Y + tz * tmp1Z;
  95747. this.r3.limitMotor3.angle = bx * tmp1X + by * tmp1Y + bz * tmp1Z;
  95748. this.r3.preSolve(timeStep, invTimeStep);
  95749. this.t3.preSolve(timeStep, invTimeStep);
  95750. };
  95751. OIMO.SliderJoint.prototype.solve = function () {
  95752. this.r3.solve();
  95753. this.t3.solve();
  95754. };
  95755. OIMO.SliderJoint.prototype.postSolve = function () {
  95756. };
  95757. OIMO.SliderJoint.prototype.acosClamp = function (cos) {
  95758. if (cos > 1) return 0;
  95759. else if (cos < -1) return OIMO.PI;
  95760. else return OIMO.acos(cos);
  95761. };
  95762. /**
  95763. * A wheel joint allows for relative rotation between two rigid bodies along two axes.
  95764. * The wheel joint also allows for relative translation for the suspension.
  95765. * @author saharan
  95766. * @author lo-th
  95767. */
  95768. OIMO.WheelJoint = function (config) {
  95769. OIMO.Joint.call(this, config);
  95770. this.type = OIMO.JOINT_WHEEL;
  95771. // The first axis in local coordinate system.
  95772. this.localAxis1 = new OIMO.Vec3().normalize(config.localAxis1);
  95773. // The second axis in local coordinate system.
  95774. this.localAxis2 = new OIMO.Vec3().normalize(config.localAxis2);
  95775. var len;
  95776. this.localAxis1X = this.localAxis1.x;
  95777. this.localAxis1Y = this.localAxis1.y;
  95778. this.localAxis1Z = this.localAxis1.z;
  95779. this.localAxis2X = this.localAxis2.x;
  95780. this.localAxis2Y = this.localAxis2.y;
  95781. this.localAxis2Z = this.localAxis2.z;
  95782. var dot = this.localAxis1X * this.localAxis2X + this.localAxis1Y * this.localAxis2Y + this.localAxis1Z * this.localAxis2Z;
  95783. if (dot > -1 && dot < 1) {
  95784. this.localAngAxis1X = this.localAxis2X - dot * this.localAxis1X;
  95785. this.localAngAxis1Y = this.localAxis2Y - dot * this.localAxis1Y;
  95786. this.localAngAxis1Z = this.localAxis2Z - dot * this.localAxis1Z;
  95787. this.localAngAxis2X = this.localAxis1X - dot * this.localAxis2X;
  95788. this.localAngAxis2Y = this.localAxis1Y - dot * this.localAxis2Y;
  95789. this.localAngAxis2Z = this.localAxis1Z - dot * this.localAxis2Z;
  95790. len = 1 / OIMO.sqrt(this.localAngAxis1X * this.localAngAxis1X + this.localAngAxis1Y * this.localAngAxis1Y + this.localAngAxis1Z * this.localAngAxis1Z);
  95791. this.localAngAxis1X *= len;
  95792. this.localAngAxis1Y *= len;
  95793. this.localAngAxis1Z *= len;
  95794. len = 1 / OIMO.sqrt(this.localAngAxis2X * this.localAngAxis2X + this.localAngAxis2Y * this.localAngAxis2Y + this.localAngAxis2Z * this.localAngAxis2Z);
  95795. this.localAngAxis2X *= len;
  95796. this.localAngAxis2Y *= len;
  95797. this.localAngAxis2Z *= len;
  95798. } else {
  95799. this.localAngAxis1X = this.localAxis1Y * this.localAxis1X - this.localAxis1Z * this.localAxis1Z;
  95800. this.localAngAxis1Y = -this.localAxis1Z * this.localAxis1Y - this.localAxis1X * this.localAxis1X;
  95801. this.localAngAxis1Z = this.localAxis1X * this.localAxis1Z + this.localAxis1Y * this.localAxis1Y;
  95802. len = 1 / OIMO.sqrt(this.localAngAxis1X * this.localAngAxis1X + this.localAngAxis1Y * this.localAngAxis1Y + this.localAngAxis1Z * this.localAngAxis1Z);
  95803. this.localAngAxis1X *= len;
  95804. this.localAngAxis1Y *= len;
  95805. this.localAngAxis1Z *= len;
  95806. var arc = new OIMO.Mat33().setQuat(new OIMO.Quat().arc(this.localAxis1, this.localAxis2));
  95807. var tarc = arc.elements;
  95808. this.localAngAxis2X = this.localAngAxis1X * tarc[0] + this.localAngAxis1Y * tarc[1] + this.localAngAxis1Z * tarc[2];
  95809. this.localAngAxis2Y = this.localAngAxis1X * tarc[3] + this.localAngAxis1Y * tarc[4] + this.localAngAxis1Z * tarc[5];
  95810. this.localAngAxis2Z = this.localAngAxis1X * tarc[6] + this.localAngAxis1Y * tarc[7] + this.localAngAxis1Z * tarc[8];
  95811. }
  95812. this.nor = new OIMO.Vec3();
  95813. this.tan = new OIMO.Vec3();
  95814. this.bin = new OIMO.Vec3();
  95815. // The translational limit and motor information of the joint.
  95816. this.translationalLimitMotor = new OIMO.LimitMotor(this.tan, true);
  95817. this.translationalLimitMotor.frequency = 8;
  95818. this.translationalLimitMotor.dampingRatio = 1;
  95819. // The first rotational limit and motor information of the joint.
  95820. this.rotationalLimitMotor1 = new OIMO.LimitMotor(this.tan, false);
  95821. // The second rotational limit and motor information of the joint.
  95822. this.rotationalLimitMotor2 = new OIMO.LimitMotor(this.bin, false);
  95823. this.t3 = new OIMO.Translational3Constraint(this, new OIMO.LimitMotor(this.nor, true), this.translationalLimitMotor, new OIMO.LimitMotor(this.bin, true));
  95824. this.t3.weight = 1;
  95825. this.r3 = new OIMO.Rotational3Constraint(this, new OIMO.LimitMotor(this.nor, true), this.rotationalLimitMotor1, this.rotationalLimitMotor2);
  95826. };
  95827. OIMO.WheelJoint.prototype = Object.create(OIMO.Joint.prototype);
  95828. OIMO.WheelJoint.prototype.constructor = OIMO.WheelJoint;
  95829. OIMO.WheelJoint.prototype.preSolve = function (timeStep, invTimeStep) {
  95830. var tmpM;
  95831. var tmp1X;
  95832. var tmp1Y;
  95833. var tmp1Z;
  95834. this.updateAnchorPoints();
  95835. tmpM = this.body1.rotation.elements;
  95836. var x1 = this.localAxis1X * tmpM[0] + this.localAxis1Y * tmpM[1] + this.localAxis1Z * tmpM[2];
  95837. var y1 = this.localAxis1X * tmpM[3] + this.localAxis1Y * tmpM[4] + this.localAxis1Z * tmpM[5];
  95838. var z1 = this.localAxis1X * tmpM[6] + this.localAxis1Y * tmpM[7] + this.localAxis1Z * tmpM[8];
  95839. var angAxis1X = this.localAngAxis1X * tmpM[0] + this.localAngAxis1Y * tmpM[1] + this.localAngAxis1Z * tmpM[2];
  95840. var angAxis1Y = this.localAngAxis1X * tmpM[3] + this.localAngAxis1Y * tmpM[4] + this.localAngAxis1Z * tmpM[5];
  95841. var angAxis1Z = this.localAngAxis1X * tmpM[6] + this.localAngAxis1Y * tmpM[7] + this.localAngAxis1Z * tmpM[8];
  95842. tmpM = this.body2.rotation.elements;
  95843. var x2 = this.localAxis2X * tmpM[0] + this.localAxis2Y * tmpM[1] + this.localAxis2Z * tmpM[2];
  95844. var y2 = this.localAxis2X * tmpM[3] + this.localAxis2Y * tmpM[4] + this.localAxis2Z * tmpM[5];
  95845. var z2 = this.localAxis2X * tmpM[6] + this.localAxis2Y * tmpM[7] + this.localAxis2Z * tmpM[8];
  95846. var angAxis2X = this.localAngAxis2X * tmpM[0] + this.localAngAxis2Y * tmpM[1] + this.localAngAxis2Z * tmpM[2];
  95847. var angAxis2Y = this.localAngAxis2X * tmpM[3] + this.localAngAxis2Y * tmpM[4] + this.localAngAxis2Z * tmpM[5];
  95848. var angAxis2Z = this.localAngAxis2X * tmpM[6] + this.localAngAxis2Y * tmpM[7] + this.localAngAxis2Z * tmpM[8];
  95849. this.r3.limitMotor1.angle = x1 * x2 + y1 * y2 + z1 * z2;
  95850. if (x1 * (angAxis1Y * z2 - angAxis1Z * y2) + y1 * (angAxis1Z * x2 - angAxis1X * z2) + z1 * (angAxis1X * y2 - angAxis1Y * x2) < 0) {
  95851. this.rotationalLimitMotor1.angle = -this.acosClamp(angAxis1X * x2 + angAxis1Y * y2 + angAxis1Z * z2);
  95852. } else {
  95853. this.rotationalLimitMotor1.angle = this.acosClamp(angAxis1X * x2 + angAxis1Y * y2 + angAxis1Z * z2);
  95854. }
  95855. if (x2 * (angAxis2Y * z1 - angAxis2Z * y1) + y2 * (angAxis2Z * x1 - angAxis2X * z1) + z2 * (angAxis2X * y1 - angAxis2Y * x1) < 0) {
  95856. this.rotationalLimitMotor2.angle = this.acosClamp(angAxis2X * x1 + angAxis2Y * y1 + angAxis2Z * z1);
  95857. } else {
  95858. this.rotationalLimitMotor2.angle = -this.acosClamp(angAxis2X * x1 + angAxis2Y * y1 + angAxis2Z * z1);
  95859. }
  95860. var nx = y2 * z1 - z2 * y1;
  95861. var ny = z2 * x1 - x2 * z1;
  95862. var nz = x2 * y1 - y2 * x1;
  95863. tmp1X = OIMO.sqrt(nx * nx + ny * ny + nz * nz);
  95864. if (tmp1X > 0) tmp1X = 1 / tmp1X;
  95865. nx *= tmp1X;
  95866. ny *= tmp1X;
  95867. nz *= tmp1X;
  95868. var tx = ny * z2 - nz * y2;
  95869. var ty = nz * x2 - nx * z2;
  95870. var tz = nx * y2 - ny * x2;
  95871. tmp1X = OIMO.sqrt(tx * tx + ty * ty + tz * tz);
  95872. if (tmp1X > 0) tmp1X = 1 / tmp1X;
  95873. tx *= tmp1X;
  95874. ty *= tmp1X;
  95875. tz *= tmp1X;
  95876. var bx = y1 * nz - z1 * ny;
  95877. var by = z1 * nx - x1 * nz;
  95878. var bz = x1 * ny - y1 * nx;
  95879. tmp1X = OIMO.sqrt(bx * bx + by * by + bz * bz);
  95880. if (tmp1X > 0) tmp1X = 1 / tmp1X;
  95881. bx *= tmp1X;
  95882. by *= tmp1X;
  95883. bz *= tmp1X;
  95884. this.nor.init(nx, ny, nz);
  95885. this.tan.init(tx, ty, tz);
  95886. this.bin.init(bx, by, bz);
  95887. this.r3.preSolve(timeStep, invTimeStep);
  95888. this.t3.preSolve(timeStep, invTimeStep);
  95889. };
  95890. OIMO.WheelJoint.prototype.solve = function () {
  95891. this.r3.solve();
  95892. this.t3.solve();
  95893. };
  95894. OIMO.WheelJoint.prototype.postSolve = function () {
  95895. };
  95896. OIMO.WheelJoint.prototype.acosClamp = function (cos) {
  95897. if (cos > 1) return 0;
  95898. else if (cos < -1) return OIMO.PI;
  95899. else return OIMO.acos(cos);
  95900. };
  95901. /**
  95902. * An angular constraint for all axes for various joints.
  95903. * @author saharan
  95904. */
  95905. OIMO.AngularConstraint = function (joint, targetOrientation) {
  95906. this.joint = joint;
  95907. this.targetOrientation = new OIMO.Quat().invert(targetOrientation);
  95908. this.relativeOrientation = new OIMO.Quat();
  95909. this.ii1 = null;
  95910. this.ii2 = null;
  95911. this.dd = null;
  95912. this.vel = new OIMO.Vec3();
  95913. this.imp = new OIMO.Vec3();
  95914. this.rn0 = new OIMO.Vec3();
  95915. this.rn1 = new OIMO.Vec3();
  95916. this.rn2 = new OIMO.Vec3();
  95917. this.b1 = joint.body1;
  95918. this.b2 = joint.body2;
  95919. this.a1 = this.b1.angularVelocity;
  95920. this.a2 = this.b2.angularVelocity;
  95921. this.i1 = this.b1.inverseInertia;
  95922. this.i2 = this.b2.inverseInertia;
  95923. };
  95924. OIMO.AngularConstraint.prototype = {
  95925. constructor: OIMO.AngularConstraint,
  95926. preSolve: function (timeStep, invTimeStep) {
  95927. var inv, len, v, vv;
  95928. this.ii1 = this.i1.clone();
  95929. this.ii2 = this.i2.clone();
  95930. v = new OIMO.Mat33().add(this.ii1, this.ii2).elements;
  95931. inv = 1 / (v[0] * (v[4] * v[8] - v[7] * v[5]) + v[3] * (v[7] * v[2] - v[1] * v[8]) + v[6] * (v[1] * v[5] - v[4] * v[2]));
  95932. this.dd = new OIMO.Mat33(
  95933. v[4] * v[8] - v[5] * v[7], v[2] * v[7] - v[1] * v[8], v[1] * v[5] - v[2] * v[4],
  95934. v[5] * v[6] - v[3] * v[8], v[0] * v[8] - v[2] * v[6], v[2] * v[3] - v[0] * v[5],
  95935. v[3] * v[7] - v[4] * v[6], v[1] * v[6] - v[0] * v[7], v[0] * v[4] - v[1] * v[3]
  95936. ).multiply(inv);
  95937. this.relativeOrientation.invert(this.b1.orientation);
  95938. this.relativeOrientation.mul(this.targetOrientation, this.relativeOrientation);
  95939. this.relativeOrientation.mul(this.b2.orientation, this.relativeOrientation);
  95940. inv = this.relativeOrientation.s * 2;
  95941. this.vel.scale(this.relativeOrientation, inv);
  95942. len = this.vel.length();
  95943. if (len > 0.02) {
  95944. len = (0.02 - len) / len * invTimeStep * 0.05;
  95945. this.vel.scaleEqual(len);
  95946. } else {
  95947. this.vel.init();
  95948. }
  95949. this.rn1.mulMat(this.ii1, this.imp);
  95950. this.rn2.mulMat(this.ii2, this.imp);
  95951. this.a1.addEqual(this.rn1);
  95952. this.a2.subEqual(this.rn2);
  95953. },
  95954. solve: function () {
  95955. var r = this.a2.clone().subEqual(this.a1).subEqual(this.vel);
  95956. this.rn0.mulMat(this.dd, r);
  95957. this.rn1.mulMat(this.ii1, this.rn0);
  95958. this.rn2.mulMat(this.ii2, this.rn0);
  95959. this.imp.addEqual(this.rn0);
  95960. this.a1.addEqual(this.rn1);
  95961. this.a2.subEqual(this.rn2);
  95962. }
  95963. };
  95964. /**
  95965. * A linear constraint for all axes for various joints.
  95966. * @author saharan
  95967. */
  95968. OIMO.LinearConstraint = function (joint) {
  95969. this.m1 = NaN;
  95970. this.m2 = NaN;
  95971. this.ii1 = null;
  95972. this.ii2 = null;
  95973. this.dd = null;
  95974. this.r1x = NaN;
  95975. this.r1y = NaN;
  95976. this.r1z = NaN;
  95977. this.r2x = NaN;
  95978. this.r2y = NaN;
  95979. this.r2z = NaN;
  95980. this.ax1x = NaN;
  95981. this.ax1y = NaN;
  95982. this.ax1z = NaN;
  95983. this.ay1x = NaN;
  95984. this.ay1y = NaN;
  95985. this.ay1z = NaN;
  95986. this.az1x = NaN;
  95987. this.az1y = NaN;
  95988. this.az1z = NaN;
  95989. this.ax2x = NaN;
  95990. this.ax2y = NaN;
  95991. this.ax2z = NaN;
  95992. this.ay2x = NaN;
  95993. this.ay2y = NaN;
  95994. this.ay2z = NaN;
  95995. this.az2x = NaN;
  95996. this.az2y = NaN;
  95997. this.az2z = NaN;
  95998. this.vel = NaN;
  95999. this.velx = NaN;
  96000. this.vely = NaN;
  96001. this.velz = NaN;
  96002. this.joint = joint;
  96003. this.r1 = joint.relativeAnchorPoint1;
  96004. this.r2 = joint.relativeAnchorPoint2;
  96005. this.p1 = joint.anchorPoint1;
  96006. this.p2 = joint.anchorPoint2;
  96007. this.b1 = joint.body1;
  96008. this.b2 = joint.body2;
  96009. this.l1 = this.b1.linearVelocity;
  96010. this.l2 = this.b2.linearVelocity;
  96011. this.a1 = this.b1.angularVelocity;
  96012. this.a2 = this.b2.angularVelocity;
  96013. this.i1 = this.b1.inverseInertia;
  96014. this.i2 = this.b2.inverseInertia;
  96015. this.impx = 0;
  96016. this.impy = 0;
  96017. this.impz = 0;
  96018. }
  96019. OIMO.LinearConstraint.prototype = {
  96020. constructor: OIMO.LinearConstraint,
  96021. preSolve: function (timeStep, invTimeStep) {
  96022. this.r1x = this.r1.x;
  96023. this.r1y = this.r1.y;
  96024. this.r1z = this.r1.z;
  96025. this.r2x = this.r2.x;
  96026. this.r2y = this.r2.y;
  96027. this.r2z = this.r2.z;
  96028. this.m1 = this.b1.inverseMass;
  96029. this.m2 = this.b2.inverseMass;
  96030. this.ii1 = this.i1.clone();
  96031. this.ii2 = this.i2.clone();
  96032. var ii1 = this.ii1.elements;
  96033. var ii2 = this.ii2.elements;
  96034. this.ax1x = this.r1z * ii1[1] + -this.r1y * ii1[2];
  96035. this.ax1y = this.r1z * ii1[4] + -this.r1y * ii1[5];
  96036. this.ax1z = this.r1z * ii1[7] + -this.r1y * ii1[8];
  96037. this.ay1x = -this.r1z * ii1[0] + this.r1x * ii1[2];
  96038. this.ay1y = -this.r1z * ii1[3] + this.r1x * ii1[5];
  96039. this.ay1z = -this.r1z * ii1[6] + this.r1x * ii1[8];
  96040. this.az1x = this.r1y * ii1[0] + -this.r1x * ii1[1];
  96041. this.az1y = this.r1y * ii1[3] + -this.r1x * ii1[4];
  96042. this.az1z = this.r1y * ii1[6] + -this.r1x * ii1[7];
  96043. this.ax2x = this.r2z * ii2[1] + -this.r2y * ii2[2];
  96044. this.ax2y = this.r2z * ii2[4] + -this.r2y * ii2[5];
  96045. this.ax2z = this.r2z * ii2[7] + -this.r2y * ii2[8];
  96046. this.ay2x = -this.r2z * ii2[0] + this.r2x * ii2[2];
  96047. this.ay2y = -this.r2z * ii2[3] + this.r2x * ii2[5];
  96048. this.ay2z = -this.r2z * ii2[6] + this.r2x * ii2[8];
  96049. this.az2x = this.r2y * ii2[0] + -this.r2x * ii2[1];
  96050. this.az2y = this.r2y * ii2[3] + -this.r2x * ii2[4];
  96051. this.az2z = this.r2y * ii2[6] + -this.r2x * ii2[7];
  96052. // calculate point-to-point mass matrix
  96053. // from impulse equation
  96054. //
  96055. // M = ([/m] - [r^][/I][r^]) ^ -1
  96056. //
  96057. // where
  96058. //
  96059. // [/m] = |1/m, 0, 0|
  96060. // |0, 1/m, 0|
  96061. // |0, 0, 1/m|
  96062. //
  96063. // [r^] = |0, -rz, ry|
  96064. // |rz, 0, -rx|
  96065. // |-ry, rx, 0|
  96066. //
  96067. // [/I] = Inverted moment inertia
  96068. var rxx = this.m1 + this.m2;
  96069. var kk = new OIMO.Mat33(rxx, 0, 0, 0, rxx, 0, 0, 0, rxx);
  96070. var k = kk.elements;
  96071. k[0] += ii1[4] * this.r1z * this.r1z - (ii1[7] + ii1[5]) * this.r1y * this.r1z + ii1[8] * this.r1y * this.r1y;
  96072. k[1] += (ii1[6] * this.r1y + ii1[5] * this.r1x) * this.r1z - ii1[3] * this.r1z * this.r1z - ii1[8] * this.r1x * this.r1y;
  96073. k[2] += (ii1[3] * this.r1y - ii1[4] * this.r1x) * this.r1z - ii1[6] * this.r1y * this.r1y + ii1[7] * this.r1x * this.r1y;
  96074. k[3] += (ii1[2] * this.r1y + ii1[7] * this.r1x) * this.r1z - ii1[1] * this.r1z * this.r1z - ii1[8] * this.r1x * this.r1y;
  96075. k[4] += ii1[0] * this.r1z * this.r1z - (ii1[6] + ii1[2]) * this.r1x * this.r1z + ii1[8] * this.r1x * this.r1x;
  96076. k[5] += (ii1[1] * this.r1x - ii1[0] * this.r1y) * this.r1z - ii1[7] * this.r1x * this.r1x + ii1[6] * this.r1x * this.r1y;
  96077. k[6] += (ii1[1] * this.r1y - ii1[4] * this.r1x) * this.r1z - ii1[2] * this.r1y * this.r1y + ii1[5] * this.r1x * this.r1y;
  96078. k[7] += (ii1[3] * this.r1x - ii1[0] * this.r1y) * this.r1z - ii1[5] * this.r1x * this.r1x + ii1[2] * this.r1x * this.r1y;
  96079. k[8] += ii1[0] * this.r1y * this.r1y - (ii1[3] + ii1[1]) * this.r1x * this.r1y + ii1[4] * this.r1x * this.r1x;
  96080. k[0] += ii2[4] * this.r2z * this.r2z - (ii2[7] + ii2[5]) * this.r2y * this.r2z + ii2[8] * this.r2y * this.r2y;
  96081. k[1] += (ii2[6] * this.r2y + ii2[5] * this.r2x) * this.r2z - ii2[3] * this.r2z * this.r2z - ii2[8] * this.r2x * this.r2y;
  96082. k[2] += (ii2[3] * this.r2y - ii2[4] * this.r2x) * this.r2z - ii2[6] * this.r2y * this.r2y + ii2[7] * this.r2x * this.r2y;
  96083. k[3] += (ii2[2] * this.r2y + ii2[7] * this.r2x) * this.r2z - ii2[1] * this.r2z * this.r2z - ii2[8] * this.r2x * this.r2y;
  96084. k[4] += ii2[0] * this.r2z * this.r2z - (ii2[6] + ii2[2]) * this.r2x * this.r2z + ii2[8] * this.r2x * this.r2x;
  96085. k[5] += (ii2[1] * this.r2x - ii2[0] * this.r2y) * this.r2z - ii2[7] * this.r2x * this.r2x + ii2[6] * this.r2x * this.r2y;
  96086. k[6] += (ii2[1] * this.r2y - ii2[4] * this.r2x) * this.r2z - ii2[2] * this.r2y * this.r2y + ii2[5] * this.r2x * this.r2y;
  96087. k[7] += (ii2[3] * this.r2x - ii2[0] * this.r2y) * this.r2z - ii2[5] * this.r2x * this.r2x + ii2[2] * this.r2x * this.r2y;
  96088. k[8] += ii2[0] * this.r2y * this.r2y - (ii2[3] + ii2[1]) * this.r2x * this.r2y + ii2[4] * this.r2x * this.r2x;
  96089. var inv = 1 / (k[0] * (k[4] * k[8] - k[7] * k[5]) + k[3] * (k[7] * k[2] - k[1] * k[8]) + k[6] * (k[1] * k[5] - k[4] * k[2]));
  96090. this.dd = new OIMO.Mat33(
  96091. k[4] * k[8] - k[5] * k[7], k[2] * k[7] - k[1] * k[8], k[1] * k[5] - k[2] * k[4],
  96092. k[5] * k[6] - k[3] * k[8], k[0] * k[8] - k[2] * k[6], k[2] * k[3] - k[0] * k[5],
  96093. k[3] * k[7] - k[4] * k[6], k[1] * k[6] - k[0] * k[7], k[0] * k[4] - k[1] * k[3]
  96094. ).multiply(inv);
  96095. this.velx = this.p2.x - this.p1.x;
  96096. this.vely = this.p2.y - this.p1.y;
  96097. this.velz = this.p2.z - this.p1.z;
  96098. var len = OIMO.sqrt(this.velx * this.velx + this.vely * this.vely + this.velz * this.velz);
  96099. if (len > 0.005) {
  96100. len = (0.005 - len) / len * invTimeStep * 0.05;
  96101. this.velx *= len;
  96102. this.vely *= len;
  96103. this.velz *= len;
  96104. } else {
  96105. this.velx = 0;
  96106. this.vely = 0;
  96107. this.velz = 0;
  96108. }
  96109. this.impx *= 0.95;
  96110. this.impy *= 0.95;
  96111. this.impz *= 0.95;
  96112. this.l1.x += this.impx * this.m1;
  96113. this.l1.y += this.impy * this.m1;
  96114. this.l1.z += this.impz * this.m1;
  96115. this.a1.x += this.impx * this.ax1x + this.impy * this.ay1x + this.impz * this.az1x;
  96116. this.a1.y += this.impx * this.ax1y + this.impy * this.ay1y + this.impz * this.az1y;
  96117. this.a1.z += this.impx * this.ax1z + this.impy * this.ay1z + this.impz * this.az1z;
  96118. this.l2.x -= this.impx * this.m2;
  96119. this.l2.y -= this.impy * this.m2;
  96120. this.l2.z -= this.impz * this.m2;
  96121. this.a2.x -= this.impx * this.ax2x + this.impy * this.ay2x + this.impz * this.az2x;
  96122. this.a2.y -= this.impx * this.ax2y + this.impy * this.ay2y + this.impz * this.az2y;
  96123. this.a2.z -= this.impx * this.ax2z + this.impy * this.ay2z + this.impz * this.az2z;
  96124. },
  96125. solve: function () {
  96126. var d = this.dd.elements;
  96127. var rvx = this.l2.x - this.l1.x + this.a2.y * this.r2z - this.a2.z * this.r2y - this.a1.y * this.r1z + this.a1.z * this.r1y - this.velx;
  96128. var rvy = this.l2.y - this.l1.y + this.a2.z * this.r2x - this.a2.x * this.r2z - this.a1.z * this.r1x + this.a1.x * this.r1z - this.vely;
  96129. var rvz = this.l2.z - this.l1.z + this.a2.x * this.r2y - this.a2.y * this.r2x - this.a1.x * this.r1y + this.a1.y * this.r1x - this.velz;
  96130. var nimpx = rvx * d[0] + rvy * d[1] + rvz * d[2];
  96131. var nimpy = rvx * d[3] + rvy * d[4] + rvz * d[5];
  96132. var nimpz = rvx * d[6] + rvy * d[7] + rvz * d[8];
  96133. this.impx += nimpx;
  96134. this.impy += nimpy;
  96135. this.impz += nimpz;
  96136. this.l1.x += nimpx * this.m1;
  96137. this.l1.y += nimpy * this.m1;
  96138. this.l1.z += nimpz * this.m1;
  96139. this.a1.x += nimpx * this.ax1x + nimpy * this.ay1x + nimpz * this.az1x;
  96140. this.a1.y += nimpx * this.ax1y + nimpy * this.ay1y + nimpz * this.az1y;
  96141. this.a1.z += nimpx * this.ax1z + nimpy * this.ay1z + nimpz * this.az1z;
  96142. this.l2.x -= nimpx * this.m2;
  96143. this.l2.y -= nimpy * this.m2;
  96144. this.l2.z -= nimpz * this.m2;
  96145. this.a2.x -= nimpx * this.ax2x + nimpy * this.ay2x + nimpz * this.az2x;
  96146. this.a2.y -= nimpx * this.ax2y + nimpy * this.ay2y + nimpz * this.az2y;
  96147. this.a2.z -= nimpx * this.ax2z + nimpy * this.ay2z + nimpz * this.az2z;
  96148. }
  96149. }
  96150. /**
  96151. * A three-axis rotational constraint for various joints.
  96152. * @author saharan
  96153. */
  96154. OIMO.Rotational3Constraint = function (joint, limitMotor1, limitMotor2, limitMotor3) {
  96155. this.cfm1 = NaN;
  96156. this.cfm2 = NaN;
  96157. this.cfm3 = NaN;
  96158. this.i1e00 = NaN;
  96159. this.i1e01 = NaN;
  96160. this.i1e02 = NaN;
  96161. this.i1e10 = NaN;
  96162. this.i1e11 = NaN;
  96163. this.i1e12 = NaN;
  96164. this.i1e20 = NaN;
  96165. this.i1e21 = NaN;
  96166. this.i1e22 = NaN;
  96167. this.i2e00 = NaN;
  96168. this.i2e01 = NaN;
  96169. this.i2e02 = NaN;
  96170. this.i2e10 = NaN;
  96171. this.i2e11 = NaN;
  96172. this.i2e12 = NaN;
  96173. this.i2e20 = NaN;
  96174. this.i2e21 = NaN;
  96175. this.i2e22 = NaN;
  96176. this.ax1 = NaN;
  96177. this.ay1 = NaN;
  96178. this.az1 = NaN;
  96179. this.ax2 = NaN;
  96180. this.ay2 = NaN;
  96181. this.az2 = NaN;
  96182. this.ax3 = NaN;
  96183. this.ay3 = NaN;
  96184. this.az3 = NaN;
  96185. this.a1x1 = NaN; // jacoians
  96186. this.a1y1 = NaN;
  96187. this.a1z1 = NaN;
  96188. this.a2x1 = NaN;
  96189. this.a2y1 = NaN;
  96190. this.a2z1 = NaN;
  96191. this.a1x2 = NaN;
  96192. this.a1y2 = NaN;
  96193. this.a1z2 = NaN;
  96194. this.a2x2 = NaN;
  96195. this.a2y2 = NaN;
  96196. this.a2z2 = NaN;
  96197. this.a1x3 = NaN;
  96198. this.a1y3 = NaN;
  96199. this.a1z3 = NaN;
  96200. this.a2x3 = NaN;
  96201. this.a2y3 = NaN;
  96202. this.a2z3 = NaN;
  96203. this.lowerLimit1 = NaN;
  96204. this.upperLimit1 = NaN;
  96205. this.limitVelocity1 = NaN;
  96206. this.limitState1 = 0; // -1: at lower, 0: locked, 1: at upper, 2: free
  96207. this.enableMotor1 = false;
  96208. this.motorSpeed1 = NaN;
  96209. this.maxMotorForce1 = NaN;
  96210. this.maxMotorImpulse1 = NaN;
  96211. this.lowerLimit2 = NaN;
  96212. this.upperLimit2 = NaN;
  96213. this.limitVelocity2 = NaN;
  96214. this.limitState2 = 0; // -1: at lower, 0: locked, 1: at upper, 2: free
  96215. this.enableMotor2 = false;
  96216. this.motorSpeed2 = NaN;
  96217. this.maxMotorForce2 = NaN;
  96218. this.maxMotorImpulse2 = NaN;
  96219. this.lowerLimit3 = NaN;
  96220. this.upperLimit3 = NaN;
  96221. this.limitVelocity3 = NaN;
  96222. this.limitState3 = 0; // -1: at lower, 0: locked, 1: at upper, 2: free
  96223. this.enableMotor3 = false;
  96224. this.motorSpeed3 = NaN;
  96225. this.maxMotorForce3 = NaN;
  96226. this.maxMotorImpulse3 = NaN;
  96227. this.k00 = NaN; // K = J*M*JT
  96228. this.k01 = NaN;
  96229. this.k02 = NaN;
  96230. this.k10 = NaN;
  96231. this.k11 = NaN;
  96232. this.k12 = NaN;
  96233. this.k20 = NaN;
  96234. this.k21 = NaN;
  96235. this.k22 = NaN;
  96236. this.kv00 = NaN; // diagonals without CFMs
  96237. this.kv11 = NaN;
  96238. this.kv22 = NaN;
  96239. this.dv00 = NaN; // ...inverted
  96240. this.dv11 = NaN;
  96241. this.dv22 = NaN;
  96242. this.d00 = NaN; // K^-1
  96243. this.d01 = NaN;
  96244. this.d02 = NaN;
  96245. this.d10 = NaN;
  96246. this.d11 = NaN;
  96247. this.d12 = NaN;
  96248. this.d20 = NaN;
  96249. this.d21 = NaN;
  96250. this.d22 = NaN;
  96251. this.limitMotor1 = limitMotor1;
  96252. this.limitMotor2 = limitMotor2;
  96253. this.limitMotor3 = limitMotor3;
  96254. this.b1 = joint.body1;
  96255. this.b2 = joint.body2;
  96256. this.a1 = this.b1.angularVelocity;
  96257. this.a2 = this.b2.angularVelocity;
  96258. this.i1 = this.b1.inverseInertia;
  96259. this.i2 = this.b2.inverseInertia;
  96260. this.limitImpulse1 = 0;
  96261. this.motorImpulse1 = 0;
  96262. this.limitImpulse2 = 0;
  96263. this.motorImpulse2 = 0;
  96264. this.limitImpulse3 = 0;
  96265. this.motorImpulse3 = 0;
  96266. }
  96267. OIMO.Rotational3Constraint.prototype = {
  96268. constructor: OIMO.Rotational3Constraint,
  96269. preSolve: function (timeStep, invTimeStep) {
  96270. this.ax1 = this.limitMotor1.axis.x;
  96271. this.ay1 = this.limitMotor1.axis.y;
  96272. this.az1 = this.limitMotor1.axis.z;
  96273. this.ax2 = this.limitMotor2.axis.x;
  96274. this.ay2 = this.limitMotor2.axis.y;
  96275. this.az2 = this.limitMotor2.axis.z;
  96276. this.ax3 = this.limitMotor3.axis.x;
  96277. this.ay3 = this.limitMotor3.axis.y;
  96278. this.az3 = this.limitMotor3.axis.z;
  96279. this.lowerLimit1 = this.limitMotor1.lowerLimit;
  96280. this.upperLimit1 = this.limitMotor1.upperLimit;
  96281. this.motorSpeed1 = this.limitMotor1.motorSpeed;
  96282. this.maxMotorForce1 = this.limitMotor1.maxMotorForce;
  96283. this.enableMotor1 = this.maxMotorForce1 > 0;
  96284. this.lowerLimit2 = this.limitMotor2.lowerLimit;
  96285. this.upperLimit2 = this.limitMotor2.upperLimit;
  96286. this.motorSpeed2 = this.limitMotor2.motorSpeed;
  96287. this.maxMotorForce2 = this.limitMotor2.maxMotorForce;
  96288. this.enableMotor2 = this.maxMotorForce2 > 0;
  96289. this.lowerLimit3 = this.limitMotor3.lowerLimit;
  96290. this.upperLimit3 = this.limitMotor3.upperLimit;
  96291. this.motorSpeed3 = this.limitMotor3.motorSpeed;
  96292. this.maxMotorForce3 = this.limitMotor3.maxMotorForce;
  96293. this.enableMotor3 = this.maxMotorForce3 > 0;
  96294. var ti1 = this.i1.elements;
  96295. var ti2 = this.i2.elements;
  96296. this.i1e00 = ti1[0];
  96297. this.i1e01 = ti1[1];
  96298. this.i1e02 = ti1[2];
  96299. this.i1e10 = ti1[3];
  96300. this.i1e11 = ti1[4];
  96301. this.i1e12 = ti1[5];
  96302. this.i1e20 = ti1[6];
  96303. this.i1e21 = ti1[7];
  96304. this.i1e22 = ti1[8];
  96305. this.i2e00 = ti2[0];
  96306. this.i2e01 = ti2[1];
  96307. this.i2e02 = ti2[2];
  96308. this.i2e10 = ti2[3];
  96309. this.i2e11 = ti2[4];
  96310. this.i2e12 = ti2[5];
  96311. this.i2e20 = ti2[6];
  96312. this.i2e21 = ti2[7];
  96313. this.i2e22 = ti2[8];
  96314. var frequency1 = this.limitMotor1.frequency;
  96315. var frequency2 = this.limitMotor2.frequency;
  96316. var frequency3 = this.limitMotor3.frequency;
  96317. var enableSpring1 = frequency1 > 0;
  96318. var enableSpring2 = frequency2 > 0;
  96319. var enableSpring3 = frequency3 > 0;
  96320. var enableLimit1 = this.lowerLimit1 <= this.upperLimit1;
  96321. var enableLimit2 = this.lowerLimit2 <= this.upperLimit2;
  96322. var enableLimit3 = this.lowerLimit3 <= this.upperLimit3;
  96323. var angle1 = this.limitMotor1.angle;
  96324. if (enableLimit1) {
  96325. if (this.lowerLimit1 == this.upperLimit1) {
  96326. if (this.limitState1 != 0) {
  96327. this.limitState1 = 0;
  96328. this.limitImpulse1 = 0;
  96329. }
  96330. this.limitVelocity1 = this.lowerLimit1 - angle1;
  96331. } else if (angle1 < this.lowerLimit1) {
  96332. if (this.limitState1 != -1) {
  96333. this.limitState1 = -1;
  96334. this.limitImpulse1 = 0;
  96335. }
  96336. this.limitVelocity1 = this.lowerLimit1 - angle1;
  96337. } else if (angle1 > this.upperLimit1) {
  96338. if (this.limitState1 != 1) {
  96339. this.limitState1 = 1;
  96340. this.limitImpulse1 = 0;
  96341. }
  96342. this.limitVelocity1 = this.upperLimit1 - angle1;
  96343. } else {
  96344. this.limitState1 = 2;
  96345. this.limitImpulse1 = 0;
  96346. this.limitVelocity1 = 0;
  96347. }
  96348. if (!enableSpring1) {
  96349. if (this.limitVelocity1 > 0.02) this.limitVelocity1 -= 0.02;
  96350. else if (this.limitVelocity1 < -0.02) this.limitVelocity1 += 0.02;
  96351. else this.limitVelocity1 = 0;
  96352. }
  96353. } else {
  96354. this.limitState1 = 2;
  96355. this.limitImpulse1 = 0;
  96356. }
  96357. var angle2 = this.limitMotor2.angle;
  96358. if (enableLimit2) {
  96359. if (this.lowerLimit2 == this.upperLimit2) {
  96360. if (this.limitState2 != 0) {
  96361. this.limitState2 = 0;
  96362. this.limitImpulse2 = 0;
  96363. }
  96364. this.limitVelocity2 = this.lowerLimit2 - angle2;
  96365. } else if (angle2 < this.lowerLimit2) {
  96366. if (this.limitState2 != -1) {
  96367. this.limitState2 = -1;
  96368. this.limitImpulse2 = 0;
  96369. }
  96370. this.limitVelocity2 = this.lowerLimit2 - angle2;
  96371. } else if (angle2 > this.upperLimit2) {
  96372. if (this.limitState2 != 1) {
  96373. this.limitState2 = 1;
  96374. this.limitImpulse2 = 0;
  96375. }
  96376. this.limitVelocity2 = this.upperLimit2 - angle2;
  96377. } else {
  96378. this.limitState2 = 2;
  96379. this.limitImpulse2 = 0;
  96380. this.limitVelocity2 = 0;
  96381. }
  96382. if (!enableSpring2) {
  96383. if (this.limitVelocity2 > 0.02) this.limitVelocity2 -= 0.02;
  96384. else if (this.limitVelocity2 < -0.02) this.limitVelocity2 += 0.02;
  96385. else this.limitVelocity2 = 0;
  96386. }
  96387. } else {
  96388. this.limitState2 = 2;
  96389. this.limitImpulse2 = 0;
  96390. }
  96391. var angle3 = this.limitMotor3.angle;
  96392. if (enableLimit3) {
  96393. if (this.lowerLimit3 == this.upperLimit3) {
  96394. if (this.limitState3 != 0) {
  96395. this.limitState3 = 0;
  96396. this.limitImpulse3 = 0;
  96397. }
  96398. this.limitVelocity3 = this.lowerLimit3 - angle3;
  96399. } else if (angle3 < this.lowerLimit3) {
  96400. if (this.limitState3 != -1) {
  96401. this.limitState3 = -1;
  96402. this.limitImpulse3 = 0;
  96403. }
  96404. this.limitVelocity3 = this.lowerLimit3 - angle3;
  96405. } else if (angle3 > this.upperLimit3) {
  96406. if (this.limitState3 != 1) {
  96407. this.limitState3 = 1;
  96408. this.limitImpulse3 = 0;
  96409. }
  96410. this.limitVelocity3 = this.upperLimit3 - angle3;
  96411. } else {
  96412. this.limitState3 = 2;
  96413. this.limitImpulse3 = 0;
  96414. this.limitVelocity3 = 0;
  96415. }
  96416. if (!enableSpring3) {
  96417. if (this.limitVelocity3 > 0.02) this.limitVelocity3 -= 0.02;
  96418. else if (this.limitVelocity3 < -0.02) this.limitVelocity3 += 0.02;
  96419. else this.limitVelocity3 = 0;
  96420. }
  96421. } else {
  96422. this.limitState3 = 2;
  96423. this.limitImpulse3 = 0;
  96424. }
  96425. if (this.enableMotor1 && (this.limitState1 != 0 || enableSpring1)) {
  96426. this.maxMotorImpulse1 = this.maxMotorForce1 * timeStep;
  96427. } else {
  96428. this.motorImpulse1 = 0;
  96429. this.maxMotorImpulse1 = 0;
  96430. }
  96431. if (this.enableMotor2 && (this.limitState2 != 0 || enableSpring2)) {
  96432. this.maxMotorImpulse2 = this.maxMotorForce2 * timeStep;
  96433. } else {
  96434. this.motorImpulse2 = 0;
  96435. this.maxMotorImpulse2 = 0;
  96436. }
  96437. if (this.enableMotor3 && (this.limitState3 != 0 || enableSpring3)) {
  96438. this.maxMotorImpulse3 = this.maxMotorForce3 * timeStep;
  96439. } else {
  96440. this.motorImpulse3 = 0;
  96441. this.maxMotorImpulse3 = 0;
  96442. }
  96443. // build jacobians
  96444. this.a1x1 = this.ax1 * this.i1e00 + this.ay1 * this.i1e01 + this.az1 * this.i1e02;
  96445. this.a1y1 = this.ax1 * this.i1e10 + this.ay1 * this.i1e11 + this.az1 * this.i1e12;
  96446. this.a1z1 = this.ax1 * this.i1e20 + this.ay1 * this.i1e21 + this.az1 * this.i1e22;
  96447. this.a2x1 = this.ax1 * this.i2e00 + this.ay1 * this.i2e01 + this.az1 * this.i2e02;
  96448. this.a2y1 = this.ax1 * this.i2e10 + this.ay1 * this.i2e11 + this.az1 * this.i2e12;
  96449. this.a2z1 = this.ax1 * this.i2e20 + this.ay1 * this.i2e21 + this.az1 * this.i2e22;
  96450. this.a1x2 = this.ax2 * this.i1e00 + this.ay2 * this.i1e01 + this.az2 * this.i1e02;
  96451. this.a1y2 = this.ax2 * this.i1e10 + this.ay2 * this.i1e11 + this.az2 * this.i1e12;
  96452. this.a1z2 = this.ax2 * this.i1e20 + this.ay2 * this.i1e21 + this.az2 * this.i1e22;
  96453. this.a2x2 = this.ax2 * this.i2e00 + this.ay2 * this.i2e01 + this.az2 * this.i2e02;
  96454. this.a2y2 = this.ax2 * this.i2e10 + this.ay2 * this.i2e11 + this.az2 * this.i2e12;
  96455. this.a2z2 = this.ax2 * this.i2e20 + this.ay2 * this.i2e21 + this.az2 * this.i2e22;
  96456. this.a1x3 = this.ax3 * this.i1e00 + this.ay3 * this.i1e01 + this.az3 * this.i1e02;
  96457. this.a1y3 = this.ax3 * this.i1e10 + this.ay3 * this.i1e11 + this.az3 * this.i1e12;
  96458. this.a1z3 = this.ax3 * this.i1e20 + this.ay3 * this.i1e21 + this.az3 * this.i1e22;
  96459. this.a2x3 = this.ax3 * this.i2e00 + this.ay3 * this.i2e01 + this.az3 * this.i2e02;
  96460. this.a2y3 = this.ax3 * this.i2e10 + this.ay3 * this.i2e11 + this.az3 * this.i2e12;
  96461. this.a2z3 = this.ax3 * this.i2e20 + this.ay3 * this.i2e21 + this.az3 * this.i2e22;
  96462. // build an impulse matrix
  96463. this.k00 = this.ax1 * (this.a1x1 + this.a2x1) + this.ay1 * (this.a1y1 + this.a2y1) + this.az1 * (this.a1z1 + this.a2z1);
  96464. this.k01 = this.ax1 * (this.a1x2 + this.a2x2) + this.ay1 * (this.a1y2 + this.a2y2) + this.az1 * (this.a1z2 + this.a2z2);
  96465. this.k02 = this.ax1 * (this.a1x3 + this.a2x3) + this.ay1 * (this.a1y3 + this.a2y3) + this.az1 * (this.a1z3 + this.a2z3);
  96466. this.k10 = this.ax2 * (this.a1x1 + this.a2x1) + this.ay2 * (this.a1y1 + this.a2y1) + this.az2 * (this.a1z1 + this.a2z1);
  96467. this.k11 = this.ax2 * (this.a1x2 + this.a2x2) + this.ay2 * (this.a1y2 + this.a2y2) + this.az2 * (this.a1z2 + this.a2z2);
  96468. this.k12 = this.ax2 * (this.a1x3 + this.a2x3) + this.ay2 * (this.a1y3 + this.a2y3) + this.az2 * (this.a1z3 + this.a2z3);
  96469. this.k20 = this.ax3 * (this.a1x1 + this.a2x1) + this.ay3 * (this.a1y1 + this.a2y1) + this.az3 * (this.a1z1 + this.a2z1);
  96470. this.k21 = this.ax3 * (this.a1x2 + this.a2x2) + this.ay3 * (this.a1y2 + this.a2y2) + this.az3 * (this.a1z2 + this.a2z2);
  96471. this.k22 = this.ax3 * (this.a1x3 + this.a2x3) + this.ay3 * (this.a1y3 + this.a2y3) + this.az3 * (this.a1z3 + this.a2z3);
  96472. this.kv00 = this.k00;
  96473. this.kv11 = this.k11;
  96474. this.kv22 = this.k22;
  96475. this.dv00 = 1 / this.kv00;
  96476. this.dv11 = 1 / this.kv11;
  96477. this.dv22 = 1 / this.kv22;
  96478. if (enableSpring1 && this.limitState1 != 2) {
  96479. var omega = 6.2831853 * frequency1;
  96480. var k = omega * omega * timeStep;
  96481. var dmp = invTimeStep / (k + 2 * this.limitMotor1.dampingRatio * omega);
  96482. this.cfm1 = this.kv00 * dmp;
  96483. this.limitVelocity1 *= k * dmp;
  96484. } else {
  96485. this.cfm1 = 0;
  96486. this.limitVelocity1 *= invTimeStep * 0.05;
  96487. }
  96488. if (enableSpring2 && this.limitState2 != 2) {
  96489. omega = 6.2831853 * frequency2;
  96490. k = omega * omega * timeStep;
  96491. dmp = invTimeStep / (k + 2 * this.limitMotor2.dampingRatio * omega);
  96492. this.cfm2 = this.kv11 * dmp;
  96493. this.limitVelocity2 *= k * dmp;
  96494. } else {
  96495. this.cfm2 = 0;
  96496. this.limitVelocity2 *= invTimeStep * 0.05;
  96497. }
  96498. if (enableSpring3 && this.limitState3 != 2) {
  96499. omega = 6.2831853 * frequency3;
  96500. k = omega * omega * timeStep;
  96501. dmp = invTimeStep / (k + 2 * this.limitMotor3.dampingRatio * omega);
  96502. this.cfm3 = this.kv22 * dmp;
  96503. this.limitVelocity3 *= k * dmp;
  96504. } else {
  96505. this.cfm3 = 0;
  96506. this.limitVelocity3 *= invTimeStep * 0.05;
  96507. }
  96508. this.k00 += this.cfm1;
  96509. this.k11 += this.cfm2;
  96510. this.k22 += this.cfm3;
  96511. var inv = 1 / (
  96512. this.k00 * (this.k11 * this.k22 - this.k21 * this.k12) +
  96513. this.k10 * (this.k21 * this.k02 - this.k01 * this.k22) +
  96514. this.k20 * (this.k01 * this.k12 - this.k11 * this.k02)
  96515. );
  96516. this.d00 = (this.k11 * this.k22 - this.k12 * this.k21) * inv;
  96517. this.d01 = (this.k02 * this.k21 - this.k01 * this.k22) * inv;
  96518. this.d02 = (this.k01 * this.k12 - this.k02 * this.k11) * inv;
  96519. this.d10 = (this.k12 * this.k20 - this.k10 * this.k22) * inv;
  96520. this.d11 = (this.k00 * this.k22 - this.k02 * this.k20) * inv;
  96521. this.d12 = (this.k02 * this.k10 - this.k00 * this.k12) * inv;
  96522. this.d20 = (this.k10 * this.k21 - this.k11 * this.k20) * inv;
  96523. this.d21 = (this.k01 * this.k20 - this.k00 * this.k21) * inv;
  96524. this.d22 = (this.k00 * this.k11 - this.k01 * this.k10) * inv;
  96525. this.limitImpulse1 *= 0.95;
  96526. this.motorImpulse1 *= 0.95;
  96527. this.limitImpulse2 *= 0.95;
  96528. this.motorImpulse2 *= 0.95;
  96529. this.limitImpulse3 *= 0.95;
  96530. this.motorImpulse3 *= 0.95;
  96531. var totalImpulse1 = this.limitImpulse1 + this.motorImpulse1;
  96532. var totalImpulse2 = this.limitImpulse2 + this.motorImpulse2;
  96533. var totalImpulse3 = this.limitImpulse3 + this.motorImpulse3;
  96534. this.a1.x += totalImpulse1 * this.a1x1 + totalImpulse2 * this.a1x2 + totalImpulse3 * this.a1x3;
  96535. this.a1.y += totalImpulse1 * this.a1y1 + totalImpulse2 * this.a1y2 + totalImpulse3 * this.a1y3;
  96536. this.a1.z += totalImpulse1 * this.a1z1 + totalImpulse2 * this.a1z2 + totalImpulse3 * this.a1z3;
  96537. this.a2.x -= totalImpulse1 * this.a2x1 + totalImpulse2 * this.a2x2 + totalImpulse3 * this.a2x3;
  96538. this.a2.y -= totalImpulse1 * this.a2y1 + totalImpulse2 * this.a2y2 + totalImpulse3 * this.a2y3;
  96539. this.a2.z -= totalImpulse1 * this.a2z1 + totalImpulse2 * this.a2z2 + totalImpulse3 * this.a2z3;
  96540. },
  96541. solve_: function () {
  96542. var rvx = this.a2.x - this.a1.x;
  96543. var rvy = this.a2.y - this.a1.y;
  96544. var rvz = this.a2.z - this.a1.z;
  96545. this.limitVelocity3 = 30;
  96546. var rvn1 = rvx * this.ax1 + rvy * this.ay1 + rvz * this.az1 - this.limitVelocity1;
  96547. var rvn2 = rvx * this.ax2 + rvy * this.ay2 + rvz * this.az2 - this.limitVelocity2;
  96548. var rvn3 = rvx * this.ax3 + rvy * this.ay3 + rvz * this.az3 - this.limitVelocity3;
  96549. var dLimitImpulse1 = rvn1 * this.d00 + rvn2 * this.d01 + rvn3 * this.d02;
  96550. var dLimitImpulse2 = rvn1 * this.d10 + rvn2 * this.d11 + rvn3 * this.d12;
  96551. var dLimitImpulse3 = rvn1 * this.d20 + rvn2 * this.d21 + rvn3 * this.d22;
  96552. this.limitImpulse1 += dLimitImpulse1;
  96553. this.limitImpulse2 += dLimitImpulse2;
  96554. this.limitImpulse3 += dLimitImpulse3;
  96555. this.a1.x += dLimitImpulse1 * this.a1x1 + dLimitImpulse2 * this.a1x2 + dLimitImpulse3 * this.a1x3;
  96556. this.a1.y += dLimitImpulse1 * this.a1y1 + dLimitImpulse2 * this.a1y2 + dLimitImpulse3 * this.a1y3;
  96557. this.a1.z += dLimitImpulse1 * this.a1z1 + dLimitImpulse2 * this.a1z2 + dLimitImpulse3 * this.a1z3;
  96558. this.a2.x -= dLimitImpulse1 * this.a2x1 + dLimitImpulse2 * this.a2x2 + dLimitImpulse3 * this.a2x3;
  96559. this.a2.y -= dLimitImpulse1 * this.a2y1 + dLimitImpulse2 * this.a2y2 + dLimitImpulse3 * this.a2y3;
  96560. this.a2.z -= dLimitImpulse1 * this.a2z1 + dLimitImpulse2 * this.a2z2 + dLimitImpulse3 * this.a2z3;
  96561. },
  96562. solve: function () {
  96563. var rvx = this.a2.x - this.a1.x;
  96564. var rvy = this.a2.y - this.a1.y;
  96565. var rvz = this.a2.z - this.a1.z;
  96566. var rvn1 = rvx * this.ax1 + rvy * this.ay1 + rvz * this.az1;
  96567. var rvn2 = rvx * this.ax2 + rvy * this.ay2 + rvz * this.az2;
  96568. var rvn3 = rvx * this.ax3 + rvy * this.ay3 + rvz * this.az3;
  96569. var oldMotorImpulse1 = this.motorImpulse1;
  96570. var oldMotorImpulse2 = this.motorImpulse2;
  96571. var oldMotorImpulse3 = this.motorImpulse3;
  96572. var dMotorImpulse1 = 0;
  96573. var dMotorImpulse2 = 0;
  96574. var dMotorImpulse3 = 0;
  96575. if (this.enableMotor1) {
  96576. dMotorImpulse1 = (rvn1 - this.motorSpeed1) * this.dv00;
  96577. this.motorImpulse1 += dMotorImpulse1;
  96578. if (this.motorImpulse1 > this.maxMotorImpulse1) { // clamp motor impulse
  96579. this.motorImpulse1 = this.maxMotorImpulse1;
  96580. } else if (this.motorImpulse1 < -this.maxMotorImpulse1) {
  96581. this.motorImpulse1 = -this.maxMotorImpulse1;
  96582. }
  96583. dMotorImpulse1 = this.motorImpulse1 - oldMotorImpulse1;
  96584. }
  96585. if (this.enableMotor2) {
  96586. dMotorImpulse2 = (rvn2 - this.motorSpeed2) * this.dv11;
  96587. this.motorImpulse2 += dMotorImpulse2;
  96588. if (this.motorImpulse2 > this.maxMotorImpulse2) { // clamp motor impulse
  96589. this.motorImpulse2 = this.maxMotorImpulse2;
  96590. } else if (this.motorImpulse2 < -this.maxMotorImpulse2) {
  96591. this.motorImpulse2 = -this.maxMotorImpulse2;
  96592. }
  96593. dMotorImpulse2 = this.motorImpulse2 - oldMotorImpulse2;
  96594. }
  96595. if (this.enableMotor3) {
  96596. dMotorImpulse3 = (rvn3 - this.motorSpeed3) * this.dv22;
  96597. this.motorImpulse3 += dMotorImpulse3;
  96598. if (this.motorImpulse3 > this.maxMotorImpulse3) { // clamp motor impulse
  96599. this.motorImpulse3 = this.maxMotorImpulse3;
  96600. } else if (this.motorImpulse3 < -this.maxMotorImpulse3) {
  96601. this.motorImpulse3 = -this.maxMotorImpulse3;
  96602. }
  96603. dMotorImpulse3 = this.motorImpulse3 - oldMotorImpulse3;
  96604. }
  96605. // apply motor impulse to relative velocity
  96606. rvn1 += dMotorImpulse1 * this.kv00 + dMotorImpulse2 * this.k01 + dMotorImpulse3 * this.k02;
  96607. rvn2 += dMotorImpulse1 * this.k10 + dMotorImpulse2 * this.kv11 + dMotorImpulse3 * this.k12;
  96608. rvn3 += dMotorImpulse1 * this.k20 + dMotorImpulse2 * this.k21 + dMotorImpulse3 * this.kv22;
  96609. // subtract target velocity and applied impulse
  96610. rvn1 -= this.limitVelocity1 + this.limitImpulse1 * this.cfm1;
  96611. rvn2 -= this.limitVelocity2 + this.limitImpulse2 * this.cfm2;
  96612. rvn3 -= this.limitVelocity3 + this.limitImpulse3 * this.cfm3;
  96613. var oldLimitImpulse1 = this.limitImpulse1;
  96614. var oldLimitImpulse2 = this.limitImpulse2;
  96615. var oldLimitImpulse3 = this.limitImpulse3;
  96616. var dLimitImpulse1 = rvn1 * this.d00 + rvn2 * this.d01 + rvn3 * this.d02;
  96617. var dLimitImpulse2 = rvn1 * this.d10 + rvn2 * this.d11 + rvn3 * this.d12;
  96618. var dLimitImpulse3 = rvn1 * this.d20 + rvn2 * this.d21 + rvn3 * this.d22;
  96619. this.limitImpulse1 += dLimitImpulse1;
  96620. this.limitImpulse2 += dLimitImpulse2;
  96621. this.limitImpulse3 += dLimitImpulse3;
  96622. // clamp
  96623. var clampState = 0;
  96624. if (this.limitState1 == 2 || this.limitImpulse1 * this.limitState1 < 0) {
  96625. dLimitImpulse1 = -oldLimitImpulse1;
  96626. rvn2 += dLimitImpulse1 * this.k10;
  96627. rvn3 += dLimitImpulse1 * this.k20;
  96628. clampState |= 1;
  96629. }
  96630. if (this.limitState2 == 2 || this.limitImpulse2 * this.limitState2 < 0) {
  96631. dLimitImpulse2 = -oldLimitImpulse2;
  96632. rvn1 += dLimitImpulse2 * this.k01;
  96633. rvn3 += dLimitImpulse2 * this.k21;
  96634. clampState |= 2;
  96635. }
  96636. if (this.limitState3 == 2 || this.limitImpulse3 * this.limitState3 < 0) {
  96637. dLimitImpulse3 = -oldLimitImpulse3;
  96638. rvn1 += dLimitImpulse3 * this.k02;
  96639. rvn2 += dLimitImpulse3 * this.k12;
  96640. clampState |= 4;
  96641. }
  96642. // update un-clamped impulse
  96643. // TODO: isolate division
  96644. var det;
  96645. switch (clampState) {
  96646. case 1: // update 2 3
  96647. det = 1 / (this.k11 * this.k22 - this.k12 * this.k21);
  96648. dLimitImpulse2 = (this.k22 * rvn2 + -this.k12 * rvn3) * det;
  96649. dLimitImpulse3 = (-this.k21 * rvn2 + this.k11 * rvn3) * det;
  96650. break;
  96651. case 2: // update 1 3
  96652. det = 1 / (this.k00 * this.k22 - this.k02 * this.k20);
  96653. dLimitImpulse1 = (this.k22 * rvn1 + -this.k02 * rvn3) * det;
  96654. dLimitImpulse3 = (-this.k20 * rvn1 + this.k00 * rvn3) * det;
  96655. break;
  96656. case 3: // update 3
  96657. dLimitImpulse3 = rvn3 / this.k22;
  96658. break;
  96659. case 4: // update 1 2
  96660. det = 1 / (this.k00 * this.k11 - this.k01 * this.k10);
  96661. dLimitImpulse1 = (this.k11 * rvn1 + -this.k01 * rvn2) * det;
  96662. dLimitImpulse2 = (-this.k10 * rvn1 + this.k00 * rvn2) * det;
  96663. break;
  96664. case 5: // update 2
  96665. dLimitImpulse2 = rvn2 / this.k11;
  96666. break;
  96667. case 6: // update 1
  96668. dLimitImpulse1 = rvn1 / this.k00;
  96669. break;
  96670. }
  96671. this.limitImpulse1 = dLimitImpulse1 + oldLimitImpulse1;
  96672. this.limitImpulse2 = dLimitImpulse2 + oldLimitImpulse2;
  96673. this.limitImpulse3 = dLimitImpulse3 + oldLimitImpulse3;
  96674. var dImpulse1 = dMotorImpulse1 + dLimitImpulse1;
  96675. var dImpulse2 = dMotorImpulse2 + dLimitImpulse2;
  96676. var dImpulse3 = dMotorImpulse3 + dLimitImpulse3;
  96677. // apply impulse
  96678. this.a1.x += dImpulse1 * this.a1x1 + dImpulse2 * this.a1x2 + dImpulse3 * this.a1x3;
  96679. this.a1.y += dImpulse1 * this.a1y1 + dImpulse2 * this.a1y2 + dImpulse3 * this.a1y3;
  96680. this.a1.z += dImpulse1 * this.a1z1 + dImpulse2 * this.a1z2 + dImpulse3 * this.a1z3;
  96681. this.a2.x -= dImpulse1 * this.a2x1 + dImpulse2 * this.a2x2 + dImpulse3 * this.a2x3;
  96682. this.a2.y -= dImpulse1 * this.a2y1 + dImpulse2 * this.a2y2 + dImpulse3 * this.a2y3;
  96683. this.a2.z -= dImpulse1 * this.a2z1 + dImpulse2 * this.a2z2 + dImpulse3 * this.a2z3;
  96684. rvx = this.a2.x - this.a1.x;
  96685. rvy = this.a2.y - this.a1.y;
  96686. rvz = this.a2.z - this.a1.z;
  96687. rvn2 = rvx * this.ax2 + rvy * this.ay2 + rvz * this.az2;
  96688. }
  96689. }
  96690. /**
  96691. * A rotational constraint for various joints.
  96692. * @author saharan
  96693. */
  96694. OIMO.RotationalConstraint = function (joint, limitMotor) {
  96695. this.cfm = NaN;
  96696. this.i1e00 = NaN;
  96697. this.i1e01 = NaN;
  96698. this.i1e02 = NaN;
  96699. this.i1e10 = NaN;
  96700. this.i1e11 = NaN;
  96701. this.i1e12 = NaN;
  96702. this.i1e20 = NaN;
  96703. this.i1e21 = NaN;
  96704. this.i1e22 = NaN;
  96705. this.i2e00 = NaN;
  96706. this.i2e01 = NaN;
  96707. this.i2e02 = NaN;
  96708. this.i2e10 = NaN;
  96709. this.i2e11 = NaN;
  96710. this.i2e12 = NaN;
  96711. this.i2e20 = NaN;
  96712. this.i2e21 = NaN;
  96713. this.i2e22 = NaN;
  96714. this.motorDenom = NaN;
  96715. this.invMotorDenom = NaN;
  96716. this.invDenom = NaN;
  96717. this.ax = NaN;
  96718. this.ay = NaN;
  96719. this.az = NaN;
  96720. this.a1x = NaN;
  96721. this.a1y = NaN;
  96722. this.a1z = NaN;
  96723. this.a2x = NaN;
  96724. this.a2y = NaN;
  96725. this.a2z = NaN;
  96726. this.enableLimit = false;
  96727. this.lowerLimit = NaN;
  96728. this.upperLimit = NaN;
  96729. this.limitVelocity = NaN;
  96730. this.limitState = 0; // -1: at lower, 0: locked, 1: at upper, 2: free
  96731. this.enableMotor = false;
  96732. this.motorSpeed = NaN;
  96733. this.maxMotorForce = NaN;
  96734. this.maxMotorImpulse = NaN;
  96735. this.limitMotor = limitMotor;
  96736. this.b1 = joint.body1;
  96737. this.b2 = joint.body2;
  96738. this.a1 = this.b1.angularVelocity;
  96739. this.a2 = this.b2.angularVelocity;
  96740. this.i1 = this.b1.inverseInertia;
  96741. this.i2 = this.b2.inverseInertia;
  96742. this.limitImpulse = 0;
  96743. this.motorImpulse = 0;
  96744. }
  96745. OIMO.RotationalConstraint.prototype = {
  96746. constructor: OIMO.RotationalConstraint,
  96747. preSolve: function (timeStep, invTimeStep) {
  96748. this.ax = this.limitMotor.axis.x;
  96749. this.ay = this.limitMotor.axis.y;
  96750. this.az = this.limitMotor.axis.z;
  96751. this.lowerLimit = this.limitMotor.lowerLimit;
  96752. this.upperLimit = this.limitMotor.upperLimit;
  96753. this.motorSpeed = this.limitMotor.motorSpeed;
  96754. this.maxMotorForce = this.limitMotor.maxMotorForce;
  96755. this.enableMotor = this.maxMotorForce > 0;
  96756. var ti1 = this.i1.elements;
  96757. var ti2 = this.i2.elements;
  96758. this.i1e00 = ti1[0];
  96759. this.i1e01 = ti1[1];
  96760. this.i1e02 = ti1[2];
  96761. this.i1e10 = ti1[3];
  96762. this.i1e11 = ti1[4];
  96763. this.i1e12 = ti1[5];
  96764. this.i1e20 = ti1[6];
  96765. this.i1e21 = ti1[7];
  96766. this.i1e22 = ti1[8];
  96767. this.i2e00 = ti2[0];
  96768. this.i2e01 = ti2[1];
  96769. this.i2e02 = ti2[2];
  96770. this.i2e10 = ti2[3];
  96771. this.i2e11 = ti2[4];
  96772. this.i2e12 = ti2[5];
  96773. this.i2e20 = ti2[6];
  96774. this.i2e21 = ti2[7];
  96775. this.i2e22 = ti2[8];
  96776. var frequency = this.limitMotor.frequency;
  96777. var enableSpring = frequency > 0;
  96778. var enableLimit = this.lowerLimit <= this.upperLimit;
  96779. var angle = this.limitMotor.angle;
  96780. if (enableLimit) {
  96781. if (this.lowerLimit == this.upperLimit) {
  96782. if (this.limitState != 0) {
  96783. this.limitState = 0;
  96784. this.limitImpulse = 0;
  96785. }
  96786. this.limitVelocity = this.lowerLimit - angle;
  96787. } else if (angle < this.lowerLimit) {
  96788. if (this.limitState != -1) {
  96789. this.limitState = -1;
  96790. this.limitImpulse = 0;
  96791. }
  96792. this.limitVelocity = this.lowerLimit - angle;
  96793. } else if (angle > this.upperLimit) {
  96794. if (this.limitState != 1) {
  96795. this.limitState = 1;
  96796. this.limitImpulse = 0;
  96797. }
  96798. this.limitVelocity = this.upperLimit - angle;
  96799. } else {
  96800. this.limitState = 2;
  96801. this.limitImpulse = 0;
  96802. this.limitVelocity = 0;
  96803. }
  96804. if (!enableSpring) {
  96805. if (this.limitVelocity > 0.02) this.limitVelocity -= 0.02;
  96806. else if (this.limitVelocity < -0.02) this.limitVelocity += 0.02;
  96807. else this.limitVelocity = 0;
  96808. }
  96809. } else {
  96810. this.limitState = 2;
  96811. this.limitImpulse = 0;
  96812. }
  96813. if (this.enableMotor && (this.limitState != 0 || enableSpring)) {
  96814. this.maxMotorImpulse = this.maxMotorForce * timeStep;
  96815. } else {
  96816. this.motorImpulse = 0;
  96817. this.maxMotorImpulse = 0;
  96818. }
  96819. this.a1x = this.ax * this.i1e00 + this.ay * this.i1e01 + this.az * this.i1e02;
  96820. this.a1y = this.ax * this.i1e10 + this.ay * this.i1e11 + this.az * this.i1e12;
  96821. this.a1z = this.ax * this.i1e20 + this.ay * this.i1e21 + this.az * this.i1e22;
  96822. this.a2x = this.ax * this.i2e00 + this.ay * this.i2e01 + this.az * this.i2e02;
  96823. this.a2y = this.ax * this.i2e10 + this.ay * this.i2e11 + this.az * this.i2e12;
  96824. this.a2z = this.ax * this.i2e20 + this.ay * this.i2e21 + this.az * this.i2e22;
  96825. this.motorDenom = this.ax * (this.a1x + this.a2x) + this.ay * (this.a1y + this.a2y) + this.az * (this.a1z + this.a2z);
  96826. this.invMotorDenom = 1 / this.motorDenom;
  96827. if (enableSpring && this.limitState != 2) {
  96828. var omega = 6.2831853 * frequency;
  96829. var k = omega * omega * timeStep;
  96830. var dmp = invTimeStep / (k + 2 * this.limitMotor.dampingRatio * omega);
  96831. this.cfm = this.motorDenom * dmp;
  96832. this.limitVelocity *= k * dmp;
  96833. } else {
  96834. this.cfm = 0;
  96835. this.limitVelocity *= invTimeStep * 0.05;
  96836. }
  96837. this.invDenom = 1 / (this.motorDenom + this.cfm);
  96838. this.limitImpulse *= 0.95;
  96839. this.motorImpulse *= 0.95;
  96840. var totalImpulse = this.limitImpulse + this.motorImpulse;
  96841. this.a1.x += totalImpulse * this.a1x;
  96842. this.a1.y += totalImpulse * this.a1y;
  96843. this.a1.z += totalImpulse * this.a1z;
  96844. this.a2.x -= totalImpulse * this.a2x;
  96845. this.a2.y -= totalImpulse * this.a2y;
  96846. this.a2.z -= totalImpulse * this.a2z;
  96847. },
  96848. solve: function () {
  96849. var rvn = this.ax * (this.a2.x - this.a1.x) + this.ay * (this.a2.y - this.a1.y) + this.az * (this.a2.z - this.a1.z);
  96850. // motor part
  96851. var newMotorImpulse;
  96852. if (this.enableMotor) {
  96853. newMotorImpulse = (rvn - this.motorSpeed) * this.invMotorDenom;
  96854. var oldMotorImpulse = this.motorImpulse;
  96855. this.motorImpulse += newMotorImpulse;
  96856. if (this.motorImpulse > this.maxMotorImpulse) this.motorImpulse = this.maxMotorImpulse;
  96857. else if (this.motorImpulse < -this.maxMotorImpulse) this.motorImpulse = -this.maxMotorImpulse;
  96858. newMotorImpulse = this.motorImpulse - oldMotorImpulse;
  96859. rvn -= newMotorImpulse * this.motorDenom;
  96860. } else newMotorImpulse = 0;
  96861. // limit part
  96862. var newLimitImpulse;
  96863. if (this.limitState != 2) {
  96864. newLimitImpulse = (rvn - this.limitVelocity - this.limitImpulse * this.cfm) * this.invDenom;
  96865. var oldLimitImpulse = this.limitImpulse;
  96866. this.limitImpulse += newLimitImpulse;
  96867. if (this.limitImpulse * this.limitState < 0) this.limitImpulse = 0;
  96868. newLimitImpulse = this.limitImpulse - oldLimitImpulse;
  96869. } else newLimitImpulse = 0;
  96870. var totalImpulse = newLimitImpulse + newMotorImpulse;
  96871. this.a1.x += totalImpulse * this.a1x;
  96872. this.a1.y += totalImpulse * this.a1y;
  96873. this.a1.z += totalImpulse * this.a1z;
  96874. this.a2.x -= totalImpulse * this.a2x;
  96875. this.a2.y -= totalImpulse * this.a2y;
  96876. this.a2.z -= totalImpulse * this.a2z;
  96877. }
  96878. }
  96879. /**
  96880. * A three-axis translational constraint for various joints.
  96881. * @author saharan
  96882. */
  96883. OIMO.Translational3Constraint = function (joint, limitMotor1, limitMotor2, limitMotor3) {
  96884. this.m1 = NaN;
  96885. this.m2 = NaN;
  96886. this.i1e00 = NaN;
  96887. this.i1e01 = NaN;
  96888. this.i1e02 = NaN;
  96889. this.i1e10 = NaN;
  96890. this.i1e11 = NaN;
  96891. this.i1e12 = NaN;
  96892. this.i1e20 = NaN;
  96893. this.i1e21 = NaN;
  96894. this.i1e22 = NaN;
  96895. this.i2e00 = NaN;
  96896. this.i2e01 = NaN;
  96897. this.i2e02 = NaN;
  96898. this.i2e10 = NaN;
  96899. this.i2e11 = NaN;
  96900. this.i2e12 = NaN;
  96901. this.i2e20 = NaN;
  96902. this.i2e21 = NaN;
  96903. this.i2e22 = NaN;
  96904. this.ax1 = NaN;
  96905. this.ay1 = NaN;
  96906. this.az1 = NaN;
  96907. this.ax2 = NaN;
  96908. this.ay2 = NaN;
  96909. this.az2 = NaN;
  96910. this.ax3 = NaN;
  96911. this.ay3 = NaN;
  96912. this.az3 = NaN;
  96913. this.r1x = NaN;
  96914. this.r1y = NaN;
  96915. this.r1z = NaN;
  96916. this.r2x = NaN;
  96917. this.r2y = NaN;
  96918. this.r2z = NaN;
  96919. this.t1x1 = NaN;// jacobians
  96920. this.t1y1 = NaN;
  96921. this.t1z1 = NaN;
  96922. this.t2x1 = NaN;
  96923. this.t2y1 = NaN;
  96924. this.t2z1 = NaN;
  96925. this.l1x1 = NaN;
  96926. this.l1y1 = NaN;
  96927. this.l1z1 = NaN;
  96928. this.l2x1 = NaN;
  96929. this.l2y1 = NaN;
  96930. this.l2z1 = NaN;
  96931. this.a1x1 = NaN;
  96932. this.a1y1 = NaN;
  96933. this.a1z1 = NaN;
  96934. this.a2x1 = NaN;
  96935. this.a2y1 = NaN;
  96936. this.a2z1 = NaN;
  96937. this.t1x2 = NaN;
  96938. this.t1y2 = NaN;
  96939. this.t1z2 = NaN;
  96940. this.t2x2 = NaN;
  96941. this.t2y2 = NaN;
  96942. this.t2z2 = NaN;
  96943. this.l1x2 = NaN;
  96944. this.l1y2 = NaN;
  96945. this.l1z2 = NaN;
  96946. this.l2x2 = NaN;
  96947. this.l2y2 = NaN;
  96948. this.l2z2 = NaN;
  96949. this.a1x2 = NaN;
  96950. this.a1y2 = NaN;
  96951. this.a1z2 = NaN;
  96952. this.a2x2 = NaN;
  96953. this.a2y2 = NaN;
  96954. this.a2z2 = NaN;
  96955. this.t1x3 = NaN;
  96956. this.t1y3 = NaN;
  96957. this.t1z3 = NaN;
  96958. this.t2x3 = NaN;
  96959. this.t2y3 = NaN;
  96960. this.t2z3 = NaN;
  96961. this.l1x3 = NaN;
  96962. this.l1y3 = NaN;
  96963. this.l1z3 = NaN;
  96964. this.l2x3 = NaN;
  96965. this.l2y3 = NaN;
  96966. this.l2z3 = NaN;
  96967. this.a1x3 = NaN;
  96968. this.a1y3 = NaN;
  96969. this.a1z3 = NaN;
  96970. this.a2x3 = NaN;
  96971. this.a2y3 = NaN;
  96972. this.a2z3 = NaN;
  96973. this.lowerLimit1 = NaN;
  96974. this.upperLimit1 = NaN;
  96975. this.limitVelocity1 = NaN;
  96976. this.limitState1 = 0; // -1: at lower, 0: locked, 1: at upper, 2: unlimited
  96977. this.enableMotor1 = false;
  96978. this.motorSpeed1 = NaN;
  96979. this.maxMotorForce1 = NaN;
  96980. this.maxMotorImpulse1 = NaN;
  96981. this.lowerLimit2 = NaN;
  96982. this.upperLimit2 = NaN;
  96983. this.limitVelocity2 = NaN;
  96984. this.limitState2 = 0; // -1: at lower, 0: locked, 1: at upper, 2: unlimited
  96985. this.enableMotor2 = false;
  96986. this.motorSpeed2 = NaN;
  96987. this.maxMotorForce2 = NaN;
  96988. this.maxMotorImpulse2 = NaN;
  96989. this.lowerLimit3 = NaN;
  96990. this.upperLimit3 = NaN;
  96991. this.limitVelocity3 = NaN;
  96992. this.limitState3 = 0; // -1: at lower, 0: locked, 1: at upper, 2: unlimited
  96993. this.enableMotor3 = false;
  96994. this.motorSpeed3 = NaN;
  96995. this.maxMotorForce3 = NaN;
  96996. this.maxMotorImpulse3 = NaN;
  96997. this.k00 = NaN; // K = J*M*JT
  96998. this.k01 = NaN;
  96999. this.k02 = NaN;
  97000. this.k10 = NaN;
  97001. this.k11 = NaN;
  97002. this.k12 = NaN;
  97003. this.k20 = NaN;
  97004. this.k21 = NaN;
  97005. this.k22 = NaN;
  97006. this.kv00 = NaN; // diagonals without CFMs
  97007. this.kv11 = NaN;
  97008. this.kv22 = NaN;
  97009. this.dv00 = NaN; // ...inverted
  97010. this.dv11 = NaN;
  97011. this.dv22 = NaN;
  97012. this.d00 = NaN; // K^-1
  97013. this.d01 = NaN;
  97014. this.d02 = NaN;
  97015. this.d10 = NaN;
  97016. this.d11 = NaN;
  97017. this.d12 = NaN;
  97018. this.d20 = NaN;
  97019. this.d21 = NaN;
  97020. this.d22 = NaN;
  97021. this.limitMotor1 = limitMotor1;
  97022. this.limitMotor2 = limitMotor2;
  97023. this.limitMotor3 = limitMotor3;
  97024. this.b1 = joint.body1;
  97025. this.b2 = joint.body2;
  97026. this.p1 = joint.anchorPoint1;
  97027. this.p2 = joint.anchorPoint2;
  97028. this.r1 = joint.relativeAnchorPoint1;
  97029. this.r2 = joint.relativeAnchorPoint2;
  97030. this.l1 = this.b1.linearVelocity;
  97031. this.l2 = this.b2.linearVelocity;
  97032. this.a1 = this.b1.angularVelocity;
  97033. this.a2 = this.b2.angularVelocity;
  97034. this.i1 = this.b1.inverseInertia;
  97035. this.i2 = this.b2.inverseInertia;
  97036. this.limitImpulse1 = 0;
  97037. this.motorImpulse1 = 0;
  97038. this.limitImpulse2 = 0;
  97039. this.motorImpulse2 = 0;
  97040. this.limitImpulse3 = 0;
  97041. this.motorImpulse3 = 0;
  97042. this.cfm1 = 0;// Constraint Force Mixing
  97043. this.cfm2 = 0;
  97044. this.cfm3 = 0;
  97045. this.weight = -1;
  97046. }
  97047. OIMO.Translational3Constraint.prototype = {
  97048. constructor: OIMO.Translational3Constraint,
  97049. preSolve: function (timeStep, invTimeStep) {
  97050. this.ax1 = this.limitMotor1.axis.x;
  97051. this.ay1 = this.limitMotor1.axis.y;
  97052. this.az1 = this.limitMotor1.axis.z;
  97053. this.ax2 = this.limitMotor2.axis.x;
  97054. this.ay2 = this.limitMotor2.axis.y;
  97055. this.az2 = this.limitMotor2.axis.z;
  97056. this.ax3 = this.limitMotor3.axis.x;
  97057. this.ay3 = this.limitMotor3.axis.y;
  97058. this.az3 = this.limitMotor3.axis.z;
  97059. this.lowerLimit1 = this.limitMotor1.lowerLimit;
  97060. this.upperLimit1 = this.limitMotor1.upperLimit;
  97061. this.motorSpeed1 = this.limitMotor1.motorSpeed;
  97062. this.maxMotorForce1 = this.limitMotor1.maxMotorForce;
  97063. this.enableMotor1 = this.maxMotorForce1 > 0;
  97064. this.lowerLimit2 = this.limitMotor2.lowerLimit;
  97065. this.upperLimit2 = this.limitMotor2.upperLimit;
  97066. this.motorSpeed2 = this.limitMotor2.motorSpeed;
  97067. this.maxMotorForce2 = this.limitMotor2.maxMotorForce;
  97068. this.enableMotor2 = this.maxMotorForce2 > 0;
  97069. this.lowerLimit3 = this.limitMotor3.lowerLimit;
  97070. this.upperLimit3 = this.limitMotor3.upperLimit;
  97071. this.motorSpeed3 = this.limitMotor3.motorSpeed;
  97072. this.maxMotorForce3 = this.limitMotor3.maxMotorForce;
  97073. this.enableMotor3 = this.maxMotorForce3 > 0;
  97074. this.m1 = this.b1.inverseMass;
  97075. this.m2 = this.b2.inverseMass;
  97076. var ti1 = this.i1.elements;
  97077. var ti2 = this.i2.elements;
  97078. this.i1e00 = ti1[0];
  97079. this.i1e01 = ti1[1];
  97080. this.i1e02 = ti1[2];
  97081. this.i1e10 = ti1[3];
  97082. this.i1e11 = ti1[4];
  97083. this.i1e12 = ti1[5];
  97084. this.i1e20 = ti1[6];
  97085. this.i1e21 = ti1[7];
  97086. this.i1e22 = ti1[8];
  97087. this.i2e00 = ti2[0];
  97088. this.i2e01 = ti2[1];
  97089. this.i2e02 = ti2[2];
  97090. this.i2e10 = ti2[3];
  97091. this.i2e11 = ti2[4];
  97092. this.i2e12 = ti2[5];
  97093. this.i2e20 = ti2[6];
  97094. this.i2e21 = ti2[7];
  97095. this.i2e22 = ti2[8];
  97096. var dx = this.p2.x - this.p1.x;
  97097. var dy = this.p2.y - this.p1.y;
  97098. var dz = this.p2.z - this.p1.z;
  97099. var d1 = dx * this.ax1 + dy * this.ay1 + dz * this.az1;
  97100. var d2 = dx * this.ax2 + dy * this.ay2 + dz * this.az2;
  97101. var d3 = dx * this.ax3 + dy * this.ay3 + dz * this.az3;
  97102. var frequency1 = this.limitMotor1.frequency;
  97103. var frequency2 = this.limitMotor2.frequency;
  97104. var frequency3 = this.limitMotor3.frequency;
  97105. var enableSpring1 = frequency1 > 0;
  97106. var enableSpring2 = frequency2 > 0;
  97107. var enableSpring3 = frequency3 > 0;
  97108. var enableLimit1 = this.lowerLimit1 <= this.upperLimit1;
  97109. var enableLimit2 = this.lowerLimit2 <= this.upperLimit2;
  97110. var enableLimit3 = this.lowerLimit3 <= this.upperLimit3;
  97111. // for stability
  97112. if (enableSpring1 && d1 > 20 || d1 < -20) {
  97113. enableSpring1 = false;
  97114. }
  97115. if (enableSpring2 && d2 > 20 || d2 < -20) {
  97116. enableSpring2 = false;
  97117. }
  97118. if (enableSpring3 && d3 > 20 || d3 < -20) {
  97119. enableSpring3 = false;
  97120. }
  97121. if (enableLimit1) {
  97122. if (this.lowerLimit1 == this.upperLimit1) {
  97123. if (this.limitState1 != 0) {
  97124. this.limitState1 = 0;
  97125. this.limitImpulse1 = 0;
  97126. }
  97127. this.limitVelocity1 = this.lowerLimit1 - d1;
  97128. if (!enableSpring1) d1 = this.lowerLimit1;
  97129. } else if (d1 < this.lowerLimit1) {
  97130. if (this.limitState1 != -1) {
  97131. this.limitState1 = -1;
  97132. this.limitImpulse1 = 0;
  97133. }
  97134. this.limitVelocity1 = this.lowerLimit1 - d1;
  97135. if (!enableSpring1) d1 = this.lowerLimit1;
  97136. } else if (d1 > this.upperLimit1) {
  97137. if (this.limitState1 != 1) {
  97138. this.limitState1 = 1;
  97139. this.limitImpulse1 = 0;
  97140. }
  97141. this.limitVelocity1 = this.upperLimit1 - d1;
  97142. if (!enableSpring1) d1 = this.upperLimit1;
  97143. } else {
  97144. this.limitState1 = 2;
  97145. this.limitImpulse1 = 0;
  97146. this.limitVelocity1 = 0;
  97147. }
  97148. if (!enableSpring1) {
  97149. if (this.limitVelocity1 > 0.005) this.limitVelocity1 -= 0.005;
  97150. else if (this.limitVelocity1 < -0.005) this.limitVelocity1 += 0.005;
  97151. else this.limitVelocity1 = 0;
  97152. }
  97153. } else {
  97154. this.limitState1 = 2;
  97155. this.limitImpulse1 = 0;
  97156. }
  97157. if (enableLimit2) {
  97158. if (this.lowerLimit2 == this.upperLimit2) {
  97159. if (this.limitState2 != 0) {
  97160. this.limitState2 = 0;
  97161. this.limitImpulse2 = 0;
  97162. }
  97163. this.limitVelocity2 = this.lowerLimit2 - d2;
  97164. if (!enableSpring2) d2 = this.lowerLimit2;
  97165. } else if (d2 < this.lowerLimit2) {
  97166. if (this.limitState2 != -1) {
  97167. this.limitState2 = -1;
  97168. this.limitImpulse2 = 0;
  97169. }
  97170. this.limitVelocity2 = this.lowerLimit2 - d2;
  97171. if (!enableSpring2) d2 = this.lowerLimit2;
  97172. } else if (d2 > this.upperLimit2) {
  97173. if (this.limitState2 != 1) {
  97174. this.limitState2 = 1;
  97175. this.limitImpulse2 = 0;
  97176. }
  97177. this.limitVelocity2 = this.upperLimit2 - d2;
  97178. if (!enableSpring2) d2 = this.upperLimit2;
  97179. } else {
  97180. this.limitState2 = 2;
  97181. this.limitImpulse2 = 0;
  97182. this.limitVelocity2 = 0;
  97183. }
  97184. if (!enableSpring2) {
  97185. if (this.limitVelocity2 > 0.005) this.limitVelocity2 -= 0.005;
  97186. else if (this.limitVelocity2 < -0.005) this.limitVelocity2 += 0.005;
  97187. else this.limitVelocity2 = 0;
  97188. }
  97189. } else {
  97190. this.limitState2 = 2;
  97191. this.limitImpulse2 = 0;
  97192. }
  97193. if (enableLimit3) {
  97194. if (this.lowerLimit3 == this.upperLimit3) {
  97195. if (this.limitState3 != 0) {
  97196. this.limitState3 = 0;
  97197. this.limitImpulse3 = 0;
  97198. }
  97199. this.limitVelocity3 = this.lowerLimit3 - d3;
  97200. if (!enableSpring3) d3 = this.lowerLimit3;
  97201. } else if (d3 < this.lowerLimit3) {
  97202. if (this.limitState3 != -1) {
  97203. this.limitState3 = -1;
  97204. this.limitImpulse3 = 0;
  97205. }
  97206. this.limitVelocity3 = this.lowerLimit3 - d3;
  97207. if (!enableSpring3) d3 = this.lowerLimit3;
  97208. } else if (d3 > this.upperLimit3) {
  97209. if (this.limitState3 != 1) {
  97210. this.limitState3 = 1;
  97211. this.limitImpulse3 = 0;
  97212. }
  97213. this.limitVelocity3 = this.upperLimit3 - d3;
  97214. if (!enableSpring3) d3 = this.upperLimit3;
  97215. } else {
  97216. this.limitState3 = 2;
  97217. this.limitImpulse3 = 0;
  97218. this.limitVelocity3 = 0;
  97219. }
  97220. if (!enableSpring3) {
  97221. if (this.limitVelocity3 > 0.005) this.limitVelocity3 -= 0.005;
  97222. else if (this.limitVelocity3 < -0.005) this.limitVelocity3 += 0.005;
  97223. else this.limitVelocity3 = 0;
  97224. }
  97225. } else {
  97226. this.limitState3 = 2;
  97227. this.limitImpulse3 = 0;
  97228. }
  97229. if (this.enableMotor1 && (this.limitState1 != 0 || enableSpring1)) {
  97230. this.maxMotorImpulse1 = this.maxMotorForce1 * timeStep;
  97231. } else {
  97232. this.motorImpulse1 = 0;
  97233. this.maxMotorImpulse1 = 0;
  97234. }
  97235. if (this.enableMotor2 && (this.limitState2 != 0 || enableSpring2)) {
  97236. this.maxMotorImpulse2 = this.maxMotorForce2 * timeStep;
  97237. } else {
  97238. this.motorImpulse2 = 0;
  97239. this.maxMotorImpulse2 = 0;
  97240. }
  97241. if (this.enableMotor3 && (this.limitState3 != 0 || enableSpring3)) {
  97242. this.maxMotorImpulse3 = this.maxMotorForce3 * timeStep;
  97243. } else {
  97244. this.motorImpulse3 = 0;
  97245. this.maxMotorImpulse3 = 0;
  97246. }
  97247. var rdx = d1 * this.ax1 + d2 * this.ax2 + d3 * this.ax2;
  97248. var rdy = d1 * this.ay1 + d2 * this.ay2 + d3 * this.ay2;
  97249. var rdz = d1 * this.az1 + d2 * this.az2 + d3 * this.az2;
  97250. var w1 = this.m2 / (this.m1 + this.m2);
  97251. if (this.weight >= 0) w1 = this.weight; // use given weight
  97252. var w2 = 1 - w1;
  97253. this.r1x = this.r1.x + rdx * w1;
  97254. this.r1y = this.r1.y + rdy * w1;
  97255. this.r1z = this.r1.z + rdz * w1;
  97256. this.r2x = this.r2.x - rdx * w2;
  97257. this.r2y = this.r2.y - rdy * w2;
  97258. this.r2z = this.r2.z - rdz * w2;
  97259. // build jacobians
  97260. this.t1x1 = this.r1y * this.az1 - this.r1z * this.ay1;
  97261. this.t1y1 = this.r1z * this.ax1 - this.r1x * this.az1;
  97262. this.t1z1 = this.r1x * this.ay1 - this.r1y * this.ax1;
  97263. this.t2x1 = this.r2y * this.az1 - this.r2z * this.ay1;
  97264. this.t2y1 = this.r2z * this.ax1 - this.r2x * this.az1;
  97265. this.t2z1 = this.r2x * this.ay1 - this.r2y * this.ax1;
  97266. this.l1x1 = this.ax1 * this.m1;
  97267. this.l1y1 = this.ay1 * this.m1;
  97268. this.l1z1 = this.az1 * this.m1;
  97269. this.l2x1 = this.ax1 * this.m2;
  97270. this.l2y1 = this.ay1 * this.m2;
  97271. this.l2z1 = this.az1 * this.m2;
  97272. this.a1x1 = this.t1x1 * this.i1e00 + this.t1y1 * this.i1e01 + this.t1z1 * this.i1e02;
  97273. this.a1y1 = this.t1x1 * this.i1e10 + this.t1y1 * this.i1e11 + this.t1z1 * this.i1e12;
  97274. this.a1z1 = this.t1x1 * this.i1e20 + this.t1y1 * this.i1e21 + this.t1z1 * this.i1e22;
  97275. this.a2x1 = this.t2x1 * this.i2e00 + this.t2y1 * this.i2e01 + this.t2z1 * this.i2e02;
  97276. this.a2y1 = this.t2x1 * this.i2e10 + this.t2y1 * this.i2e11 + this.t2z1 * this.i2e12;
  97277. this.a2z1 = this.t2x1 * this.i2e20 + this.t2y1 * this.i2e21 + this.t2z1 * this.i2e22;
  97278. this.t1x2 = this.r1y * this.az2 - this.r1z * this.ay2;
  97279. this.t1y2 = this.r1z * this.ax2 - this.r1x * this.az2;
  97280. this.t1z2 = this.r1x * this.ay2 - this.r1y * this.ax2;
  97281. this.t2x2 = this.r2y * this.az2 - this.r2z * this.ay2;
  97282. this.t2y2 = this.r2z * this.ax2 - this.r2x * this.az2;
  97283. this.t2z2 = this.r2x * this.ay2 - this.r2y * this.ax2;
  97284. this.l1x2 = this.ax2 * this.m1;
  97285. this.l1y2 = this.ay2 * this.m1;
  97286. this.l1z2 = this.az2 * this.m1;
  97287. this.l2x2 = this.ax2 * this.m2;
  97288. this.l2y2 = this.ay2 * this.m2;
  97289. this.l2z2 = this.az2 * this.m2;
  97290. this.a1x2 = this.t1x2 * this.i1e00 + this.t1y2 * this.i1e01 + this.t1z2 * this.i1e02;
  97291. this.a1y2 = this.t1x2 * this.i1e10 + this.t1y2 * this.i1e11 + this.t1z2 * this.i1e12;
  97292. this.a1z2 = this.t1x2 * this.i1e20 + this.t1y2 * this.i1e21 + this.t1z2 * this.i1e22;
  97293. this.a2x2 = this.t2x2 * this.i2e00 + this.t2y2 * this.i2e01 + this.t2z2 * this.i2e02;
  97294. this.a2y2 = this.t2x2 * this.i2e10 + this.t2y2 * this.i2e11 + this.t2z2 * this.i2e12;
  97295. this.a2z2 = this.t2x2 * this.i2e20 + this.t2y2 * this.i2e21 + this.t2z2 * this.i2e22;
  97296. this.t1x3 = this.r1y * this.az3 - this.r1z * this.ay3;
  97297. this.t1y3 = this.r1z * this.ax3 - this.r1x * this.az3;
  97298. this.t1z3 = this.r1x * this.ay3 - this.r1y * this.ax3;
  97299. this.t2x3 = this.r2y * this.az3 - this.r2z * this.ay3;
  97300. this.t2y3 = this.r2z * this.ax3 - this.r2x * this.az3;
  97301. this.t2z3 = this.r2x * this.ay3 - this.r2y * this.ax3;
  97302. this.l1x3 = this.ax3 * this.m1;
  97303. this.l1y3 = this.ay3 * this.m1;
  97304. this.l1z3 = this.az3 * this.m1;
  97305. this.l2x3 = this.ax3 * this.m2;
  97306. this.l2y3 = this.ay3 * this.m2;
  97307. this.l2z3 = this.az3 * this.m2;
  97308. this.a1x3 = this.t1x3 * this.i1e00 + this.t1y3 * this.i1e01 + this.t1z3 * this.i1e02;
  97309. this.a1y3 = this.t1x3 * this.i1e10 + this.t1y3 * this.i1e11 + this.t1z3 * this.i1e12;
  97310. this.a1z3 = this.t1x3 * this.i1e20 + this.t1y3 * this.i1e21 + this.t1z3 * this.i1e22;
  97311. this.a2x3 = this.t2x3 * this.i2e00 + this.t2y3 * this.i2e01 + this.t2z3 * this.i2e02;
  97312. this.a2y3 = this.t2x3 * this.i2e10 + this.t2y3 * this.i2e11 + this.t2z3 * this.i2e12;
  97313. this.a2z3 = this.t2x3 * this.i2e20 + this.t2y3 * this.i2e21 + this.t2z3 * this.i2e22;
  97314. // build an impulse matrix
  97315. var m12 = this.m1 + this.m2;
  97316. this.k00 = (this.ax1 * this.ax1 + this.ay1 * this.ay1 + this.az1 * this.az1) * m12;
  97317. this.k01 = (this.ax1 * this.ax2 + this.ay1 * this.ay2 + this.az1 * this.az2) * m12;
  97318. this.k02 = (this.ax1 * this.ax3 + this.ay1 * this.ay3 + this.az1 * this.az3) * m12;
  97319. this.k10 = (this.ax2 * this.ax1 + this.ay2 * this.ay1 + this.az2 * this.az1) * m12;
  97320. this.k11 = (this.ax2 * this.ax2 + this.ay2 * this.ay2 + this.az2 * this.az2) * m12;
  97321. this.k12 = (this.ax2 * this.ax3 + this.ay2 * this.ay3 + this.az2 * this.az3) * m12;
  97322. this.k20 = (this.ax3 * this.ax1 + this.ay3 * this.ay1 + this.az3 * this.az1) * m12;
  97323. this.k21 = (this.ax3 * this.ax2 + this.ay3 * this.ay2 + this.az3 * this.az2) * m12;
  97324. this.k22 = (this.ax3 * this.ax3 + this.ay3 * this.ay3 + this.az3 * this.az3) * m12;
  97325. this.k00 += this.t1x1 * this.a1x1 + this.t1y1 * this.a1y1 + this.t1z1 * this.a1z1;
  97326. this.k01 += this.t1x1 * this.a1x2 + this.t1y1 * this.a1y2 + this.t1z1 * this.a1z2;
  97327. this.k02 += this.t1x1 * this.a1x3 + this.t1y1 * this.a1y3 + this.t1z1 * this.a1z3;
  97328. this.k10 += this.t1x2 * this.a1x1 + this.t1y2 * this.a1y1 + this.t1z2 * this.a1z1;
  97329. this.k11 += this.t1x2 * this.a1x2 + this.t1y2 * this.a1y2 + this.t1z2 * this.a1z2;
  97330. this.k12 += this.t1x2 * this.a1x3 + this.t1y2 * this.a1y3 + this.t1z2 * this.a1z3;
  97331. this.k20 += this.t1x3 * this.a1x1 + this.t1y3 * this.a1y1 + this.t1z3 * this.a1z1;
  97332. this.k21 += this.t1x3 * this.a1x2 + this.t1y3 * this.a1y2 + this.t1z3 * this.a1z2;
  97333. this.k22 += this.t1x3 * this.a1x3 + this.t1y3 * this.a1y3 + this.t1z3 * this.a1z3;
  97334. this.k00 += this.t2x1 * this.a2x1 + this.t2y1 * this.a2y1 + this.t2z1 * this.a2z1;
  97335. this.k01 += this.t2x1 * this.a2x2 + this.t2y1 * this.a2y2 + this.t2z1 * this.a2z2;
  97336. this.k02 += this.t2x1 * this.a2x3 + this.t2y1 * this.a2y3 + this.t2z1 * this.a2z3;
  97337. this.k10 += this.t2x2 * this.a2x1 + this.t2y2 * this.a2y1 + this.t2z2 * this.a2z1;
  97338. this.k11 += this.t2x2 * this.a2x2 + this.t2y2 * this.a2y2 + this.t2z2 * this.a2z2;
  97339. this.k12 += this.t2x2 * this.a2x3 + this.t2y2 * this.a2y3 + this.t2z2 * this.a2z3;
  97340. this.k20 += this.t2x3 * this.a2x1 + this.t2y3 * this.a2y1 + this.t2z3 * this.a2z1;
  97341. this.k21 += this.t2x3 * this.a2x2 + this.t2y3 * this.a2y2 + this.t2z3 * this.a2z2;
  97342. this.k22 += this.t2x3 * this.a2x3 + this.t2y3 * this.a2y3 + this.t2z3 * this.a2z3;
  97343. this.kv00 = this.k00;
  97344. this.kv11 = this.k11;
  97345. this.kv22 = this.k22;
  97346. this.dv00 = 1 / this.kv00;
  97347. this.dv11 = 1 / this.kv11;
  97348. this.dv22 = 1 / this.kv22;
  97349. if (enableSpring1 && this.limitState1 != 2) {
  97350. var omega = 6.2831853 * frequency1;
  97351. var k = omega * omega * timeStep;
  97352. var dmp = invTimeStep / (k + 2 * this.limitMotor1.dampingRatio * omega);
  97353. this.cfm1 = this.kv00 * dmp;
  97354. this.limitVelocity1 *= k * dmp;
  97355. } else {
  97356. this.cfm1 = 0;
  97357. this.limitVelocity1 *= invTimeStep * 0.05;
  97358. }
  97359. if (enableSpring2 && this.limitState2 != 2) {
  97360. omega = 6.2831853 * frequency2;
  97361. k = omega * omega * timeStep;
  97362. dmp = invTimeStep / (k + 2 * this.limitMotor2.dampingRatio * omega);
  97363. this.cfm2 = this.kv11 * dmp;
  97364. this.limitVelocity2 *= k * dmp;
  97365. } else {
  97366. this.cfm2 = 0;
  97367. this.limitVelocity2 *= invTimeStep * 0.05;
  97368. }
  97369. if (enableSpring3 && this.limitState3 != 2) {
  97370. omega = 6.2831853 * frequency3;
  97371. k = omega * omega * timeStep;
  97372. dmp = invTimeStep / (k + 2 * this.limitMotor3.dampingRatio * omega);
  97373. this.cfm3 = this.kv22 * dmp;
  97374. this.limitVelocity3 *= k * dmp;
  97375. } else {
  97376. this.cfm3 = 0;
  97377. this.limitVelocity3 *= invTimeStep * 0.05;
  97378. }
  97379. this.k00 += this.cfm1;
  97380. this.k11 += this.cfm2;
  97381. this.k22 += this.cfm3;
  97382. var inv = 1 / (
  97383. this.k00 * (this.k11 * this.k22 - this.k21 * this.k12) +
  97384. this.k10 * (this.k21 * this.k02 - this.k01 * this.k22) +
  97385. this.k20 * (this.k01 * this.k12 - this.k11 * this.k02)
  97386. );
  97387. this.d00 = (this.k11 * this.k22 - this.k12 * this.k21) * inv;
  97388. this.d01 = (this.k02 * this.k21 - this.k01 * this.k22) * inv;
  97389. this.d02 = (this.k01 * this.k12 - this.k02 * this.k11) * inv;
  97390. this.d10 = (this.k12 * this.k20 - this.k10 * this.k22) * inv;
  97391. this.d11 = (this.k00 * this.k22 - this.k02 * this.k20) * inv;
  97392. this.d12 = (this.k02 * this.k10 - this.k00 * this.k12) * inv;
  97393. this.d20 = (this.k10 * this.k21 - this.k11 * this.k20) * inv;
  97394. this.d21 = (this.k01 * this.k20 - this.k00 * this.k21) * inv;
  97395. this.d22 = (this.k00 * this.k11 - this.k01 * this.k10) * inv;
  97396. // warm starting
  97397. var totalImpulse1 = this.limitImpulse1 + this.motorImpulse1;
  97398. var totalImpulse2 = this.limitImpulse2 + this.motorImpulse2;
  97399. var totalImpulse3 = this.limitImpulse3 + this.motorImpulse3;
  97400. this.l1.x += totalImpulse1 * this.l1x1 + totalImpulse2 * this.l1x2 + totalImpulse3 * this.l1x3;
  97401. this.l1.y += totalImpulse1 * this.l1y1 + totalImpulse2 * this.l1y2 + totalImpulse3 * this.l1y3;
  97402. this.l1.z += totalImpulse1 * this.l1z1 + totalImpulse2 * this.l1z2 + totalImpulse3 * this.l1z3;
  97403. this.a1.x += totalImpulse1 * this.a1x1 + totalImpulse2 * this.a1x2 + totalImpulse3 * this.a1x3;
  97404. this.a1.y += totalImpulse1 * this.a1y1 + totalImpulse2 * this.a1y2 + totalImpulse3 * this.a1y3;
  97405. this.a1.z += totalImpulse1 * this.a1z1 + totalImpulse2 * this.a1z2 + totalImpulse3 * this.a1z3;
  97406. this.l2.x -= totalImpulse1 * this.l2x1 + totalImpulse2 * this.l2x2 + totalImpulse3 * this.l2x3;
  97407. this.l2.y -= totalImpulse1 * this.l2y1 + totalImpulse2 * this.l2y2 + totalImpulse3 * this.l2y3;
  97408. this.l2.z -= totalImpulse1 * this.l2z1 + totalImpulse2 * this.l2z2 + totalImpulse3 * this.l2z3;
  97409. this.a2.x -= totalImpulse1 * this.a2x1 + totalImpulse2 * this.a2x2 + totalImpulse3 * this.a2x3;
  97410. this.a2.y -= totalImpulse1 * this.a2y1 + totalImpulse2 * this.a2y2 + totalImpulse3 * this.a2y3;
  97411. this.a2.z -= totalImpulse1 * this.a2z1 + totalImpulse2 * this.a2z2 + totalImpulse3 * this.a2z3;
  97412. },
  97413. solve: function () {
  97414. var rvx = this.l2.x - this.l1.x + this.a2.y * this.r2z - this.a2.z * this.r2y - this.a1.y * this.r1z + this.a1.z * this.r1y;
  97415. var rvy = this.l2.y - this.l1.y + this.a2.z * this.r2x - this.a2.x * this.r2z - this.a1.z * this.r1x + this.a1.x * this.r1z;
  97416. var rvz = this.l2.z - this.l1.z + this.a2.x * this.r2y - this.a2.y * this.r2x - this.a1.x * this.r1y + this.a1.y * this.r1x;
  97417. var rvn1 = rvx * this.ax1 + rvy * this.ay1 + rvz * this.az1;
  97418. var rvn2 = rvx * this.ax2 + rvy * this.ay2 + rvz * this.az2;
  97419. var rvn3 = rvx * this.ax3 + rvy * this.ay3 + rvz * this.az3;
  97420. var oldMotorImpulse1 = this.motorImpulse1;
  97421. var oldMotorImpulse2 = this.motorImpulse2;
  97422. var oldMotorImpulse3 = this.motorImpulse3;
  97423. var dMotorImpulse1 = 0;
  97424. var dMotorImpulse2 = 0;
  97425. var dMotorImpulse3 = 0;
  97426. if (this.enableMotor1) {
  97427. dMotorImpulse1 = (rvn1 - this.motorSpeed1) * this.dv00;
  97428. this.motorImpulse1 += dMotorImpulse1;
  97429. if (this.motorImpulse1 > this.maxMotorImpulse1) { // clamp motor impulse
  97430. this.motorImpulse1 = this.maxMotorImpulse1;
  97431. } else if (this.motorImpulse1 < -this.maxMotorImpulse1) {
  97432. this.motorImpulse1 = -this.maxMotorImpulse1;
  97433. }
  97434. dMotorImpulse1 = this.motorImpulse1 - oldMotorImpulse1;
  97435. }
  97436. if (this.enableMotor2) {
  97437. dMotorImpulse2 = (rvn2 - this.motorSpeed2) * this.dv11;
  97438. this.motorImpulse2 += dMotorImpulse2;
  97439. if (this.motorImpulse2 > this.maxMotorImpulse2) { // clamp motor impulse
  97440. this.motorImpulse2 = this.maxMotorImpulse2;
  97441. } else if (this.motorImpulse2 < -this.maxMotorImpulse2) {
  97442. this.motorImpulse2 = -this.maxMotorImpulse2;
  97443. }
  97444. dMotorImpulse2 = this.motorImpulse2 - oldMotorImpulse2;
  97445. }
  97446. if (this.enableMotor3) {
  97447. dMotorImpulse3 = (rvn3 - this.motorSpeed3) * this.dv22;
  97448. this.motorImpulse3 += dMotorImpulse3;
  97449. if (this.motorImpulse3 > this.maxMotorImpulse3) { // clamp motor impulse
  97450. this.motorImpulse3 = this.maxMotorImpulse3;
  97451. } else if (this.motorImpulse3 < -this.maxMotorImpulse3) {
  97452. this.motorImpulse3 = -this.maxMotorImpulse3;
  97453. }
  97454. dMotorImpulse3 = this.motorImpulse3 - oldMotorImpulse3;
  97455. }
  97456. // apply motor impulse to relative velocity
  97457. rvn1 += dMotorImpulse1 * this.kv00 + dMotorImpulse2 * this.k01 + dMotorImpulse3 * this.k02;
  97458. rvn2 += dMotorImpulse1 * this.k10 + dMotorImpulse2 * this.kv11 + dMotorImpulse3 * this.k12;
  97459. rvn3 += dMotorImpulse1 * this.k20 + dMotorImpulse2 * this.k21 + dMotorImpulse3 * this.kv22;
  97460. // subtract target velocity and applied impulse
  97461. rvn1 -= this.limitVelocity1 + this.limitImpulse1 * this.cfm1;
  97462. rvn2 -= this.limitVelocity2 + this.limitImpulse2 * this.cfm2;
  97463. rvn3 -= this.limitVelocity3 + this.limitImpulse3 * this.cfm3;
  97464. var oldLimitImpulse1 = this.limitImpulse1;
  97465. var oldLimitImpulse2 = this.limitImpulse2;
  97466. var oldLimitImpulse3 = this.limitImpulse3;
  97467. var dLimitImpulse1 = rvn1 * this.d00 + rvn2 * this.d01 + rvn3 * this.d02;
  97468. var dLimitImpulse2 = rvn1 * this.d10 + rvn2 * this.d11 + rvn3 * this.d12;
  97469. var dLimitImpulse3 = rvn1 * this.d20 + rvn2 * this.d21 + rvn3 * this.d22;
  97470. this.limitImpulse1 += dLimitImpulse1;
  97471. this.limitImpulse2 += dLimitImpulse2;
  97472. this.limitImpulse3 += dLimitImpulse3;
  97473. // clamp
  97474. var clampState = 0;
  97475. if (this.limitState1 == 2 || this.limitImpulse1 * this.limitState1 < 0) {
  97476. dLimitImpulse1 = -oldLimitImpulse1;
  97477. rvn2 += dLimitImpulse1 * this.k10;
  97478. rvn3 += dLimitImpulse1 * this.k20;
  97479. clampState |= 1;
  97480. }
  97481. if (this.limitState2 == 2 || this.limitImpulse2 * this.limitState2 < 0) {
  97482. dLimitImpulse2 = -oldLimitImpulse2;
  97483. rvn1 += dLimitImpulse2 * this.k01;
  97484. rvn3 += dLimitImpulse2 * this.k21;
  97485. clampState |= 2;
  97486. }
  97487. if (this.limitState3 == 2 || this.limitImpulse3 * this.limitState3 < 0) {
  97488. dLimitImpulse3 = -oldLimitImpulse3;
  97489. rvn1 += dLimitImpulse3 * this.k02;
  97490. rvn2 += dLimitImpulse3 * this.k12;
  97491. clampState |= 4;
  97492. }
  97493. // update un-clamped impulse
  97494. // TODO: isolate division
  97495. var det;
  97496. switch (clampState) {
  97497. case 1:// update 2 3
  97498. det = 1 / (this.k11 * this.k22 - this.k12 * this.k21);
  97499. dLimitImpulse2 = (this.k22 * rvn2 + -this.k12 * rvn3) * det;
  97500. dLimitImpulse3 = (-this.k21 * rvn2 + this.k11 * rvn3) * det;
  97501. break;
  97502. case 2:// update 1 3
  97503. det = 1 / (this.k00 * this.k22 - this.k02 * this.k20);
  97504. dLimitImpulse1 = (this.k22 * rvn1 + -this.k02 * rvn3) * det;
  97505. dLimitImpulse3 = (-this.k20 * rvn1 + this.k00 * rvn3) * det;
  97506. break;
  97507. case 3:// update 3
  97508. dLimitImpulse3 = rvn3 / this.k22;
  97509. break;
  97510. case 4:// update 1 2
  97511. det = 1 / (this.k00 * this.k11 - this.k01 * this.k10);
  97512. dLimitImpulse1 = (this.k11 * rvn1 + -this.k01 * rvn2) * det;
  97513. dLimitImpulse2 = (-this.k10 * rvn1 + this.k00 * rvn2) * det;
  97514. break;
  97515. case 5:// update 2
  97516. dLimitImpulse2 = rvn2 / this.k11;
  97517. break;
  97518. case 6:// update 1
  97519. dLimitImpulse1 = rvn1 / this.k00;
  97520. break;
  97521. }
  97522. this.limitImpulse1 = oldLimitImpulse1 + dLimitImpulse1;
  97523. this.limitImpulse2 = oldLimitImpulse2 + dLimitImpulse2;
  97524. this.limitImpulse3 = oldLimitImpulse3 + dLimitImpulse3;
  97525. var dImpulse1 = dMotorImpulse1 + dLimitImpulse1;
  97526. var dImpulse2 = dMotorImpulse2 + dLimitImpulse2;
  97527. var dImpulse3 = dMotorImpulse3 + dLimitImpulse3;
  97528. // apply impulse
  97529. this.l1.x += dImpulse1 * this.l1x1 + dImpulse2 * this.l1x2 + dImpulse3 * this.l1x3;
  97530. this.l1.y += dImpulse1 * this.l1y1 + dImpulse2 * this.l1y2 + dImpulse3 * this.l1y3;
  97531. this.l1.z += dImpulse1 * this.l1z1 + dImpulse2 * this.l1z2 + dImpulse3 * this.l1z3;
  97532. this.a1.x += dImpulse1 * this.a1x1 + dImpulse2 * this.a1x2 + dImpulse3 * this.a1x3;
  97533. this.a1.y += dImpulse1 * this.a1y1 + dImpulse2 * this.a1y2 + dImpulse3 * this.a1y3;
  97534. this.a1.z += dImpulse1 * this.a1z1 + dImpulse2 * this.a1z2 + dImpulse3 * this.a1z3;
  97535. this.l2.x -= dImpulse1 * this.l2x1 + dImpulse2 * this.l2x2 + dImpulse3 * this.l2x3;
  97536. this.l2.y -= dImpulse1 * this.l2y1 + dImpulse2 * this.l2y2 + dImpulse3 * this.l2y3;
  97537. this.l2.z -= dImpulse1 * this.l2z1 + dImpulse2 * this.l2z2 + dImpulse3 * this.l2z3;
  97538. this.a2.x -= dImpulse1 * this.a2x1 + dImpulse2 * this.a2x2 + dImpulse3 * this.a2x3;
  97539. this.a2.y -= dImpulse1 * this.a2y1 + dImpulse2 * this.a2y2 + dImpulse3 * this.a2y3;
  97540. this.a2.z -= dImpulse1 * this.a2z1 + dImpulse2 * this.a2z2 + dImpulse3 * this.a2z3;
  97541. }
  97542. }
  97543. /**
  97544. * A translational constraint for various joints.
  97545. * @author saharan
  97546. */
  97547. OIMO.TranslationalConstraint = function (joint, limitMotor) {
  97548. this.cfm = NaN;
  97549. this.m1 = NaN;
  97550. this.m2 = NaN;
  97551. this.i1e00 = NaN;
  97552. this.i1e01 = NaN;
  97553. this.i1e02 = NaN;
  97554. this.i1e10 = NaN;
  97555. this.i1e11 = NaN;
  97556. this.i1e12 = NaN;
  97557. this.i1e20 = NaN;
  97558. this.i1e21 = NaN;
  97559. this.i1e22 = NaN;
  97560. this.i2e00 = NaN;
  97561. this.i2e01 = NaN;
  97562. this.i2e02 = NaN;
  97563. this.i2e10 = NaN;
  97564. this.i2e11 = NaN;
  97565. this.i2e12 = NaN;
  97566. this.i2e20 = NaN;
  97567. this.i2e21 = NaN;
  97568. this.i2e22 = NaN;
  97569. this.motorDenom = NaN;
  97570. this.invMotorDenom = NaN;
  97571. this.invDenom = NaN;
  97572. this.ax = NaN;
  97573. this.ay = NaN;
  97574. this.az = NaN;
  97575. this.r1x = NaN;
  97576. this.r1y = NaN;
  97577. this.r1z = NaN;
  97578. this.r2x = NaN;
  97579. this.r2y = NaN;
  97580. this.r2z = NaN;
  97581. this.t1x = NaN;
  97582. this.t1y = NaN;
  97583. this.t1z = NaN;
  97584. this.t2x = NaN;
  97585. this.t2y = NaN;
  97586. this.t2z = NaN;
  97587. this.l1x = NaN;
  97588. this.l1y = NaN;
  97589. this.l1z = NaN;
  97590. this.l2x = NaN;
  97591. this.l2y = NaN;
  97592. this.l2z = NaN;
  97593. this.a1x = NaN;
  97594. this.a1y = NaN;
  97595. this.a1z = NaN;
  97596. this.a2x = NaN;
  97597. this.a2y = NaN;
  97598. this.a2z = NaN;
  97599. this.lowerLimit = NaN;
  97600. this.upperLimit = NaN;
  97601. this.limitVelocity = NaN;
  97602. this.limitState = 0; // -1: at lower, 0: locked, 1: at upper, 2: free
  97603. this.enableMotor = false;
  97604. this.motorSpeed = NaN;
  97605. this.maxMotorForce = NaN;
  97606. this.maxMotorImpulse = NaN;
  97607. this.limitMotor = limitMotor;
  97608. this.b1 = joint.body1;
  97609. this.b2 = joint.body2;
  97610. this.p1 = joint.anchorPoint1;
  97611. this.p2 = joint.anchorPoint2;
  97612. this.r1 = joint.relativeAnchorPoint1;
  97613. this.r2 = joint.relativeAnchorPoint2;
  97614. this.l1 = this.b1.linearVelocity;
  97615. this.l2 = this.b2.linearVelocity;
  97616. this.a1 = this.b1.angularVelocity;
  97617. this.a2 = this.b2.angularVelocity;
  97618. this.i1 = this.b1.inverseInertia;
  97619. this.i2 = this.b2.inverseInertia;
  97620. this.limitImpulse = 0;
  97621. this.motorImpulse = 0;
  97622. }
  97623. OIMO.TranslationalConstraint.prototype = {
  97624. constructor: OIMO.TranslationalConstraint,
  97625. preSolve: function (timeStep, invTimeStep) {
  97626. this.ax = this.limitMotor.axis.x;
  97627. this.ay = this.limitMotor.axis.y;
  97628. this.az = this.limitMotor.axis.z;
  97629. this.lowerLimit = this.limitMotor.lowerLimit;
  97630. this.upperLimit = this.limitMotor.upperLimit;
  97631. this.motorSpeed = this.limitMotor.motorSpeed;
  97632. this.maxMotorForce = this.limitMotor.maxMotorForce;
  97633. this.enableMotor = this.maxMotorForce > 0;
  97634. this.m1 = this.b1.inverseMass;
  97635. this.m2 = this.b2.inverseMass;
  97636. var ti1 = this.i1.elements;
  97637. var ti2 = this.i2.elements;
  97638. this.i1e00 = ti1[0];
  97639. this.i1e01 = ti1[1];
  97640. this.i1e02 = ti1[2];
  97641. this.i1e10 = ti1[3];
  97642. this.i1e11 = ti1[4];
  97643. this.i1e12 = ti1[5];
  97644. this.i1e20 = ti1[6];
  97645. this.i1e21 = ti1[7];
  97646. this.i1e22 = ti1[8];
  97647. this.i2e00 = ti2[0];
  97648. this.i2e01 = ti2[1];
  97649. this.i2e02 = ti2[2];
  97650. this.i2e10 = ti2[3];
  97651. this.i2e11 = ti2[4];
  97652. this.i2e12 = ti2[5];
  97653. this.i2e20 = ti2[6];
  97654. this.i2e21 = ti2[7];
  97655. this.i2e22 = ti2[8];
  97656. var dx = this.p2.x - this.p1.x;
  97657. var dy = this.p2.y - this.p1.y;
  97658. var dz = this.p2.z - this.p1.z;
  97659. var d = dx * this.ax + dy * this.ay + dz * this.az;
  97660. var frequency = this.limitMotor.frequency;
  97661. var enableSpring = frequency > 0;
  97662. var enableLimit = this.lowerLimit <= this.upperLimit;
  97663. if (enableSpring && d > 20 || d < -20) {
  97664. enableSpring = false;
  97665. }
  97666. if (enableLimit) {
  97667. if (this.lowerLimit == this.upperLimit) {
  97668. if (this.limitState != 0) {
  97669. this.limitState = 0;
  97670. this.limitImpulse = 0;
  97671. }
  97672. this.limitVelocity = this.lowerLimit - d;
  97673. if (!enableSpring) d = this.lowerLimit;
  97674. } else if (d < this.lowerLimit) {
  97675. if (this.limitState != -1) {
  97676. this.limitState = -1;
  97677. this.limitImpulse = 0;
  97678. }
  97679. this.limitVelocity = this.lowerLimit - d;
  97680. if (!enableSpring) d = this.lowerLimit;
  97681. } else if (d > this.upperLimit) {
  97682. if (this.limitState != 1) {
  97683. this.limitState = 1;
  97684. this.limitImpulse = 0;
  97685. }
  97686. this.limitVelocity = this.upperLimit - d;
  97687. if (!enableSpring) d = this.upperLimit;
  97688. } else {
  97689. this.limitState = 2;
  97690. this.limitImpulse = 0;
  97691. this.limitVelocity = 0;
  97692. }
  97693. if (!enableSpring) {
  97694. if (this.limitVelocity > 0.005) this.limitVelocity -= 0.005;
  97695. else if (this.limitVelocity < -0.005) this.limitVelocity += 0.005;
  97696. else this.limitVelocity = 0;
  97697. }
  97698. } else {
  97699. this.limitState = 2;
  97700. this.limitImpulse = 0;
  97701. }
  97702. if (this.enableMotor && (this.limitState != 0 || enableSpring)) {
  97703. this.maxMotorImpulse = this.maxMotorForce * timeStep;
  97704. } else {
  97705. this.motorImpulse = 0;
  97706. this.maxMotorImpulse = 0;
  97707. }
  97708. var rdx = d * this.ax;
  97709. var rdy = d * this.ay;
  97710. var rdz = d * this.az;
  97711. var w1 = this.m1 / (this.m1 + this.m2);
  97712. var w2 = 1 - w1;
  97713. this.r1x = this.r1.x + rdx * w1;
  97714. this.r1y = this.r1.y + rdy * w1;
  97715. this.r1z = this.r1.z + rdz * w1;
  97716. this.r2x = this.r2.x - rdx * w2;
  97717. this.r2y = this.r2.y - rdy * w2;
  97718. this.r2z = this.r2.z - rdz * w2;
  97719. this.t1x = this.r1y * this.az - this.r1z * this.ay;
  97720. this.t1y = this.r1z * this.ax - this.r1x * this.az;
  97721. this.t1z = this.r1x * this.ay - this.r1y * this.ax;
  97722. this.t2x = this.r2y * this.az - this.r2z * this.ay;
  97723. this.t2y = this.r2z * this.ax - this.r2x * this.az;
  97724. this.t2z = this.r2x * this.ay - this.r2y * this.ax;
  97725. this.l1x = this.ax * this.m1;
  97726. this.l1y = this.ay * this.m1;
  97727. this.l1z = this.az * this.m1;
  97728. this.l2x = this.ax * this.m2;
  97729. this.l2y = this.ay * this.m2;
  97730. this.l2z = this.az * this.m2;
  97731. this.a1x = this.t1x * this.i1e00 + this.t1y * this.i1e01 + this.t1z * this.i1e02;
  97732. this.a1y = this.t1x * this.i1e10 + this.t1y * this.i1e11 + this.t1z * this.i1e12;
  97733. this.a1z = this.t1x * this.i1e20 + this.t1y * this.i1e21 + this.t1z * this.i1e22;
  97734. this.a2x = this.t2x * this.i2e00 + this.t2y * this.i2e01 + this.t2z * this.i2e02;
  97735. this.a2y = this.t2x * this.i2e10 + this.t2y * this.i2e11 + this.t2z * this.i2e12;
  97736. this.a2z = this.t2x * this.i2e20 + this.t2y * this.i2e21 + this.t2z * this.i2e22;
  97737. this.motorDenom =
  97738. this.m1 + this.m2 +
  97739. this.ax * (this.a1y * this.r1z - this.a1z * this.r1y + this.a2y * this.r2z - this.a2z * this.r2y) +
  97740. this.ay * (this.a1z * this.r1x - this.a1x * this.r1z + this.a2z * this.r2x - this.a2x * this.r2z) +
  97741. this.az * (this.a1x * this.r1y - this.a1y * this.r1x + this.a2x * this.r2y - this.a2y * this.r2x);
  97742. this.invMotorDenom = 1 / this.motorDenom;
  97743. if (enableSpring && this.limitState != 2) {
  97744. var omega = 6.2831853 * frequency;
  97745. var k = omega * omega * timeStep;
  97746. var dmp = invTimeStep / (k + 2 * this.limitMotor.dampingRatio * omega);
  97747. this.cfm = this.motorDenom * dmp;
  97748. this.limitVelocity *= k * dmp;
  97749. } else {
  97750. this.cfm = 0;
  97751. this.limitVelocity *= invTimeStep * 0.05;
  97752. }
  97753. this.invDenom = 1 / (this.motorDenom + this.cfm);
  97754. var totalImpulse = this.limitImpulse + this.motorImpulse;
  97755. this.l1.x += totalImpulse * this.l1x;
  97756. this.l1.y += totalImpulse * this.l1y;
  97757. this.l1.z += totalImpulse * this.l1z;
  97758. this.a1.x += totalImpulse * this.a1x;
  97759. this.a1.y += totalImpulse * this.a1y;
  97760. this.a1.z += totalImpulse * this.a1z;
  97761. this.l2.x -= totalImpulse * this.l2x;
  97762. this.l2.y -= totalImpulse * this.l2y;
  97763. this.l2.z -= totalImpulse * this.l2z;
  97764. this.a2.x -= totalImpulse * this.a2x;
  97765. this.a2.y -= totalImpulse * this.a2y;
  97766. this.a2.z -= totalImpulse * this.a2z;
  97767. },
  97768. solve: function () {
  97769. var rvn =
  97770. this.ax * (this.l2.x - this.l1.x) + this.ay * (this.l2.y - this.l1.y) + this.az * (this.l2.z - this.l1.z) +
  97771. this.t2x * this.a2.x - this.t1x * this.a1.x + this.t2y * this.a2.y - this.t1y * this.a1.y + this.t2z * this.a2.z - this.t1z * this.a1.z;
  97772. // motor part
  97773. var newMotorImpulse;
  97774. if (this.enableMotor) {
  97775. newMotorImpulse = (rvn - this.motorSpeed) * this.invMotorDenom;
  97776. var oldMotorImpulse = this.motorImpulse;
  97777. this.motorImpulse += newMotorImpulse;
  97778. if (this.motorImpulse > this.maxMotorImpulse) this.motorImpulse = this.maxMotorImpulse;
  97779. else if (this.motorImpulse < -this.maxMotorImpulse) this.motorImpulse = -this.maxMotorImpulse;
  97780. newMotorImpulse = this.motorImpulse - oldMotorImpulse;
  97781. rvn -= newMotorImpulse * this.motorDenom;
  97782. } else newMotorImpulse = 0;
  97783. // limit part
  97784. var newLimitImpulse;
  97785. if (this.limitState != 2) {
  97786. newLimitImpulse = (rvn - this.limitVelocity - this.limitImpulse * this.cfm) * this.invDenom;
  97787. var oldLimitImpulse = this.limitImpulse;
  97788. this.limitImpulse += newLimitImpulse;
  97789. if (this.limitImpulse * this.limitState < 0) this.limitImpulse = 0;
  97790. newLimitImpulse = this.limitImpulse - oldLimitImpulse;
  97791. } else newLimitImpulse = 0;
  97792. var totalImpulse = newLimitImpulse + newMotorImpulse;
  97793. this.l1.x += totalImpulse * this.l1x;
  97794. this.l1.y += totalImpulse * this.l1y;
  97795. this.l1.z += totalImpulse * this.l1z;
  97796. this.a1.x += totalImpulse * this.a1x;
  97797. this.a1.y += totalImpulse * this.a1y;
  97798. this.a1.z += totalImpulse * this.a1z;
  97799. this.l2.x -= totalImpulse * this.l2x;
  97800. this.l2.y -= totalImpulse * this.l2y;
  97801. this.l2.z -= totalImpulse * this.l2z;
  97802. this.a2.x -= totalImpulse * this.a2x;
  97803. this.a2.y -= totalImpulse * this.a2y;
  97804. this.a2.z -= totalImpulse * this.a2z;
  97805. }
  97806. }
  97807. /**
  97808. * A contact is a pair of shapes whose axis-aligned bounding boxes are overlapping.
  97809. * @author saharan
  97810. */
  97811. OIMO.Contact = function () {
  97812. // The first shape.
  97813. this.shape1 = null;
  97814. // The second shape.
  97815. this.shape2 = null;
  97816. // The first rigid body.
  97817. this.body1 = null;
  97818. // The second rigid body.
  97819. this.body2 = null;
  97820. // The previous contact in the world.
  97821. this.prev = null;
  97822. // The next contact in the world.
  97823. this.next = null;
  97824. // Internal
  97825. this.persisting = false;
  97826. // Whether both the rigid bodies are sleeping or not.
  97827. this.sleeping = false;
  97828. // The collision detector between two shapes.
  97829. this.detector = null;
  97830. // The contact constraint of the contact.
  97831. this.constraint = null;
  97832. // Whether the shapes are touching or not.
  97833. this.touching = false;
  97834. this.b1Link = new OIMO.ContactLink(this);
  97835. this.b2Link = new OIMO.ContactLink(this);
  97836. this.s1Link = new OIMO.ContactLink(this);
  97837. this.s2Link = new OIMO.ContactLink(this);
  97838. // The contact manifold of the contact.
  97839. this.manifold = new OIMO.ContactManifold();
  97840. this.buffer = [];// vector 4
  97841. this.buffer.length = 4;
  97842. this.buffer[0] = new OIMO.ImpulseDataBuffer();
  97843. this.buffer[1] = new OIMO.ImpulseDataBuffer();
  97844. this.buffer[2] = new OIMO.ImpulseDataBuffer();
  97845. this.buffer[3] = new OIMO.ImpulseDataBuffer();
  97846. this.points = this.manifold.points;
  97847. this.constraint = new OIMO.ContactConstraint(this.manifold);
  97848. }
  97849. OIMO.Contact.prototype = {
  97850. constructor: OIMO.Contact,
  97851. mixRestitution: function (restitution1, restitution2) {
  97852. return OIMO.sqrt(restitution1 * restitution2);
  97853. },
  97854. mixFriction: function (friction1, friction2) {
  97855. return OIMO.sqrt(friction1 * friction2);
  97856. },
  97857. /**
  97858. * Update the contact manifold.
  97859. */
  97860. updateManifold: function () {
  97861. this.constraint.restitution = this.mixRestitution(this.shape1.restitution, this.shape2.restitution);
  97862. this.constraint.friction = this.mixFriction(this.shape1.friction, this.shape2.friction);
  97863. var numBuffers = this.manifold.numPoints;
  97864. var i = numBuffers;
  97865. while (i--) {
  97866. //for(var i=0;i<numBuffers;i++){
  97867. var b = this.buffer[i];
  97868. var p = this.points[i];
  97869. b.lp1X = p.localPoint1.x;
  97870. b.lp1Y = p.localPoint1.y;
  97871. b.lp1Z = p.localPoint1.z;
  97872. b.lp2X = p.localPoint2.x;
  97873. b.lp2Y = p.localPoint2.y;
  97874. b.lp2Z = p.localPoint2.z;
  97875. b.impulse = p.normalImpulse;
  97876. }
  97877. this.manifold.numPoints = 0;
  97878. this.detector.detectCollision(this.shape1, this.shape2, this.manifold);
  97879. var num = this.manifold.numPoints;
  97880. if (num == 0) {
  97881. this.touching = false;
  97882. return;
  97883. }
  97884. this.touching = true;
  97885. i = num;
  97886. while (i--) {
  97887. //for(i=0; i<num; i++){
  97888. p = this.points[i];
  97889. var lp1x = p.localPoint1.x;
  97890. var lp1y = p.localPoint1.y;
  97891. var lp1z = p.localPoint1.z;
  97892. var lp2x = p.localPoint2.x;
  97893. var lp2y = p.localPoint2.y;
  97894. var lp2z = p.localPoint2.z;
  97895. var index = -1;
  97896. var minDistance = 0.0004;
  97897. var j = numBuffers;
  97898. while (j--) {
  97899. //for(var j=0;j<numBuffers;j++){
  97900. b = this.buffer[j];
  97901. var dx = b.lp1X - lp1x;
  97902. var dy = b.lp1Y - lp1y;
  97903. var dz = b.lp1Z - lp1z;
  97904. var distance1 = dx * dx + dy * dy + dz * dz;
  97905. dx = b.lp2X - lp2x;
  97906. dy = b.lp2Y - lp2y;
  97907. dz = b.lp2Z - lp2z;
  97908. var distance2 = dx * dx + dy * dy + dz * dz;
  97909. if (distance1 < distance2) {
  97910. if (distance1 < minDistance) {
  97911. minDistance = distance1;
  97912. index = j;
  97913. }
  97914. } else {
  97915. if (distance2 < minDistance) {
  97916. minDistance = distance2;
  97917. index = j;
  97918. }
  97919. }
  97920. }
  97921. if (index != -1) {
  97922. var tmp = this.buffer[index];
  97923. this.buffer[index] = this.buffer[--numBuffers];
  97924. this.buffer[numBuffers] = tmp;
  97925. p.normalImpulse = tmp.impulse;
  97926. p.warmStarted = true;
  97927. } else {
  97928. p.normalImpulse = 0;
  97929. p.warmStarted = false;
  97930. }
  97931. }
  97932. },
  97933. /**
  97934. * Attach the contact to the shapes.
  97935. * @param shape1
  97936. * @param shape2
  97937. */
  97938. attach: function (shape1, shape2) {
  97939. this.shape1 = shape1;
  97940. this.shape2 = shape2;
  97941. this.body1 = shape1.parent;
  97942. this.body2 = shape2.parent;
  97943. this.manifold.body1 = this.body1;
  97944. this.manifold.body2 = this.body2;
  97945. this.constraint.body1 = this.body1;
  97946. this.constraint.body2 = this.body2;
  97947. this.constraint.attach();
  97948. this.s1Link.shape = shape2;
  97949. this.s1Link.body = this.body2;
  97950. this.s2Link.shape = shape1;
  97951. this.s2Link.body = this.body1;
  97952. if (shape1.contactLink != null) (this.s1Link.next = shape1.contactLink).prev = this.s1Link;
  97953. else this.s1Link.next = null;
  97954. shape1.contactLink = this.s1Link;
  97955. shape1.numContacts++;
  97956. if (shape2.contactLink != null) (this.s2Link.next = shape2.contactLink).prev = this.s2Link;
  97957. else this.s2Link.next = null;
  97958. shape2.contactLink = this.s2Link;
  97959. shape2.numContacts++;
  97960. this.b1Link.shape = shape2;
  97961. this.b1Link.body = this.body2;
  97962. this.b2Link.shape = shape1;
  97963. this.b2Link.body = this.body1;
  97964. if (this.body1.contactLink != null) (this.b1Link.next = this.body1.contactLink).prev = this.b1Link;
  97965. else this.b1Link.next = null;
  97966. this.body1.contactLink = this.b1Link;
  97967. this.body1.numContacts++;
  97968. if (this.body2.contactLink != null) (this.b2Link.next = this.body2.contactLink).prev = this.b2Link;
  97969. else this.b2Link.next = null;
  97970. this.body2.contactLink = this.b2Link;
  97971. this.body2.numContacts++;
  97972. this.prev = null;
  97973. this.next = null;
  97974. this.persisting = true;
  97975. this.sleeping = this.body1.sleeping && this.body2.sleeping;
  97976. this.manifold.numPoints = 0;
  97977. },
  97978. /**
  97979. * Detach the contact from the shapes.
  97980. */
  97981. detach: function () {
  97982. var prev = this.s1Link.prev;
  97983. var next = this.s1Link.next;
  97984. if (prev !== null) prev.next = next;
  97985. if (next !== null) next.prev = prev;
  97986. if (this.shape1.contactLink == this.s1Link) this.shape1.contactLink = next;
  97987. this.s1Link.prev = null;
  97988. this.s1Link.next = null;
  97989. this.s1Link.shape = null;
  97990. this.s1Link.body = null;
  97991. this.shape1.numContacts--;
  97992. prev = this.s2Link.prev;
  97993. next = this.s2Link.next;
  97994. if (prev !== null) prev.next = next;
  97995. if (next !== null) next.prev = prev;
  97996. if (this.shape2.contactLink == this.s2Link) this.shape2.contactLink = next;
  97997. this.s2Link.prev = null;
  97998. this.s2Link.next = null;
  97999. this.s2Link.shape = null;
  98000. this.s2Link.body = null;
  98001. this.shape2.numContacts--;
  98002. prev = this.b1Link.prev;
  98003. next = this.b1Link.next;
  98004. if (prev !== null) prev.next = next;
  98005. if (next !== null) next.prev = prev;
  98006. if (this.body1.contactLink == this.b1Link) this.body1.contactLink = next;
  98007. this.b1Link.prev = null;
  98008. this.b1Link.next = null;
  98009. this.b1Link.shape = null;
  98010. this.b1Link.body = null;
  98011. this.body1.numContacts--;
  98012. prev = this.b2Link.prev;
  98013. next = this.b2Link.next;
  98014. if (prev !== null) prev.next = next;
  98015. if (next !== null) next.prev = prev;
  98016. if (this.body2.contactLink == this.b2Link) this.body2.contactLink = next;
  98017. this.b2Link.prev = null;
  98018. this.b2Link.next = null;
  98019. this.b2Link.shape = null;
  98020. this.b2Link.body = null;
  98021. this.body2.numContacts--;
  98022. this.manifold.body1 = null;
  98023. this.manifold.body2 = null;
  98024. this.constraint.body1 = null;
  98025. this.constraint.body2 = null;
  98026. this.constraint.detach();
  98027. this.shape1 = null;
  98028. this.shape2 = null;
  98029. this.body1 = null;
  98030. this.body2 = null;
  98031. }
  98032. }
  98033. /**
  98034. * ...
  98035. * @author saharan
  98036. */
  98037. OIMO.ContactConstraint = function (manifold) {
  98038. OIMO.Constraint.call(this);
  98039. // The contact manifold of the constraint.
  98040. this.manifold = manifold;
  98041. // The coefficient of restitution of the constraint.
  98042. this.restitution = NaN;
  98043. // The coefficient of friction of the constraint.
  98044. this.friction = NaN;
  98045. this.p1 = null;
  98046. this.p2 = null;
  98047. this.lv1 = null;
  98048. this.lv2 = null;
  98049. this.av1 = null;
  98050. this.av2 = null;
  98051. this.i1 = null;
  98052. this.i2 = null;
  98053. this.ii1 = null;
  98054. this.ii2 = null;
  98055. this.m1 = NaN;
  98056. this.m2 = NaN;
  98057. this.num = 0;
  98058. this.ps = manifold.points;
  98059. this.cs = new OIMO.ContactPointDataBuffer();
  98060. this.cs.next = new OIMO.ContactPointDataBuffer();
  98061. this.cs.next.next = new OIMO.ContactPointDataBuffer();
  98062. this.cs.next.next.next = new OIMO.ContactPointDataBuffer();
  98063. }
  98064. OIMO.ContactConstraint.prototype = Object.create(OIMO.Constraint.prototype);
  98065. /**
  98066. * Attach the constraint to the bodies.
  98067. */
  98068. OIMO.ContactConstraint.prototype.attach = function () {
  98069. this.p1 = this.body1.position;
  98070. this.p2 = this.body2.position;
  98071. this.lv1 = this.body1.linearVelocity;
  98072. this.av1 = this.body1.angularVelocity;
  98073. this.lv2 = this.body2.linearVelocity;
  98074. this.av2 = this.body2.angularVelocity;
  98075. this.i1 = this.body1.inverseInertia;
  98076. this.i2 = this.body2.inverseInertia;
  98077. }
  98078. /**
  98079. * Detach the constraint from the bodies.
  98080. */
  98081. OIMO.ContactConstraint.prototype.detach = function () {
  98082. this.p1 = null;
  98083. this.p2 = null;
  98084. this.lv1 = null;
  98085. this.lv2 = null;
  98086. this.av1 = null;
  98087. this.av2 = null;
  98088. this.i1 = null;
  98089. this.i2 = null;
  98090. }
  98091. OIMO.ContactConstraint.prototype.preSolve = function (timeStep, invTimeStep) {
  98092. this.m1 = this.body1.inverseMass;
  98093. this.m2 = this.body2.inverseMass;
  98094. this.ii1 = this.i1.clone();
  98095. this.ii2 = this.i2.clone();
  98096. var ii1 = this.ii1.elements;
  98097. var ii2 = this.ii2.elements;
  98098. var p1x = this.p1.x;
  98099. var p1y = this.p1.y;
  98100. var p1z = this.p1.z;
  98101. var p2x = this.p2.x;
  98102. var p2y = this.p2.y;
  98103. var p2z = this.p2.z;
  98104. var m1m2 = this.m1 + this.m2;
  98105. this.num = this.manifold.numPoints;
  98106. var c = this.cs;
  98107. for (var i = 0; i < this.num; i++) {
  98108. var p = this.ps[i];
  98109. var tmp1X;
  98110. var tmp1Y;
  98111. var tmp1Z;
  98112. var tmp2X;
  98113. var tmp2Y;
  98114. var tmp2Z;
  98115. tmp1X = p.position.x;
  98116. tmp1Y = p.position.y;
  98117. tmp1Z = p.position.z;
  98118. var rp1X = tmp1X - p1x;
  98119. var rp1Y = tmp1Y - p1y;
  98120. var rp1Z = tmp1Z - p1z;
  98121. var rp2X = tmp1X - p2x;
  98122. var rp2Y = tmp1Y - p2y;
  98123. var rp2Z = tmp1Z - p2z;
  98124. c.rp1X = rp1X;
  98125. c.rp1Y = rp1Y;
  98126. c.rp1Z = rp1Z;
  98127. c.rp2X = rp2X;
  98128. c.rp2Y = rp2Y;
  98129. c.rp2Z = rp2Z;
  98130. c.norImp = p.normalImpulse;
  98131. c.tanImp = p.tangentImpulse;
  98132. c.binImp = p.binormalImpulse;
  98133. var norX = p.normal.x;
  98134. var norY = p.normal.y;
  98135. var norZ = p.normal.z;
  98136. var rvX = (this.lv2.x + this.av2.y * rp2Z - this.av2.z * rp2Y) - (this.lv1.x + this.av1.y * rp1Z - this.av1.z * rp1Y);
  98137. var rvY = (this.lv2.y + this.av2.z * rp2X - this.av2.x * rp2Z) - (this.lv1.y + this.av1.z * rp1X - this.av1.x * rp1Z);
  98138. var rvZ = (this.lv2.z + this.av2.x * rp2Y - this.av2.y * rp2X) - (this.lv1.z + this.av1.x * rp1Y - this.av1.y * rp1X);
  98139. var rvn = norX * rvX + norY * rvY + norZ * rvZ;
  98140. var tanX = rvX - rvn * norX;
  98141. var tanY = rvY - rvn * norY;
  98142. var tanZ = rvZ - rvn * norZ;
  98143. var len = tanX * tanX + tanY * tanY + tanZ * tanZ;
  98144. if (len > 0.04) {
  98145. len = 1 / OIMO.sqrt(len);
  98146. } else {
  98147. tanX = norY * norX - norZ * norZ;
  98148. tanY = -norZ * norY - norX * norX;
  98149. tanZ = norX * norZ + norY * norY;
  98150. len = 1 / OIMO.sqrt(tanX * tanX + tanY * tanY + tanZ * tanZ);
  98151. }
  98152. tanX *= len;
  98153. tanY *= len;
  98154. tanZ *= len;
  98155. var binX = norY * tanZ - norZ * tanY;
  98156. var binY = norZ * tanX - norX * tanZ;
  98157. var binZ = norX * tanY - norY * tanX;
  98158. c.norX = norX;
  98159. c.norY = norY;
  98160. c.norZ = norZ;
  98161. c.tanX = tanX;
  98162. c.tanY = tanY;
  98163. c.tanZ = tanZ;
  98164. c.binX = binX;
  98165. c.binY = binY;
  98166. c.binZ = binZ;
  98167. c.norU1X = norX * this.m1;
  98168. c.norU1Y = norY * this.m1;
  98169. c.norU1Z = norZ * this.m1;
  98170. c.norU2X = norX * this.m2;
  98171. c.norU2Y = norY * this.m2;
  98172. c.norU2Z = norZ * this.m2;
  98173. c.tanU1X = tanX * this.m1;
  98174. c.tanU1Y = tanY * this.m1;
  98175. c.tanU1Z = tanZ * this.m1;
  98176. c.tanU2X = tanX * this.m2;
  98177. c.tanU2Y = tanY * this.m2;
  98178. c.tanU2Z = tanZ * this.m2;
  98179. c.binU1X = binX * this.m1;
  98180. c.binU1Y = binY * this.m1;
  98181. c.binU1Z = binZ * this.m1;
  98182. c.binU2X = binX * this.m2;
  98183. c.binU2Y = binY * this.m2;
  98184. c.binU2Z = binZ * this.m2;
  98185. var norT1X = rp1Y * norZ - rp1Z * norY;
  98186. var norT1Y = rp1Z * norX - rp1X * norZ;
  98187. var norT1Z = rp1X * norY - rp1Y * norX;
  98188. var norT2X = rp2Y * norZ - rp2Z * norY;
  98189. var norT2Y = rp2Z * norX - rp2X * norZ;
  98190. var norT2Z = rp2X * norY - rp2Y * norX;
  98191. var tanT1X = rp1Y * tanZ - rp1Z * tanY;
  98192. var tanT1Y = rp1Z * tanX - rp1X * tanZ;
  98193. var tanT1Z = rp1X * tanY - rp1Y * tanX;
  98194. var tanT2X = rp2Y * tanZ - rp2Z * tanY;
  98195. var tanT2Y = rp2Z * tanX - rp2X * tanZ;
  98196. var tanT2Z = rp2X * tanY - rp2Y * tanX;
  98197. var binT1X = rp1Y * binZ - rp1Z * binY;
  98198. var binT1Y = rp1Z * binX - rp1X * binZ;
  98199. var binT1Z = rp1X * binY - rp1Y * binX;
  98200. var binT2X = rp2Y * binZ - rp2Z * binY;
  98201. var binT2Y = rp2Z * binX - rp2X * binZ;
  98202. var binT2Z = rp2X * binY - rp2Y * binX;
  98203. var norTU1X = norT1X * ii1[0] + norT1Y * ii1[1] + norT1Z * ii1[2];
  98204. var norTU1Y = norT1X * ii1[3] + norT1Y * ii1[4] + norT1Z * ii1[5];
  98205. var norTU1Z = norT1X * ii1[6] + norT1Y * ii1[7] + norT1Z * ii1[8];
  98206. var norTU2X = norT2X * ii2[0] + norT2Y * ii2[1] + norT2Z * ii2[2];
  98207. var norTU2Y = norT2X * ii2[3] + norT2Y * ii2[4] + norT2Z * ii2[5];
  98208. var norTU2Z = norT2X * ii2[6] + norT2Y * ii2[7] + norT2Z * ii2[8];
  98209. var tanTU1X = tanT1X * ii1[0] + tanT1Y * ii1[1] + tanT1Z * ii1[2];
  98210. var tanTU1Y = tanT1X * ii1[3] + tanT1Y * ii1[4] + tanT1Z * ii1[5];
  98211. var tanTU1Z = tanT1X * ii1[6] + tanT1Y * ii1[7] + tanT1Z * ii1[8];
  98212. var tanTU2X = tanT2X * ii2[0] + tanT2Y * ii2[1] + tanT2Z * ii2[2];
  98213. var tanTU2Y = tanT2X * ii2[3] + tanT2Y * ii2[4] + tanT2Z * ii2[5];
  98214. var tanTU2Z = tanT2X * ii2[6] + tanT2Y * ii2[7] + tanT2Z * ii2[8];
  98215. var binTU1X = binT1X * ii1[0] + binT1Y * ii1[1] + binT1Z * ii1[2];
  98216. var binTU1Y = binT1X * ii1[3] + binT1Y * ii1[4] + binT1Z * ii1[5];
  98217. var binTU1Z = binT1X * ii1[6] + binT1Y * ii1[7] + binT1Z * ii1[8];
  98218. var binTU2X = binT2X * ii2[0] + binT2Y * ii2[1] + binT2Z * ii2[2];
  98219. var binTU2Y = binT2X * ii2[3] + binT2Y * ii2[4] + binT2Z * ii2[5];
  98220. var binTU2Z = binT2X * ii2[6] + binT2Y * ii2[7] + binT2Z * ii2[8];
  98221. c.norT1X = norT1X;
  98222. c.norT1Y = norT1Y;
  98223. c.norT1Z = norT1Z;
  98224. c.tanT1X = tanT1X;
  98225. c.tanT1Y = tanT1Y;
  98226. c.tanT1Z = tanT1Z;
  98227. c.binT1X = binT1X;
  98228. c.binT1Y = binT1Y;
  98229. c.binT1Z = binT1Z;
  98230. c.norT2X = norT2X;
  98231. c.norT2Y = norT2Y;
  98232. c.norT2Z = norT2Z;
  98233. c.tanT2X = tanT2X;
  98234. c.tanT2Y = tanT2Y;
  98235. c.tanT2Z = tanT2Z;
  98236. c.binT2X = binT2X;
  98237. c.binT2Y = binT2Y;
  98238. c.binT2Z = binT2Z;
  98239. c.norTU1X = norTU1X;
  98240. c.norTU1Y = norTU1Y;
  98241. c.norTU1Z = norTU1Z;
  98242. c.tanTU1X = tanTU1X;
  98243. c.tanTU1Y = tanTU1Y;
  98244. c.tanTU1Z = tanTU1Z;
  98245. c.binTU1X = binTU1X;
  98246. c.binTU1Y = binTU1Y;
  98247. c.binTU1Z = binTU1Z;
  98248. c.norTU2X = norTU2X;
  98249. c.norTU2Y = norTU2Y;
  98250. c.norTU2Z = norTU2Z;
  98251. c.tanTU2X = tanTU2X;
  98252. c.tanTU2Y = tanTU2Y;
  98253. c.tanTU2Z = tanTU2Z;
  98254. c.binTU2X = binTU2X;
  98255. c.binTU2Y = binTU2Y;
  98256. c.binTU2Z = binTU2Z;
  98257. tmp1X = norT1X * ii1[0] + norT1Y * ii1[1] + norT1Z * ii1[2];
  98258. tmp1Y = norT1X * ii1[3] + norT1Y * ii1[4] + norT1Z * ii1[5];
  98259. tmp1Z = norT1X * ii1[6] + norT1Y * ii1[7] + norT1Z * ii1[8];
  98260. tmp2X = tmp1Y * rp1Z - tmp1Z * rp1Y;
  98261. tmp2Y = tmp1Z * rp1X - tmp1X * rp1Z;
  98262. tmp2Z = tmp1X * rp1Y - tmp1Y * rp1X;
  98263. tmp1X = norT2X * ii2[0] + norT2Y * ii2[1] + norT2Z * ii2[2];
  98264. tmp1Y = norT2X * ii2[3] + norT2Y * ii2[4] + norT2Z * ii2[5];
  98265. tmp1Z = norT2X * ii2[6] + norT2Y * ii2[7] + norT2Z * ii2[8];
  98266. tmp2X += tmp1Y * rp2Z - tmp1Z * rp2Y;
  98267. tmp2Y += tmp1Z * rp2X - tmp1X * rp2Z;
  98268. tmp2Z += tmp1X * rp2Y - tmp1Y * rp2X;
  98269. var norDen = 1 / (m1m2 + norX * tmp2X + norY * tmp2Y + norZ * tmp2Z);
  98270. tmp1X = tanT1X * ii1[0] + tanT1Y * ii1[1] + tanT1Z * ii1[2];
  98271. tmp1Y = tanT1X * ii1[3] + tanT1Y * ii1[4] + tanT1Z * ii1[5];
  98272. tmp1Z = tanT1X * ii1[6] + tanT1Y * ii1[7] + tanT1Z * ii1[8];
  98273. tmp2X = tmp1Y * rp1Z - tmp1Z * rp1Y;
  98274. tmp2Y = tmp1Z * rp1X - tmp1X * rp1Z;
  98275. tmp2Z = tmp1X * rp1Y - tmp1Y * rp1X;
  98276. tmp1X = tanT2X * ii2[0] + tanT2Y * ii2[1] + tanT2Z * ii2[2];
  98277. tmp1Y = tanT2X * ii2[3] + tanT2Y * ii2[4] + tanT2Z * ii2[5];
  98278. tmp1Z = tanT2X * ii2[6] + tanT2Y * ii2[7] + tanT2Z * ii2[8];
  98279. tmp2X += tmp1Y * rp2Z - tmp1Z * rp2Y;
  98280. tmp2Y += tmp1Z * rp2X - tmp1X * rp2Z;
  98281. tmp2Z += tmp1X * rp2Y - tmp1Y * rp2X;
  98282. var tanDen = 1 / (m1m2 + tanX * tmp2X + tanY * tmp2Y + tanZ * tmp2Z);
  98283. tmp1X = binT1X * ii1[0] + binT1Y * ii1[1] + binT1Z * ii1[2];
  98284. tmp1Y = binT1X * ii1[3] + binT1Y * ii1[4] + binT1Z * ii1[5];
  98285. tmp1Z = binT1X * ii1[6] + binT1Y * ii1[7] + binT1Z * ii1[8];
  98286. tmp2X = tmp1Y * rp1Z - tmp1Z * rp1Y;
  98287. tmp2Y = tmp1Z * rp1X - tmp1X * rp1Z;
  98288. tmp2Z = tmp1X * rp1Y - tmp1Y * rp1X;
  98289. tmp1X = binT2X * ii2[0] + binT2Y * ii2[1] + binT2Z * ii2[2];
  98290. tmp1Y = binT2X * ii2[3] + binT2Y * ii2[4] + binT2Z * ii2[5];
  98291. tmp1Z = binT2X * ii2[6] + binT2Y * ii2[7] + binT2Z * ii2[8];
  98292. tmp2X += tmp1Y * rp2Z - tmp1Z * rp2Y;
  98293. tmp2Y += tmp1Z * rp2X - tmp1X * rp2Z;
  98294. tmp2Z += tmp1X * rp2Y - tmp1Y * rp2X;
  98295. var binDen = 1 / (m1m2 + binX * tmp2X + binY * tmp2Y + binZ * tmp2Z);
  98296. c.norDen = norDen;
  98297. c.tanDen = tanDen;
  98298. c.binDen = binDen;
  98299. if (p.warmStarted) {
  98300. var norImp = p.normalImpulse;
  98301. this.lv1.x += c.norU1X * norImp;
  98302. this.lv1.y += c.norU1Y * norImp;
  98303. this.lv1.z += c.norU1Z * norImp;
  98304. this.av1.x += norTU1X * norImp;
  98305. this.av1.y += norTU1Y * norImp;
  98306. this.av1.z += norTU1Z * norImp;
  98307. this.lv2.x -= c.norU2X * norImp;
  98308. this.lv2.y -= c.norU2Y * norImp;
  98309. this.lv2.z -= c.norU2Z * norImp;
  98310. this.av2.x -= norTU2X * norImp;
  98311. this.av2.y -= norTU2Y * norImp;
  98312. this.av2.z -= norTU2Z * norImp;
  98313. c.norImp = norImp;
  98314. c.tanImp = 0;
  98315. c.binImp = 0;
  98316. rvn = 0; // disable bouncing
  98317. } else {
  98318. c.norImp = 0;
  98319. c.tanImp = 0;
  98320. c.binImp = 0;
  98321. }
  98322. if (rvn > -1) {
  98323. rvn = 0; // disable bouncing
  98324. }
  98325. var norTar = this.restitution * -rvn;
  98326. var sepV = -(p.penetration + 0.005) * invTimeStep * 0.05; // allow 0.5cm error
  98327. if (norTar < sepV) norTar = sepV;
  98328. c.norTar = norTar;
  98329. c.last = i == this.num - 1;
  98330. c = c.next;
  98331. }
  98332. }
  98333. OIMO.ContactConstraint.prototype.solve = function () {
  98334. var lv1x = this.lv1.x;
  98335. var lv1y = this.lv1.y;
  98336. var lv1z = this.lv1.z;
  98337. var lv2x = this.lv2.x;
  98338. var lv2y = this.lv2.y;
  98339. var lv2z = this.lv2.z;
  98340. var av1x = this.av1.x;
  98341. var av1y = this.av1.y;
  98342. var av1z = this.av1.z;
  98343. var av2x = this.av2.x;
  98344. var av2y = this.av2.y;
  98345. var av2z = this.av2.z;
  98346. var c = this.cs;
  98347. while (true) {
  98348. var oldImp1;
  98349. var newImp1;
  98350. var oldImp2;
  98351. var newImp2;
  98352. var rvn;
  98353. var norImp = c.norImp;
  98354. var tanImp = c.tanImp;
  98355. var binImp = c.binImp;
  98356. var max = -norImp * this.friction;
  98357. var rvX = lv2x - lv1x;
  98358. var rvY = lv2y - lv1y;
  98359. var rvZ = lv2z - lv1z;
  98360. rvn =
  98361. rvX * c.tanX + rvY * c.tanY + rvZ * c.tanZ +
  98362. av2x * c.tanT2X + av2y * c.tanT2Y + av2z * c.tanT2Z -
  98363. av1x * c.tanT1X - av1y * c.tanT1Y - av1z * c.tanT1Z
  98364. ;
  98365. oldImp1 = tanImp;
  98366. newImp1 = rvn * c.tanDen;
  98367. tanImp += newImp1;
  98368. rvn =
  98369. rvX * c.binX + rvY * c.binY + rvZ * c.binZ +
  98370. av2x * c.binT2X + av2y * c.binT2Y + av2z * c.binT2Z -
  98371. av1x * c.binT1X - av1y * c.binT1Y - av1z * c.binT1Z
  98372. ;
  98373. oldImp2 = binImp;
  98374. newImp2 = rvn * c.binDen;
  98375. binImp += newImp2;
  98376. // cone friction clamp
  98377. var len = tanImp * tanImp + binImp * binImp;
  98378. if (len > max * max) {
  98379. len = max / OIMO.sqrt(len);
  98380. tanImp *= len;
  98381. binImp *= len;
  98382. }
  98383. newImp1 = tanImp - oldImp1;
  98384. newImp2 = binImp - oldImp2;
  98385. lv1x += c.tanU1X * newImp1 + c.binU1X * newImp2;
  98386. lv1y += c.tanU1Y * newImp1 + c.binU1Y * newImp2;
  98387. lv1z += c.tanU1Z * newImp1 + c.binU1Z * newImp2;
  98388. av1x += c.tanTU1X * newImp1 + c.binTU1X * newImp2;
  98389. av1y += c.tanTU1Y * newImp1 + c.binTU1Y * newImp2;
  98390. av1z += c.tanTU1Z * newImp1 + c.binTU1Z * newImp2;
  98391. lv2x -= c.tanU2X * newImp1 + c.binU2X * newImp2;
  98392. lv2y -= c.tanU2Y * newImp1 + c.binU2Y * newImp2;
  98393. lv2z -= c.tanU2Z * newImp1 + c.binU2Z * newImp2;
  98394. av2x -= c.tanTU2X * newImp1 + c.binTU2X * newImp2;
  98395. av2y -= c.tanTU2Y * newImp1 + c.binTU2Y * newImp2;
  98396. av2z -= c.tanTU2Z * newImp1 + c.binTU2Z * newImp2;
  98397. // restitution part
  98398. rvn =
  98399. (lv2x - lv1x) * c.norX + (lv2y - lv1y) * c.norY + (lv2z - lv1z) * c.norZ +
  98400. av2x * c.norT2X + av2y * c.norT2Y + av2z * c.norT2Z -
  98401. av1x * c.norT1X - av1y * c.norT1Y - av1z * c.norT1Z;
  98402. oldImp1 = norImp;
  98403. newImp1 = (rvn - c.norTar) * c.norDen;
  98404. norImp += newImp1;
  98405. if (norImp > 0) norImp = 0;
  98406. newImp1 = norImp - oldImp1;
  98407. lv1x += c.norU1X * newImp1;
  98408. lv1y += c.norU1Y * newImp1;
  98409. lv1z += c.norU1Z * newImp1;
  98410. av1x += c.norTU1X * newImp1;
  98411. av1y += c.norTU1Y * newImp1;
  98412. av1z += c.norTU1Z * newImp1;
  98413. lv2x -= c.norU2X * newImp1;
  98414. lv2y -= c.norU2Y * newImp1;
  98415. lv2z -= c.norU2Z * newImp1;
  98416. av2x -= c.norTU2X * newImp1;
  98417. av2y -= c.norTU2Y * newImp1;
  98418. av2z -= c.norTU2Z * newImp1;
  98419. c.norImp = norImp;
  98420. c.tanImp = tanImp;
  98421. c.binImp = binImp;
  98422. if (c.last) break;
  98423. c = c.next;
  98424. }
  98425. this.lv1.x = lv1x;
  98426. this.lv1.y = lv1y;
  98427. this.lv1.z = lv1z;
  98428. this.lv2.x = lv2x;
  98429. this.lv2.y = lv2y;
  98430. this.lv2.z = lv2z;
  98431. this.av1.x = av1x;
  98432. this.av1.y = av1y;
  98433. this.av1.z = av1z;
  98434. this.av2.x = av2x;
  98435. this.av2.y = av2y;
  98436. this.av2.z = av2z;
  98437. }
  98438. OIMO.ContactConstraint.prototype.postSolve = function () {
  98439. var c = this.cs;
  98440. var i = this.num;
  98441. while (i--) {
  98442. //for(var i=0;i<this.num;i++){
  98443. var p = this.ps[i];
  98444. p.normal.x = c.norX;
  98445. p.normal.y = c.norY;
  98446. p.normal.z = c.norZ;
  98447. p.tangent.x = c.tanX;
  98448. p.tangent.y = c.tanY;
  98449. p.tangent.z = c.tanZ;
  98450. p.binormal.x = c.binX;
  98451. p.binormal.y = c.binY;
  98452. p.binormal.z = c.binZ;
  98453. p.normalImpulse = c.norImp;
  98454. p.tangentImpulse = c.tanImp;
  98455. p.binormalImpulse = c.binImp;
  98456. p.normalDenominator = c.norDen;
  98457. p.tangentDenominator = c.tanDen;
  98458. p.binormalDenominator = c.binDen;
  98459. c = c.next;
  98460. }
  98461. }
  98462. /**
  98463. * A link list of contacts.
  98464. * @author saharan
  98465. */
  98466. OIMO.ContactLink = function (contact) {
  98467. // The previous contact link.
  98468. this.prev = null;
  98469. // The next contact link.
  98470. this.next = null;
  98471. // The shape of the contact.
  98472. this.shape = null;
  98473. // The other rigid body.
  98474. this.body = null;
  98475. // The contact of the link.
  98476. this.contact = contact;
  98477. }
  98478. /**
  98479. * A contact manifold between two shapes.
  98480. * @author saharan
  98481. */
  98482. OIMO.ContactManifold = function () {
  98483. // The first rigid body.
  98484. this.body1 = null;
  98485. // The second rigid body.
  98486. this.body2 = null;
  98487. // The number of manifold points.
  98488. this.numPoints = 0;
  98489. // The manifold points.
  98490. this.points = [];
  98491. this.points.length = 4;
  98492. this.points[0] = new OIMO.ManifoldPoint();
  98493. this.points[1] = new OIMO.ManifoldPoint();
  98494. this.points[2] = new OIMO.ManifoldPoint();
  98495. this.points[3] = new OIMO.ManifoldPoint();
  98496. }
  98497. OIMO.ContactManifold.prototype = {
  98498. constructor: OIMO.ContactManifold,
  98499. /**
  98500. * Reset the manifold.
  98501. * @param shape1
  98502. * @param shape2
  98503. */
  98504. reset: function (shape1, shape2) {
  98505. this.body1 = shape1.parent;
  98506. this.body2 = shape2.parent;
  98507. this.numPoints = 0;
  98508. },
  98509. /**
  98510. * Add a point into this manifold.
  98511. * @param x
  98512. * @param y
  98513. * @param z
  98514. * @param normalX
  98515. * @param normalY
  98516. * @param normalZ
  98517. * @param penetration
  98518. * @param flip
  98519. */
  98520. addPoint: function (x, y, z, normalX, normalY, normalZ, penetration, flip) {
  98521. var p = this.points[this.numPoints++];
  98522. p.position.x = x;
  98523. p.position.y = y;
  98524. p.position.z = z;
  98525. var r = this.body1.rotation;
  98526. var rx = x - this.body1.position.x;
  98527. var ry = y - this.body1.position.y;
  98528. var rz = z - this.body1.position.z;
  98529. var tr = r.elements;
  98530. p.localPoint1.x = rx * tr[0] + ry * tr[3] + rz * tr[6];
  98531. p.localPoint1.y = rx * tr[1] + ry * tr[4] + rz * tr[7];
  98532. p.localPoint1.z = rx * tr[2] + ry * tr[5] + rz * tr[8];
  98533. r = this.body2.rotation;
  98534. rx = x - this.body2.position.x;
  98535. ry = y - this.body2.position.y;
  98536. rz = z - this.body2.position.z;
  98537. p.localPoint2.x = rx * tr[0] + ry * tr[3] + rz * tr[6];
  98538. p.localPoint2.y = rx * tr[1] + ry * tr[4] + rz * tr[7];
  98539. p.localPoint2.z = rx * tr[2] + ry * tr[5] + rz * tr[8];
  98540. p.normalImpulse = 0;
  98541. if (flip) {
  98542. p.normal.x = -normalX;
  98543. p.normal.y = -normalY;
  98544. p.normal.z = -normalZ;
  98545. } else {
  98546. p.normal.x = normalX;
  98547. p.normal.y = normalY;
  98548. p.normal.z = normalZ;
  98549. }
  98550. p.penetration = penetration;
  98551. p.warmStarted = false;
  98552. }
  98553. }
  98554. OIMO.ContactPointDataBuffer = function () {
  98555. this.norX = NaN;
  98556. this.norY = NaN;
  98557. this.norZ = NaN;
  98558. this.tanX = NaN;
  98559. this.tanY = NaN;
  98560. this.tanZ = NaN;
  98561. this.binX = NaN;
  98562. this.binY = NaN;
  98563. this.binZ = NaN;
  98564. this.rp1X = NaN;
  98565. this.rp1Y = NaN;
  98566. this.rp1Z = NaN;
  98567. this.rp2X = NaN;
  98568. this.rp2Y = NaN;
  98569. this.rp2Z = NaN;
  98570. this.norU1X = NaN;
  98571. this.norU1Y = NaN;
  98572. this.norU1Z = NaN;
  98573. this.norU2X = NaN;
  98574. this.norU2Y = NaN;
  98575. this.norU2Z = NaN;
  98576. this.tanU1X = NaN;
  98577. this.tanU1Y = NaN;
  98578. this.tanU1Z = NaN;
  98579. this.tanU2X = NaN;
  98580. this.tanU2Y = NaN;
  98581. this.tanU2Z = NaN;
  98582. this.binU1X = NaN;
  98583. this.binU1Y = NaN;
  98584. this.binU1Z = NaN;
  98585. this.binU2X = NaN;
  98586. this.binU2Y = NaN;
  98587. this.binU2Z = NaN;
  98588. this.norT1X = NaN;
  98589. this.norT1Y = NaN;
  98590. this.norT1Z = NaN;
  98591. this.norT2X = NaN;
  98592. this.norT2Y = NaN;
  98593. this.norT2Z = NaN;
  98594. this.tanT1X = NaN;
  98595. this.tanT1Y = NaN;
  98596. this.tanT1Z = NaN;
  98597. this.tanT2X = NaN;
  98598. this.tanT2Y = NaN;
  98599. this.tanT2Z = NaN;
  98600. this.binT1X = NaN;
  98601. this.binT1Y = NaN;
  98602. this.binT1Z = NaN;
  98603. this.binT2X = NaN;
  98604. this.binT2Y = NaN;
  98605. this.binT2Z = NaN;
  98606. this.norTU1X = NaN;
  98607. this.norTU1Y = NaN;
  98608. this.norTU1Z = NaN;
  98609. this.norTU2X = NaN;
  98610. this.norTU2Y = NaN;
  98611. this.norTU2Z = NaN;
  98612. this.tanTU1X = NaN;
  98613. this.tanTU1Y = NaN;
  98614. this.tanTU1Z = NaN;
  98615. this.tanTU2X = NaN;
  98616. this.tanTU2Y = NaN;
  98617. this.tanTU2Z = NaN;
  98618. this.binTU1X = NaN;
  98619. this.binTU1Y = NaN;
  98620. this.binTU1Z = NaN;
  98621. this.binTU2X = NaN;
  98622. this.binTU2Y = NaN;
  98623. this.binTU2Z = NaN;
  98624. this.norImp = NaN;
  98625. this.tanImp = NaN;
  98626. this.binImp = NaN;
  98627. this.norDen = NaN;
  98628. this.tanDen = NaN;
  98629. this.binDen = NaN;
  98630. this.norTar = NaN;
  98631. this.next = null;
  98632. this.last = false;
  98633. }
  98634. OIMO.ImpulseDataBuffer = function () {
  98635. this.lp1X = NaN;
  98636. this.lp1Y = NaN;
  98637. this.lp1Z = NaN;
  98638. this.lp2X = NaN;
  98639. this.lp2Y = NaN;
  98640. this.lp2Z = NaN;
  98641. this.impulse = NaN;
  98642. }
  98643. /**
  98644. * The class holds details of the contact point.
  98645. * @author saharan
  98646. */
  98647. OIMO.ManifoldPoint = function () {
  98648. // Whether this manifold point is persisting or not.
  98649. this.warmStarted = false;
  98650. // The position of this manifold point.
  98651. this.position = new OIMO.Vec3();
  98652. // The position in the first shape's coordinate.
  98653. this.localPoint1 = new OIMO.Vec3();
  98654. // The position in the second shape's coordinate.
  98655. this.localPoint2 = new OIMO.Vec3();
  98656. // The normal vector of this manifold point.
  98657. this.normal = new OIMO.Vec3();
  98658. // The tangent vector of this manifold point.
  98659. this.tangent = new OIMO.Vec3();
  98660. // The binormal vector of this manifold point.
  98661. this.binormal = new OIMO.Vec3();
  98662. // The impulse in normal direction.
  98663. this.normalImpulse = 0;
  98664. // The impulse in tangent direction.
  98665. this.tangentImpulse = 0;
  98666. // The impulse in binormal direction.
  98667. this.binormalImpulse = 0;
  98668. // The denominator in normal direction.
  98669. this.normalDenominator = 0;
  98670. // The denominator in tangent direction.
  98671. this.tangentDenominator = 0;
  98672. // The denominator in binormal direction.
  98673. this.binormalDenominator = 0;
  98674. // The depth of penetration.
  98675. this.penetration = 0;
  98676. }
  98677. /**
  98678. * This class holds mass information of a shape.
  98679. * @author saharan
  98680. */
  98681. OIMO.MassInfo = function () {
  98682. // Mass of the shape.
  98683. this.mass = 0;
  98684. // The moment inertia of the shape.
  98685. this.inertia = new OIMO.Mat33();
  98686. };
  98687. /**
  98688. * A shape is used to detect collisions of rigid bodies.
  98689. * @author saharan
  98690. * @author lo-th
  98691. */
  98692. OIMO.Shape = function (config) {
  98693. this.type = OIMO.SHAPE_NULL;
  98694. // The global identification of the shape should be unique to the shape.
  98695. this.id = OIMO.nextID++;
  98696. // The previous shape in parent rigid body.
  98697. this.prev = null;
  98698. // The next shape in parent rigid body.
  98699. this.next = null;
  98700. // The proxy of the shape used for broad-phase collision detection.
  98701. this.proxy = null;
  98702. // The parent rigid body of the shape.
  98703. this.parent = null;
  98704. // The linked list of the contacts with the shape.
  98705. this.contactLink = null;
  98706. // The number of the contacts with the shape.
  98707. this.numContacts = 0;
  98708. // The center of gravity of the shape in world coordinate system.
  98709. this.position = new OIMO.Vec3();
  98710. // The rotation matrix of the shape in world coordinate system
  98711. this.rotation = new OIMO.Mat33();
  98712. // The position of the shape in parent's coordinate system.
  98713. this.relativePosition = new OIMO.Vec3().copy(config.relativePosition);
  98714. // The rotation matrix of the shape in parent's coordinate system.
  98715. this.relativeRotation = new OIMO.Mat33().copy(config.relativeRotation);
  98716. // The axis-aligned bounding box of the shape.
  98717. this.aabb = new OIMO.AABB();
  98718. // The density of the shape.
  98719. this.density = config.density;
  98720. // The coefficient of friction of the shape.
  98721. this.friction = config.friction;
  98722. // The coefficient of restitution of the shape.
  98723. this.restitution = config.restitution;
  98724. // The bits of the collision groups to which the shape belongs.
  98725. this.belongsTo = config.belongsTo;
  98726. // The bits of the collision groups with which the shape collides.
  98727. this.collidesWith = config.collidesWith;
  98728. };
  98729. OIMO.Shape.prototype = {
  98730. constructor: OIMO.Shape,
  98731. // Calculate the mass information of the shape.
  98732. calculateMassInfo: function (out) {
  98733. OIMO.Error("Shape", "Inheritance error.");
  98734. },
  98735. // Update the proxy of the shape.
  98736. updateProxy: function () {
  98737. OIMO.Error("Shape", "Inheritance error.");
  98738. }
  98739. };
  98740. /**
  98741. * A shape configuration holds common configuration data for constructing a shape.
  98742. * Shape configurations can be reused safely.
  98743. * @author saharan
  98744. */
  98745. OIMO.ShapeConfig = function () {
  98746. // The position of the shape in parent's coordinate system.
  98747. this.relativePosition = new OIMO.Vec3();
  98748. // The rotation matrix of the shape in parent's coordinate system.
  98749. this.relativeRotation = new OIMO.Mat33();
  98750. // The coefficient of friction of the shape.
  98751. this.friction = 0.4;
  98752. // The coefficient of restitution of the shape.
  98753. this.restitution = 0.2;
  98754. // The density of the shape.
  98755. this.density = 1;
  98756. // The bits of the collision groups to which the shape belongs.
  98757. this.belongsTo = 1;
  98758. // The bits of the collision groups with which the shape collides.
  98759. this.collidesWith = 0xffffffff;
  98760. };
  98761. /**
  98762. * A box shape.
  98763. * @author saharan
  98764. * @author lo-th
  98765. */
  98766. OIMO.BoxShape = function (config, Width, Height, Depth) {
  98767. OIMO.Shape.call(this, config);
  98768. this.type = OIMO.SHAPE_BOX;
  98769. // The width of the box.
  98770. this.width = Width;
  98771. // The height of the box.
  98772. this.height = Height;
  98773. // The depth of the box.
  98774. this.depth = Depth;
  98775. // The half-width of the box.
  98776. this.halfWidth = Width * 0.5;
  98777. // The half-height of the box.
  98778. this.halfHeight = Height * 0.5;
  98779. // The half-depth of the box.
  98780. this.halfDepth = Depth * 0.5;
  98781. this.dimentions = new OIMO_ARRAY_TYPE(18);
  98782. this.elements = new OIMO_ARRAY_TYPE(24);
  98783. };
  98784. OIMO.BoxShape.prototype = Object.create(OIMO.Shape.prototype);
  98785. OIMO.BoxShape.prototype.constructor = OIMO.BoxShape;
  98786. OIMO.BoxShape.prototype.calculateMassInfo = function (out) {
  98787. var mass = this.width * this.height * this.depth * this.density;
  98788. var divid = 1 / 12;
  98789. out.mass = mass;
  98790. out.inertia.set(
  98791. mass * (this.height * this.height + this.depth * this.depth) * divid, 0, 0,
  98792. 0, mass * (this.width * this.width + this.depth * this.depth) * divid, 0,
  98793. 0, 0, mass * (this.width * this.width + this.height * this.height) * divid
  98794. );
  98795. };
  98796. OIMO.BoxShape.prototype.updateProxy = function () {
  98797. var te = this.rotation.elements;
  98798. var di = this.dimentions;
  98799. // Width
  98800. di[0] = te[0];
  98801. di[1] = te[3];
  98802. di[2] = te[6];
  98803. // Height
  98804. di[3] = te[1];
  98805. di[4] = te[4];
  98806. di[5] = te[7];
  98807. // Depth
  98808. di[6] = te[2];
  98809. di[7] = te[5];
  98810. di[8] = te[8];
  98811. // halp Width
  98812. di[9] = te[0] * this.halfWidth;
  98813. di[10] = te[3] * this.halfWidth;
  98814. di[11] = te[6] * this.halfWidth;
  98815. // halp Height
  98816. di[12] = te[1] * this.halfHeight;
  98817. di[13] = te[4] * this.halfHeight;
  98818. di[14] = te[7] * this.halfHeight;
  98819. // halp Depth
  98820. di[15] = te[2] * this.halfDepth;
  98821. di[16] = te[5] * this.halfDepth;
  98822. di[17] = te[8] * this.halfDepth;
  98823. var wx = di[9];
  98824. var wy = di[10];
  98825. var wz = di[11];
  98826. var hx = di[12];
  98827. var hy = di[13];
  98828. var hz = di[14];
  98829. var dx = di[15];
  98830. var dy = di[16];
  98831. var dz = di[17];
  98832. var x = this.position.x;
  98833. var y = this.position.y;
  98834. var z = this.position.z;
  98835. var v = this.elements;
  98836. //v1
  98837. v[0] = x + wx + hx + dx;
  98838. v[1] = y + wy + hy + dy;
  98839. v[2] = z + wz + hz + dz;
  98840. //v2
  98841. v[3] = x + wx + hx - dx;
  98842. v[4] = y + wy + hy - dy;
  98843. v[5] = z + wz + hz - dz;
  98844. //v3
  98845. v[6] = x + wx - hx + dx;
  98846. v[7] = y + wy - hy + dy;
  98847. v[8] = z + wz - hz + dz;
  98848. //v4
  98849. v[9] = x + wx - hx - dx;
  98850. v[10] = y + wy - hy - dy;
  98851. v[11] = z + wz - hz - dz;
  98852. //v5
  98853. v[12] = x - wx + hx + dx;
  98854. v[13] = y - wy + hy + dy;
  98855. v[14] = z - wz + hz + dz;
  98856. //v6
  98857. v[15] = x - wx + hx - dx;
  98858. v[16] = y - wy + hy - dy;
  98859. v[17] = z - wz + hz - dz;
  98860. //v7
  98861. v[18] = x - wx - hx + dx;
  98862. v[19] = y - wy - hy + dy;
  98863. v[20] = z - wz - hz + dz;
  98864. //v8
  98865. v[21] = x - wx - hx - dx;
  98866. v[22] = y - wy - hy - dy;
  98867. v[23] = z - wz - hz - dz;
  98868. var w = di[9] < 0 ? -di[9] : di[9];
  98869. var h = di[10] < 0 ? -di[10] : di[10];
  98870. var d = di[11] < 0 ? -di[11] : di[11];
  98871. w = di[12] < 0 ? w - di[12] : w + di[12];
  98872. h = di[13] < 0 ? h - di[13] : h + di[13];
  98873. d = di[14] < 0 ? d - di[14] : d + di[14];
  98874. w = di[15] < 0 ? w - di[15] : w + di[15];
  98875. h = di[16] < 0 ? h - di[16] : h + di[16];
  98876. d = di[17] < 0 ? d - di[17] : d + di[17];
  98877. var p = OIMO.AABB_PROX;
  98878. this.aabb.set(
  98879. this.position.x - w - p, this.position.x + w + p,
  98880. this.position.y - h - p, this.position.y + h + p,
  98881. this.position.z - d - p, this.position.z + d + p
  98882. );
  98883. if (this.proxy != null) this.proxy.update();
  98884. };
  98885. /**
  98886. * A sphere shape.
  98887. * @author saharan
  98888. * @author lo-th
  98889. */
  98890. OIMO.SphereShape = function (config, radius) {
  98891. OIMO.Shape.call(this, config);
  98892. this.type = OIMO.SHAPE_SPHERE;
  98893. // The radius of the shape.
  98894. this.radius = radius;
  98895. };
  98896. OIMO.SphereShape.prototype = Object.create(OIMO.Shape.prototype);
  98897. OIMO.SphereShape.prototype.constructor = OIMO.SphereShape;
  98898. OIMO.SphereShape.prototype.calculateMassInfo = function (out) {
  98899. var mass = 1.333 * OIMO.PI * this.radius * this.radius * this.radius * this.density;
  98900. out.mass = mass;
  98901. var inertia = mass * this.radius * this.radius * 0.4;
  98902. out.inertia.set(inertia, 0, 0, 0, inertia, 0, 0, 0, inertia);
  98903. };
  98904. OIMO.SphereShape.prototype.updateProxy = function () {
  98905. var p = OIMO.AABB_PROX;
  98906. this.aabb.set(
  98907. this.position.x - this.radius - p, this.position.x + this.radius + p,
  98908. this.position.y - this.radius - p, this.position.y + this.radius + p,
  98909. this.position.z - this.radius - p, this.position.z + this.radius + p
  98910. );
  98911. if (this.proxy != null) this.proxy.update();
  98912. };
  98913. /**
  98914. * A cylinder shap.
  98915. * @author saharan
  98916. * @author lo-th
  98917. */
  98918. OIMO.CylinderShape = function (config, radius, height) {
  98919. OIMO.Shape.call(this, config);
  98920. this.type = OIMO.SHAPE_CYLINDER;
  98921. this.radius = radius;
  98922. this.height = height;
  98923. this.halfHeight = height * 0.5;
  98924. this.normalDirection = new OIMO.Vec3();
  98925. this.halfDirection = new OIMO.Vec3();
  98926. };
  98927. OIMO.CylinderShape.prototype = Object.create(OIMO.Shape.prototype);
  98928. OIMO.CylinderShape.prototype.constructor = OIMO.CylinderShape;
  98929. OIMO.CylinderShape.prototype.calculateMassInfo = function (out) {
  98930. var rsq = this.radius * this.radius;
  98931. var mass = OIMO.PI * rsq * this.height * this.density;
  98932. var inertiaXZ = ((0.25 * rsq) + (0.0833 * this.height * this.height)) * mass;
  98933. var inertiaY = 0.5 * rsq;
  98934. out.mass = mass;
  98935. out.inertia.set(inertiaXZ, 0, 0, 0, inertiaY, 0, 0, 0, inertiaXZ);
  98936. };
  98937. OIMO.CylinderShape.prototype.updateProxy = function () {
  98938. var te = this.rotation.elements;
  98939. var len, wx, hy, dz, xx, yy, zz, w, h, d, p;
  98940. xx = te[1] * te[1];
  98941. yy = te[4] * te[4];
  98942. zz = te[7] * te[7];
  98943. this.normalDirection.set(te[1], te[4], te[7]);
  98944. this.halfDirection.scale(this.normalDirection, this.halfHeight);
  98945. wx = 1 - xx;
  98946. len = OIMO.sqrt(wx * wx + xx * yy + xx * zz);
  98947. if (len > 0) len = this.radius / len;
  98948. wx *= len;
  98949. hy = 1 - yy;
  98950. len = OIMO.sqrt(yy * xx + hy * hy + yy * zz);
  98951. if (len > 0) len = this.radius / len;
  98952. hy *= len;
  98953. dz = 1 - zz;
  98954. len = OIMO.sqrt(zz * xx + zz * yy + dz * dz);
  98955. if (len > 0) len = this.radius / len;
  98956. dz *= len;
  98957. w = this.halfDirection.x < 0 ? -this.halfDirection.x : this.halfDirection.x;
  98958. h = this.halfDirection.y < 0 ? -this.halfDirection.y : this.halfDirection.y;
  98959. d = this.halfDirection.z < 0 ? -this.halfDirection.z : this.halfDirection.z;
  98960. w = wx < 0 ? w - wx : w + wx;
  98961. h = hy < 0 ? h - hy : h + hy;
  98962. d = dz < 0 ? d - dz : d + dz;
  98963. p = OIMO.AABB_PROX;
  98964. this.aabb.set(
  98965. this.position.x - w - p, this.position.x + w + p,
  98966. this.position.y - h - p, this.position.y + h + p,
  98967. this.position.z - d - p, this.position.z + d + p
  98968. );
  98969. if (this.proxy != null) this.proxy.update();
  98970. };
  98971. /**
  98972. * A tetra shape.
  98973. * @author xprogram
  98974. */
  98975. OIMO.TetraShape = function (config, p1, p2, p3, p4) {
  98976. OIMO.Shape.call(this, config);
  98977. this.type = OIMO.SHAPE_TETRA;
  98978. // Vertices and faces of tetra
  98979. this.verts = [p1, p2, p3, p4];
  98980. this.faces = [
  98981. mtri(0, 1, 2),
  98982. mtri(1, 2, 3),
  98983. mtri(2, 3, 4),
  98984. mtri(4, 0, 1),
  98985. ];
  98986. };
  98987. OIMO.TetraShape.prototype = Object.create(OIMO.Shape.prototype);
  98988. OIMO.TetraShape.prototype.constructor = OIMO.TetraShape;
  98989. OIMO.TetraShape.prototype.calculateMassInfo = function () {
  98990. // I guess you could calculate box mass and split it
  98991. // in half for the tetra...
  98992. };
  98993. OIMO.TetraShape.prototype.updateProxy = function () {
  98994. this.aabb.setFromPoints(this.verts);
  98995. if (this.proxy !== null)
  98996. this.proxy.update();
  98997. };
  98998. function mtri(a, b, c) {
  98999. return { a: a, b: b, c: c };
  99000. }
  99001. OIMO.CollisionDetector = function () {
  99002. this.flip = false;
  99003. };
  99004. OIMO.CollisionDetector.prototype = {
  99005. constructor: OIMO.CollisionDetector,
  99006. detectCollision: function (shape1, shape2, manifold) {
  99007. OIMO.Error("CollisionDetector", "Inheritance error.");
  99008. }
  99009. };
  99010. /**
  99011. * A collision detector which detects collisions between two boxes.
  99012. * @author saharan
  99013. */
  99014. OIMO.BoxBoxCollisionDetector = function () {
  99015. OIMO.CollisionDetector.call(this);
  99016. this.clipVertices1 = new OIMO_ARRAY_TYPE(24); // 8 vertices x,y,z
  99017. this.clipVertices2 = new OIMO_ARRAY_TYPE(24);
  99018. this.used = new OIMO_ARRAY_TYPE(8);
  99019. this.INF = 1 / 0;
  99020. };
  99021. OIMO.BoxBoxCollisionDetector.prototype = Object.create(OIMO.CollisionDetector.prototype);
  99022. OIMO.BoxBoxCollisionDetector.prototype.constructor = OIMO.BoxBoxCollisionDetector;
  99023. OIMO.BoxBoxCollisionDetector.prototype.detectCollision = function (shape1, shape2, manifold) {
  99024. // What you are doing
  99025. // · I to prepare a separate axis of the fifteen
  99026. //-Six in each of three normal vectors of the xyz direction of the box both
  99027. // · Remaining nine 3x3 a vector perpendicular to the side of the box 2 and the side of the box 1
  99028. // · Calculate the depth to the separation axis
  99029. // Calculates the distance using the inner product and put the amount of embedment
  99030. // · However a vertical separation axis and side to weight a little to avoid vibration
  99031. // And end when there is a separate axis that is remote even one
  99032. // · I look for separation axis with little to dent most
  99033. // Men and if separation axis of the first six - end collision
  99034. // Heng If it separate axis of nine other - side collision
  99035. // Heng - case of a side collision
  99036. // · Find points of two sides on which you made ​​the separation axis
  99037. // Calculates the point of closest approach of a straight line consisting of separate axis points obtained, and the collision point
  99038. //-Surface - the case of the plane crash
  99039. //-Box A, box B and the other a box of better made ​​a separate axis
  99040. // • The surface A and the plane that made the separation axis of the box A, and B to the surface the face of the box B close in the opposite direction to the most isolated axis
  99041. // When viewed from the front surface A, and the cut part exceeding the area of the surface A is a surface B
  99042. //-Plane B becomes the 3-8 triangle, I a candidate for the collision point the vertex of surface B
  99043. // • If more than one candidate 5 exists, scraping up to four
  99044. // For potential collision points of all, to examine the distance between the surface A
  99045. // • If you were on the inside surface of A, and the collision point
  99046. var b1;
  99047. var b2;
  99048. if (shape1.id < shape2.id) {
  99049. b1 = (shape1);
  99050. b2 = (shape2);
  99051. } else {
  99052. b1 = (shape2);
  99053. b2 = (shape1);
  99054. }
  99055. var V1 = b1.elements;
  99056. var V2 = b2.elements;
  99057. var D1 = b1.dimentions;
  99058. var D2 = b2.dimentions;
  99059. var p1 = b1.position;
  99060. var p2 = b2.position;
  99061. var p1x = p1.x;
  99062. var p1y = p1.y;
  99063. var p1z = p1.z;
  99064. var p2x = p2.x;
  99065. var p2y = p2.y;
  99066. var p2z = p2.z;
  99067. // diff
  99068. var dx = p2x - p1x;
  99069. var dy = p2y - p1y;
  99070. var dz = p2z - p1z;
  99071. // distance
  99072. var w1 = b1.halfWidth;
  99073. var h1 = b1.halfHeight;
  99074. var d1 = b1.halfDepth;
  99075. var w2 = b2.halfWidth;
  99076. var h2 = b2.halfHeight;
  99077. var d2 = b2.halfDepth;
  99078. // direction
  99079. // ----------------------------
  99080. // 15 separating axes
  99081. // 1~6: face
  99082. // 7~f: edge
  99083. // http://marupeke296.com/COL_3D_No13_OBBvsOBB.html
  99084. // ----------------------------
  99085. var a1x = D1[0];
  99086. var a1y = D1[1];
  99087. var a1z = D1[2];
  99088. var a2x = D1[3];
  99089. var a2y = D1[4];
  99090. var a2z = D1[5];
  99091. var a3x = D1[6];
  99092. var a3y = D1[7];
  99093. var a3z = D1[8];
  99094. var d1x = D1[9];
  99095. var d1y = D1[10];
  99096. var d1z = D1[11];
  99097. var d2x = D1[12];
  99098. var d2y = D1[13];
  99099. var d2z = D1[14];
  99100. var d3x = D1[15];
  99101. var d3y = D1[16];
  99102. var d3z = D1[17];
  99103. var a4x = D2[0];
  99104. var a4y = D2[1];
  99105. var a4z = D2[2];
  99106. var a5x = D2[3];
  99107. var a5y = D2[4];
  99108. var a5z = D2[5];
  99109. var a6x = D2[6];
  99110. var a6y = D2[7];
  99111. var a6z = D2[8];
  99112. var d4x = D2[9];
  99113. var d4y = D2[10];
  99114. var d4z = D2[11];
  99115. var d5x = D2[12];
  99116. var d5y = D2[13];
  99117. var d5z = D2[14];
  99118. var d6x = D2[15];
  99119. var d6y = D2[16];
  99120. var d6z = D2[17];
  99121. var a7x = a1y * a4z - a1z * a4y;
  99122. var a7y = a1z * a4x - a1x * a4z;
  99123. var a7z = a1x * a4y - a1y * a4x;
  99124. var a8x = a1y * a5z - a1z * a5y;
  99125. var a8y = a1z * a5x - a1x * a5z;
  99126. var a8z = a1x * a5y - a1y * a5x;
  99127. var a9x = a1y * a6z - a1z * a6y;
  99128. var a9y = a1z * a6x - a1x * a6z;
  99129. var a9z = a1x * a6y - a1y * a6x;
  99130. var aax = a2y * a4z - a2z * a4y;
  99131. var aay = a2z * a4x - a2x * a4z;
  99132. var aaz = a2x * a4y - a2y * a4x;
  99133. var abx = a2y * a5z - a2z * a5y;
  99134. var aby = a2z * a5x - a2x * a5z;
  99135. var abz = a2x * a5y - a2y * a5x;
  99136. var acx = a2y * a6z - a2z * a6y;
  99137. var acy = a2z * a6x - a2x * a6z;
  99138. var acz = a2x * a6y - a2y * a6x;
  99139. var adx = a3y * a4z - a3z * a4y;
  99140. var ady = a3z * a4x - a3x * a4z;
  99141. var adz = a3x * a4y - a3y * a4x;
  99142. var aex = a3y * a5z - a3z * a5y;
  99143. var aey = a3z * a5x - a3x * a5z;
  99144. var aez = a3x * a5y - a3y * a5x;
  99145. var afx = a3y * a6z - a3z * a6y;
  99146. var afy = a3z * a6x - a3x * a6z;
  99147. var afz = a3x * a6y - a3y * a6x;
  99148. // right or left flags
  99149. var right1;
  99150. var right2;
  99151. var right3;
  99152. var right4;
  99153. var right5;
  99154. var right6;
  99155. var right7;
  99156. var right8;
  99157. var right9;
  99158. var righta;
  99159. var rightb;
  99160. var rightc;
  99161. var rightd;
  99162. var righte;
  99163. var rightf;
  99164. // overlapping distances
  99165. var overlap1;
  99166. var overlap2;
  99167. var overlap3;
  99168. var overlap4;
  99169. var overlap5;
  99170. var overlap6;
  99171. var overlap7;
  99172. var overlap8;
  99173. var overlap9;
  99174. var overlapa;
  99175. var overlapb;
  99176. var overlapc;
  99177. var overlapd;
  99178. var overlape;
  99179. var overlapf;
  99180. // invalid flags
  99181. var invalid7 = false;
  99182. var invalid8 = false;
  99183. var invalid9 = false;
  99184. var invalida = false;
  99185. var invalidb = false;
  99186. var invalidc = false;
  99187. var invalidd = false;
  99188. var invalide = false;
  99189. var invalidf = false;
  99190. // temporary variables
  99191. var len;
  99192. var len1;
  99193. var len2;
  99194. var dot1;
  99195. var dot2;
  99196. var dot3;
  99197. // try axis 1
  99198. len = a1x * dx + a1y * dy + a1z * dz;
  99199. right1 = len > 0;
  99200. if (!right1) len = -len;
  99201. len1 = w1;
  99202. dot1 = a1x * a4x + a1y * a4y + a1z * a4z;
  99203. dot2 = a1x * a5x + a1y * a5y + a1z * a5z;
  99204. dot3 = a1x * a6x + a1y * a6y + a1z * a6z;
  99205. if (dot1 < 0) dot1 = -dot1;
  99206. if (dot2 < 0) dot2 = -dot2;
  99207. if (dot3 < 0) dot3 = -dot3;
  99208. len2 = dot1 * w2 + dot2 * h2 + dot3 * d2;
  99209. overlap1 = len - len1 - len2;
  99210. if (overlap1 > 0) return;
  99211. // try axis 2
  99212. len = a2x * dx + a2y * dy + a2z * dz;
  99213. right2 = len > 0;
  99214. if (!right2) len = -len;
  99215. len1 = h1;
  99216. dot1 = a2x * a4x + a2y * a4y + a2z * a4z;
  99217. dot2 = a2x * a5x + a2y * a5y + a2z * a5z;
  99218. dot3 = a2x * a6x + a2y * a6y + a2z * a6z;
  99219. if (dot1 < 0) dot1 = -dot1;
  99220. if (dot2 < 0) dot2 = -dot2;
  99221. if (dot3 < 0) dot3 = -dot3;
  99222. len2 = dot1 * w2 + dot2 * h2 + dot3 * d2;
  99223. overlap2 = len - len1 - len2;
  99224. if (overlap2 > 0) return;
  99225. // try axis 3
  99226. len = a3x * dx + a3y * dy + a3z * dz;
  99227. right3 = len > 0;
  99228. if (!right3) len = -len;
  99229. len1 = d1;
  99230. dot1 = a3x * a4x + a3y * a4y + a3z * a4z;
  99231. dot2 = a3x * a5x + a3y * a5y + a3z * a5z;
  99232. dot3 = a3x * a6x + a3y * a6y + a3z * a6z;
  99233. if (dot1 < 0) dot1 = -dot1;
  99234. if (dot2 < 0) dot2 = -dot2;
  99235. if (dot3 < 0) dot3 = -dot3;
  99236. len2 = dot1 * w2 + dot2 * h2 + dot3 * d2;
  99237. overlap3 = len - len1 - len2;
  99238. if (overlap3 > 0) return;
  99239. // try axis 4
  99240. len = a4x * dx + a4y * dy + a4z * dz;
  99241. right4 = len > 0;
  99242. if (!right4) len = -len;
  99243. dot1 = a4x * a1x + a4y * a1y + a4z * a1z;
  99244. dot2 = a4x * a2x + a4y * a2y + a4z * a2z;
  99245. dot3 = a4x * a3x + a4y * a3y + a4z * a3z;
  99246. if (dot1 < 0) dot1 = -dot1;
  99247. if (dot2 < 0) dot2 = -dot2;
  99248. if (dot3 < 0) dot3 = -dot3;
  99249. len1 = dot1 * w1 + dot2 * h1 + dot3 * d1;
  99250. len2 = w2;
  99251. overlap4 = (len - len1 - len2) * 1.0;
  99252. if (overlap4 > 0) return;
  99253. // try axis 5
  99254. len = a5x * dx + a5y * dy + a5z * dz;
  99255. right5 = len > 0;
  99256. if (!right5) len = -len;
  99257. dot1 = a5x * a1x + a5y * a1y + a5z * a1z;
  99258. dot2 = a5x * a2x + a5y * a2y + a5z * a2z;
  99259. dot3 = a5x * a3x + a5y * a3y + a5z * a3z;
  99260. if (dot1 < 0) dot1 = -dot1;
  99261. if (dot2 < 0) dot2 = -dot2;
  99262. if (dot3 < 0) dot3 = -dot3;
  99263. len1 = dot1 * w1 + dot2 * h1 + dot3 * d1;
  99264. len2 = h2;
  99265. overlap5 = (len - len1 - len2) * 1.0;
  99266. if (overlap5 > 0) return;
  99267. // try axis 6
  99268. len = a6x * dx + a6y * dy + a6z * dz;
  99269. right6 = len > 0;
  99270. if (!right6) len = -len;
  99271. dot1 = a6x * a1x + a6y * a1y + a6z * a1z;
  99272. dot2 = a6x * a2x + a6y * a2y + a6z * a2z;
  99273. dot3 = a6x * a3x + a6y * a3y + a6z * a3z;
  99274. if (dot1 < 0) dot1 = -dot1;
  99275. if (dot2 < 0) dot2 = -dot2;
  99276. if (dot3 < 0) dot3 = -dot3;
  99277. len1 = dot1 * w1 + dot2 * h1 + dot3 * d1;
  99278. len2 = d2;
  99279. overlap6 = (len - len1 - len2) * 1.0;
  99280. if (overlap6 > 0) return;
  99281. // try axis 7
  99282. len = a7x * a7x + a7y * a7y + a7z * a7z;
  99283. if (len > 1e-5) {
  99284. len = 1 / OIMO.sqrt(len);
  99285. a7x *= len;
  99286. a7y *= len;
  99287. a7z *= len;
  99288. len = a7x * dx + a7y * dy + a7z * dz;
  99289. right7 = len > 0;
  99290. if (!right7) len = -len;
  99291. dot1 = a7x * a2x + a7y * a2y + a7z * a2z;
  99292. dot2 = a7x * a3x + a7y * a3y + a7z * a3z;
  99293. if (dot1 < 0) dot1 = -dot1;
  99294. if (dot2 < 0) dot2 = -dot2;
  99295. len1 = dot1 * h1 + dot2 * d1;
  99296. dot1 = a7x * a5x + a7y * a5y + a7z * a5z;
  99297. dot2 = a7x * a6x + a7y * a6y + a7z * a6z;
  99298. if (dot1 < 0) dot1 = -dot1;
  99299. if (dot2 < 0) dot2 = -dot2;
  99300. len2 = dot1 * h2 + dot2 * d2;
  99301. overlap7 = len - len1 - len2;
  99302. if (overlap7 > 0) return;
  99303. } else {
  99304. right7 = false;
  99305. overlap7 = 0;
  99306. invalid7 = true;
  99307. }
  99308. // try axis 8
  99309. len = a8x * a8x + a8y * a8y + a8z * a8z;
  99310. if (len > 1e-5) {
  99311. len = 1 / OIMO.sqrt(len);
  99312. a8x *= len;
  99313. a8y *= len;
  99314. a8z *= len;
  99315. len = a8x * dx + a8y * dy + a8z * dz;
  99316. right8 = len > 0;
  99317. if (!right8) len = -len;
  99318. dot1 = a8x * a2x + a8y * a2y + a8z * a2z;
  99319. dot2 = a8x * a3x + a8y * a3y + a8z * a3z;
  99320. if (dot1 < 0) dot1 = -dot1;
  99321. if (dot2 < 0) dot2 = -dot2;
  99322. len1 = dot1 * h1 + dot2 * d1;
  99323. dot1 = a8x * a4x + a8y * a4y + a8z * a4z;
  99324. dot2 = a8x * a6x + a8y * a6y + a8z * a6z;
  99325. if (dot1 < 0) dot1 = -dot1;
  99326. if (dot2 < 0) dot2 = -dot2;
  99327. len2 = dot1 * w2 + dot2 * d2;
  99328. overlap8 = len - len1 - len2;
  99329. if (overlap8 > 0) return;
  99330. } else {
  99331. right8 = false;
  99332. overlap8 = 0;
  99333. invalid8 = true;
  99334. }
  99335. // try axis 9
  99336. len = a9x * a9x + a9y * a9y + a9z * a9z;
  99337. if (len > 1e-5) {
  99338. len = 1 / OIMO.sqrt(len);
  99339. a9x *= len;
  99340. a9y *= len;
  99341. a9z *= len;
  99342. len = a9x * dx + a9y * dy + a9z * dz;
  99343. right9 = len > 0;
  99344. if (!right9) len = -len;
  99345. dot1 = a9x * a2x + a9y * a2y + a9z * a2z;
  99346. dot2 = a9x * a3x + a9y * a3y + a9z * a3z;
  99347. if (dot1 < 0) dot1 = -dot1;
  99348. if (dot2 < 0) dot2 = -dot2;
  99349. len1 = dot1 * h1 + dot2 * d1;
  99350. dot1 = a9x * a4x + a9y * a4y + a9z * a4z;
  99351. dot2 = a9x * a5x + a9y * a5y + a9z * a5z;
  99352. if (dot1 < 0) dot1 = -dot1;
  99353. if (dot2 < 0) dot2 = -dot2;
  99354. len2 = dot1 * w2 + dot2 * h2;
  99355. overlap9 = len - len1 - len2;
  99356. if (overlap9 > 0) return;
  99357. } else {
  99358. right9 = false;
  99359. overlap9 = 0;
  99360. invalid9 = true;
  99361. }
  99362. // try axis 10
  99363. len = aax * aax + aay * aay + aaz * aaz;
  99364. if (len > 1e-5) {
  99365. len = 1 / OIMO.sqrt(len);
  99366. aax *= len;
  99367. aay *= len;
  99368. aaz *= len;
  99369. len = aax * dx + aay * dy + aaz * dz;
  99370. righta = len > 0;
  99371. if (!righta) len = -len;
  99372. dot1 = aax * a1x + aay * a1y + aaz * a1z;
  99373. dot2 = aax * a3x + aay * a3y + aaz * a3z;
  99374. if (dot1 < 0) dot1 = -dot1;
  99375. if (dot2 < 0) dot2 = -dot2;
  99376. len1 = dot1 * w1 + dot2 * d1;
  99377. dot1 = aax * a5x + aay * a5y + aaz * a5z;
  99378. dot2 = aax * a6x + aay * a6y + aaz * a6z;
  99379. if (dot1 < 0) dot1 = -dot1;
  99380. if (dot2 < 0) dot2 = -dot2;
  99381. len2 = dot1 * h2 + dot2 * d2;
  99382. overlapa = len - len1 - len2;
  99383. if (overlapa > 0) return;
  99384. } else {
  99385. righta = false;
  99386. overlapa = 0;
  99387. invalida = true;
  99388. }
  99389. // try axis 11
  99390. len = abx * abx + aby * aby + abz * abz;
  99391. if (len > 1e-5) {
  99392. len = 1 / OIMO.sqrt(len);
  99393. abx *= len;
  99394. aby *= len;
  99395. abz *= len;
  99396. len = abx * dx + aby * dy + abz * dz;
  99397. rightb = len > 0;
  99398. if (!rightb) len = -len;
  99399. dot1 = abx * a1x + aby * a1y + abz * a1z;
  99400. dot2 = abx * a3x + aby * a3y + abz * a3z;
  99401. if (dot1 < 0) dot1 = -dot1;
  99402. if (dot2 < 0) dot2 = -dot2;
  99403. len1 = dot1 * w1 + dot2 * d1;
  99404. dot1 = abx * a4x + aby * a4y + abz * a4z;
  99405. dot2 = abx * a6x + aby * a6y + abz * a6z;
  99406. if (dot1 < 0) dot1 = -dot1;
  99407. if (dot2 < 0) dot2 = -dot2;
  99408. len2 = dot1 * w2 + dot2 * d2;
  99409. overlapb = len - len1 - len2;
  99410. if (overlapb > 0) return;
  99411. } else {
  99412. rightb = false;
  99413. overlapb = 0;
  99414. invalidb = true;
  99415. }
  99416. // try axis 12
  99417. len = acx * acx + acy * acy + acz * acz;
  99418. if (len > 1e-5) {
  99419. len = 1 / OIMO.sqrt(len);
  99420. acx *= len;
  99421. acy *= len;
  99422. acz *= len;
  99423. len = acx * dx + acy * dy + acz * dz;
  99424. rightc = len > 0;
  99425. if (!rightc) len = -len;
  99426. dot1 = acx * a1x + acy * a1y + acz * a1z;
  99427. dot2 = acx * a3x + acy * a3y + acz * a3z;
  99428. if (dot1 < 0) dot1 = -dot1;
  99429. if (dot2 < 0) dot2 = -dot2;
  99430. len1 = dot1 * w1 + dot2 * d1;
  99431. dot1 = acx * a4x + acy * a4y + acz * a4z;
  99432. dot2 = acx * a5x + acy * a5y + acz * a5z;
  99433. if (dot1 < 0) dot1 = -dot1;
  99434. if (dot2 < 0) dot2 = -dot2;
  99435. len2 = dot1 * w2 + dot2 * h2;
  99436. overlapc = len - len1 - len2;
  99437. if (overlapc > 0) return;
  99438. } else {
  99439. rightc = false;
  99440. overlapc = 0;
  99441. invalidc = true;
  99442. }
  99443. // try axis 13
  99444. len = adx * adx + ady * ady + adz * adz;
  99445. if (len > 1e-5) {
  99446. len = 1 / OIMO.sqrt(len);
  99447. adx *= len;
  99448. ady *= len;
  99449. adz *= len;
  99450. len = adx * dx + ady * dy + adz * dz;
  99451. rightd = len > 0;
  99452. if (!rightd) len = -len;
  99453. dot1 = adx * a1x + ady * a1y + adz * a1z;
  99454. dot2 = adx * a2x + ady * a2y + adz * a2z;
  99455. if (dot1 < 0) dot1 = -dot1;
  99456. if (dot2 < 0) dot2 = -dot2;
  99457. len1 = dot1 * w1 + dot2 * h1;
  99458. dot1 = adx * a5x + ady * a5y + adz * a5z;
  99459. dot2 = adx * a6x + ady * a6y + adz * a6z;
  99460. if (dot1 < 0) dot1 = -dot1;
  99461. if (dot2 < 0) dot2 = -dot2;
  99462. len2 = dot1 * h2 + dot2 * d2;
  99463. overlapd = len - len1 - len2;
  99464. if (overlapd > 0) return;
  99465. } else {
  99466. rightd = false;
  99467. overlapd = 0;
  99468. invalidd = true;
  99469. }
  99470. // try axis 14
  99471. len = aex * aex + aey * aey + aez * aez;
  99472. if (len > 1e-5) {
  99473. len = 1 / OIMO.sqrt(len);
  99474. aex *= len;
  99475. aey *= len;
  99476. aez *= len;
  99477. len = aex * dx + aey * dy + aez * dz;
  99478. righte = len > 0;
  99479. if (!righte) len = -len;
  99480. dot1 = aex * a1x + aey * a1y + aez * a1z;
  99481. dot2 = aex * a2x + aey * a2y + aez * a2z;
  99482. if (dot1 < 0) dot1 = -dot1;
  99483. if (dot2 < 0) dot2 = -dot2;
  99484. len1 = dot1 * w1 + dot2 * h1;
  99485. dot1 = aex * a4x + aey * a4y + aez * a4z;
  99486. dot2 = aex * a6x + aey * a6y + aez * a6z;
  99487. if (dot1 < 0) dot1 = -dot1;
  99488. if (dot2 < 0) dot2 = -dot2;
  99489. len2 = dot1 * w2 + dot2 * d2;
  99490. overlape = len - len1 - len2;
  99491. if (overlape > 0) return;
  99492. } else {
  99493. righte = false;
  99494. overlape = 0;
  99495. invalide = true;
  99496. }
  99497. // try axis 15
  99498. len = afx * afx + afy * afy + afz * afz;
  99499. if (len > 1e-5) {
  99500. len = 1 / OIMO.sqrt(len);
  99501. afx *= len;
  99502. afy *= len;
  99503. afz *= len;
  99504. len = afx * dx + afy * dy + afz * dz;
  99505. rightf = len > 0;
  99506. if (!rightf) len = -len;
  99507. dot1 = afx * a1x + afy * a1y + afz * a1z;
  99508. dot2 = afx * a2x + afy * a2y + afz * a2z;
  99509. if (dot1 < 0) dot1 = -dot1;
  99510. if (dot2 < 0) dot2 = -dot2;
  99511. len1 = dot1 * w1 + dot2 * h1;
  99512. dot1 = afx * a4x + afy * a4y + afz * a4z;
  99513. dot2 = afx * a5x + afy * a5y + afz * a5z;
  99514. if (dot1 < 0) dot1 = -dot1;
  99515. if (dot2 < 0) dot2 = -dot2;
  99516. len2 = dot1 * w2 + dot2 * h2;
  99517. overlapf = len - len1 - len2;
  99518. if (overlapf > 0) return;
  99519. } else {
  99520. rightf = false;
  99521. overlapf = 0;
  99522. invalidf = true;
  99523. }
  99524. // boxes are overlapping
  99525. var depth = overlap1;
  99526. var depth2 = overlap1;
  99527. var minIndex = 0;
  99528. var right = right1;
  99529. if (overlap2 > depth2) {
  99530. depth = overlap2;
  99531. depth2 = overlap2;
  99532. minIndex = 1;
  99533. right = right2;
  99534. }
  99535. if (overlap3 > depth2) {
  99536. depth = overlap3;
  99537. depth2 = overlap3;
  99538. minIndex = 2;
  99539. right = right3;
  99540. }
  99541. if (overlap4 > depth2) {
  99542. depth = overlap4;
  99543. depth2 = overlap4;
  99544. minIndex = 3;
  99545. right = right4;
  99546. }
  99547. if (overlap5 > depth2) {
  99548. depth = overlap5;
  99549. depth2 = overlap5;
  99550. minIndex = 4;
  99551. right = right5;
  99552. }
  99553. if (overlap6 > depth2) {
  99554. depth = overlap6;
  99555. depth2 = overlap6;
  99556. minIndex = 5;
  99557. right = right6;
  99558. }
  99559. if (overlap7 - 0.01 > depth2 && !invalid7) {
  99560. depth = overlap7;
  99561. depth2 = overlap7 - 0.01;
  99562. minIndex = 6;
  99563. right = right7;
  99564. }
  99565. if (overlap8 - 0.01 > depth2 && !invalid8) {
  99566. depth = overlap8;
  99567. depth2 = overlap8 - 0.01;
  99568. minIndex = 7;
  99569. right = right8;
  99570. }
  99571. if (overlap9 - 0.01 > depth2 && !invalid9) {
  99572. depth = overlap9;
  99573. depth2 = overlap9 - 0.01;
  99574. minIndex = 8;
  99575. right = right9;
  99576. }
  99577. if (overlapa - 0.01 > depth2 && !invalida) {
  99578. depth = overlapa;
  99579. depth2 = overlapa - 0.01;
  99580. minIndex = 9;
  99581. right = righta;
  99582. }
  99583. if (overlapb - 0.01 > depth2 && !invalidb) {
  99584. depth = overlapb;
  99585. depth2 = overlapb - 0.01;
  99586. minIndex = 10;
  99587. right = rightb;
  99588. }
  99589. if (overlapc - 0.01 > depth2 && !invalidc) {
  99590. depth = overlapc;
  99591. depth2 = overlapc - 0.01;
  99592. minIndex = 11;
  99593. right = rightc;
  99594. }
  99595. if (overlapd - 0.01 > depth2 && !invalidd) {
  99596. depth = overlapd;
  99597. depth2 = overlapd - 0.01;
  99598. minIndex = 12;
  99599. right = rightd;
  99600. }
  99601. if (overlape - 0.01 > depth2 && !invalide) {
  99602. depth = overlape;
  99603. depth2 = overlape - 0.01;
  99604. minIndex = 13;
  99605. right = righte;
  99606. }
  99607. if (overlapf - 0.01 > depth2 && !invalidf) {
  99608. depth = overlapf;
  99609. minIndex = 14;
  99610. right = rightf;
  99611. }
  99612. // normal
  99613. var nx = 0;
  99614. var ny = 0;
  99615. var nz = 0;
  99616. // edge line or face side normal
  99617. var n1x = 0;
  99618. var n1y = 0;
  99619. var n1z = 0;
  99620. var n2x = 0;
  99621. var n2y = 0;
  99622. var n2z = 0;
  99623. // center of current face
  99624. var cx = 0;
  99625. var cy = 0;
  99626. var cz = 0;
  99627. // face side
  99628. var s1x = 0;
  99629. var s1y = 0;
  99630. var s1z = 0;
  99631. var s2x = 0;
  99632. var s2y = 0;
  99633. var s2z = 0;
  99634. // swap b1 b2
  99635. var swap = false;
  99636. //_______________________________________
  99637. if (minIndex == 0) {// b1.x * b2
  99638. if (right) {
  99639. cx = p1x + d1x; cy = p1y + d1y; cz = p1z + d1z;
  99640. nx = a1x; ny = a1y; nz = a1z;
  99641. } else {
  99642. cx = p1x - d1x; cy = p1y - d1y; cz = p1z - d1z;
  99643. nx = -a1x; ny = -a1y; nz = -a1z;
  99644. }
  99645. s1x = d2x; s1y = d2y; s1z = d2z;
  99646. n1x = -a2x; n1y = -a2y; n1z = -a2z;
  99647. s2x = d3x; s2y = d3y; s2z = d3z;
  99648. n2x = -a3x; n2y = -a3y; n2z = -a3z;
  99649. }
  99650. else if (minIndex == 1) {// b1.y * b2
  99651. if (right) {
  99652. cx = p1x + d2x; cy = p1y + d2y; cz = p1z + d2z;
  99653. nx = a2x; ny = a2y; nz = a2z;
  99654. } else {
  99655. cx = p1x - d2x; cy = p1y - d2y; cz = p1z - d2z;
  99656. nx = -a2x; ny = -a2y; nz = -a2z;
  99657. }
  99658. s1x = d1x; s1y = d1y; s1z = d1z;
  99659. n1x = -a1x; n1y = -a1y; n1z = -a1z;
  99660. s2x = d3x; s2y = d3y; s2z = d3z;
  99661. n2x = -a3x; n2y = -a3y; n2z = -a3z;
  99662. }
  99663. else if (minIndex == 2) {// b1.z * b2
  99664. if (right) {
  99665. cx = p1x + d3x; cy = p1y + d3y; cz = p1z + d3z;
  99666. nx = a3x; ny = a3y; nz = a3z;
  99667. } else {
  99668. cx = p1x - d3x; cy = p1y - d3y; cz = p1z - d3z;
  99669. nx = -a3x; ny = -a3y; nz = -a3z;
  99670. }
  99671. s1x = d1x; s1y = d1y; s1z = d1z;
  99672. n1x = -a1x; n1y = -a1y; n1z = -a1z;
  99673. s2x = d2x; s2y = d2y; s2z = d2z;
  99674. n2x = -a2x; n2y = -a2y; n2z = -a2z;
  99675. }
  99676. else if (minIndex == 3) {// b2.x * b1
  99677. swap = true;
  99678. if (!right) {
  99679. cx = p2x + d4x; cy = p2y + d4y; cz = p2z + d4z;
  99680. nx = a4x; ny = a4y; nz = a4z;
  99681. } else {
  99682. cx = p2x - d4x; cy = p2y - d4y; cz = p2z - d4z;
  99683. nx = -a4x; ny = -a4y; nz = -a4z;
  99684. }
  99685. s1x = d5x; s1y = d5y; s1z = d5z;
  99686. n1x = -a5x; n1y = -a5y; n1z = -a5z;
  99687. s2x = d6x; s2y = d6y; s2z = d6z;
  99688. n2x = -a6x; n2y = -a6y; n2z = -a6z;
  99689. }
  99690. else if (minIndex == 4) {// b2.y * b1
  99691. swap = true;
  99692. if (!right) {
  99693. cx = p2x + d5x; cy = p2y + d5y; cz = p2z + d5z;
  99694. nx = a5x; ny = a5y; nz = a5z;
  99695. } else {
  99696. cx = p2x - d5x; cy = p2y - d5y; cz = p2z - d5z;
  99697. nx = -a5x; ny = -a5y; nz = -a5z;
  99698. }
  99699. s1x = d4x; s1y = d4y; s1z = d4z;
  99700. n1x = -a4x; n1y = -a4y; n1z = -a4z;
  99701. s2x = d6x; s2y = d6y; s2z = d6z;
  99702. n2x = -a6x; n2y = -a6y; n2z = -a6z;
  99703. }
  99704. else if (minIndex == 5) {// b2.z * b1
  99705. swap = true;
  99706. if (!right) {
  99707. cx = p2x + d6x; cy = p2y + d6y; cz = p2z + d6z;
  99708. nx = a6x; ny = a6y; nz = a6z;
  99709. } else {
  99710. cx = p2x - d6x; cy = p2y - d6y; cz = p2z - d6z;
  99711. nx = -a6x; ny = -a6y; nz = -a6z;
  99712. }
  99713. s1x = d4x; s1y = d4y; s1z = d4z;
  99714. n1x = -a4x; n1y = -a4y; n1z = -a4z;
  99715. s2x = d5x; s2y = d5y; s2z = d5z;
  99716. n2x = -a5x; n2y = -a5y; n2z = -a5z;
  99717. }
  99718. else if (minIndex == 6) {// b1.x * b2.x
  99719. nx = a7x; ny = a7y; nz = a7z;
  99720. n1x = a1x; n1y = a1y; n1z = a1z;
  99721. n2x = a4x; n2y = a4y; n2z = a4z;
  99722. }
  99723. else if (minIndex == 7) {// b1.x * b2.y
  99724. nx = a8x; ny = a8y; nz = a8z;
  99725. n1x = a1x; n1y = a1y; n1z = a1z;
  99726. n2x = a5x; n2y = a5y; n2z = a5z;
  99727. }
  99728. else if (minIndex == 8) {// b1.x * b2.z
  99729. nx = a9x; ny = a9y; nz = a9z;
  99730. n1x = a1x; n1y = a1y; n1z = a1z;
  99731. n2x = a6x; n2y = a6y; n2z = a6z;
  99732. }
  99733. else if (minIndex == 9) {// b1.y * b2.x
  99734. nx = aax; ny = aay; nz = aaz;
  99735. n1x = a2x; n1y = a2y; n1z = a2z;
  99736. n2x = a4x; n2y = a4y; n2z = a4z
  99737. }
  99738. else if (minIndex == 10) {// b1.y * b2.y
  99739. nx = abx; ny = aby; nz = abz;
  99740. n1x = a2x; n1y = a2y; n1z = a2z;
  99741. n2x = a5x; n2y = a5y; n2z = a5z;
  99742. }
  99743. else if (minIndex == 11) {// b1.y * b2.z
  99744. nx = acx; ny = acy; nz = acz;
  99745. n1x = a2x; n1y = a2y; n1z = a2z;
  99746. n2x = a6x; n2y = a6y; n2z = a6z;
  99747. }
  99748. else if (minIndex == 12) {// b1.z * b2.x
  99749. nx = adx; ny = ady; nz = adz;
  99750. n1x = a3x; n1y = a3y; n1z = a3z;
  99751. n2x = a4x; n2y = a4y; n2z = a4z;
  99752. }
  99753. else if (minIndex == 13) {// b1.z * b2.y
  99754. nx = aex; ny = aey; nz = aez;
  99755. n1x = a3x; n1y = a3y; n1z = a3z;
  99756. n2x = a5x; n2y = a5y; n2z = a5z;
  99757. }
  99758. else if (minIndex == 14) {// b1.z * b2.z
  99759. nx = afx; ny = afy; nz = afz;
  99760. n1x = a3x; n1y = a3y; n1z = a3z;
  99761. n2x = a6x; n2y = a6y; n2z = a6z;
  99762. }
  99763. //__________________________________________
  99764. var v;
  99765. if (minIndex > 5) {
  99766. if (!right) {
  99767. nx = -nx; ny = -ny; nz = -nz;
  99768. }
  99769. var distance;
  99770. var maxDistance;
  99771. var vx;
  99772. var vy;
  99773. var vz;
  99774. var v1x;
  99775. var v1y;
  99776. var v1z;
  99777. var v2x;
  99778. var v2y;
  99779. var v2z;
  99780. //vertex1;
  99781. v1x = V1[0]; v1y = V1[1]; v1z = V1[2];
  99782. maxDistance = nx * v1x + ny * v1y + nz * v1z;
  99783. //vertex2;
  99784. vx = V1[3]; vy = V1[4]; vz = V1[5];
  99785. distance = nx * vx + ny * vy + nz * vz;
  99786. if (distance > maxDistance) {
  99787. maxDistance = distance;
  99788. v1x = vx; v1y = vy; v1z = vz;
  99789. }
  99790. //vertex3;
  99791. vx = V1[6]; vy = V1[7]; vz = V1[8];
  99792. distance = nx * vx + ny * vy + nz * vz;
  99793. if (distance > maxDistance) {
  99794. maxDistance = distance;
  99795. v1x = vx; v1y = vy; v1z = vz;
  99796. }
  99797. //vertex4;
  99798. vx = V1[9]; vy = V1[10]; vz = V1[11];
  99799. distance = nx * vx + ny * vy + nz * vz;
  99800. if (distance > maxDistance) {
  99801. maxDistance = distance;
  99802. v1x = vx; v1y = vy; v1z = vz;
  99803. }
  99804. //vertex5;
  99805. vx = V1[12]; vy = V1[13]; vz = V1[14];
  99806. distance = nx * vx + ny * vy + nz * vz;
  99807. if (distance > maxDistance) {
  99808. maxDistance = distance;
  99809. v1x = vx; v1y = vy; v1z = vz;
  99810. }
  99811. //vertex6;
  99812. vx = V1[15]; vy = V1[16]; vz = V1[17];
  99813. distance = nx * vx + ny * vy + nz * vz;
  99814. if (distance > maxDistance) {
  99815. maxDistance = distance;
  99816. v1x = vx; v1y = vy; v1z = vz;
  99817. }
  99818. //vertex7;
  99819. vx = V1[18]; vy = V1[19]; vz = V1[20];
  99820. distance = nx * vx + ny * vy + nz * vz;
  99821. if (distance > maxDistance) {
  99822. maxDistance = distance;
  99823. v1x = vx; v1y = vy; v1z = vz;
  99824. }
  99825. //vertex8;
  99826. vx = V1[21]; vy = V1[22]; vz = V1[23];
  99827. distance = nx * vx + ny * vy + nz * vz;
  99828. if (distance > maxDistance) {
  99829. maxDistance = distance;
  99830. v1x = vx; v1y = vy; v1z = vz;
  99831. }
  99832. //vertex1;
  99833. v2x = V2[0]; v2y = V2[1]; v2z = V2[2];
  99834. maxDistance = nx * v2x + ny * v2y + nz * v2z;
  99835. //vertex2;
  99836. vx = V2[3]; vy = V2[4]; vz = V2[5];
  99837. distance = nx * vx + ny * vy + nz * vz;
  99838. if (distance < maxDistance) {
  99839. maxDistance = distance;
  99840. v2x = vx; v2y = vy; v2z = vz;
  99841. }
  99842. //vertex3;
  99843. vx = V2[6]; vy = V2[7]; vz = V2[8];
  99844. distance = nx * vx + ny * vy + nz * vz;
  99845. if (distance < maxDistance) {
  99846. maxDistance = distance;
  99847. v2x = vx; v2y = vy; v2z = vz;
  99848. }
  99849. //vertex4;
  99850. vx = V2[9]; vy = V2[10]; vz = V2[11];
  99851. distance = nx * vx + ny * vy + nz * vz;
  99852. if (distance < maxDistance) {
  99853. maxDistance = distance;
  99854. v2x = vx; v2y = vy; v2z = vz;
  99855. }
  99856. //vertex5;
  99857. vx = V2[12]; vy = V2[13]; vz = V2[14];
  99858. distance = nx * vx + ny * vy + nz * vz;
  99859. if (distance < maxDistance) {
  99860. maxDistance = distance;
  99861. v2x = vx; v2y = vy; v2z = vz;
  99862. }
  99863. //vertex6;
  99864. vx = V2[15]; vy = V2[16]; vz = V2[17];
  99865. distance = nx * vx + ny * vy + nz * vz;
  99866. if (distance < maxDistance) {
  99867. maxDistance = distance;
  99868. v2x = vx; v2y = vy; v2z = vz;
  99869. }
  99870. //vertex7;
  99871. vx = V2[18]; vy = V2[19]; vz = V2[20];
  99872. distance = nx * vx + ny * vy + nz * vz;
  99873. if (distance < maxDistance) {
  99874. maxDistance = distance;
  99875. v2x = vx; v2y = vy; v2z = vz;
  99876. }
  99877. //vertex8;
  99878. vx = V2[21]; vy = V2[22]; vz = V2[23];
  99879. distance = nx * vx + ny * vy + nz * vz;
  99880. if (distance < maxDistance) {
  99881. maxDistance = distance;
  99882. v2x = vx; v2y = vy; v2z = vz;
  99883. }
  99884. vx = v2x - v1x; vy = v2y - v1y; vz = v2z - v1z;
  99885. dot1 = n1x * n2x + n1y * n2y + n1z * n2z;
  99886. var t = (vx * (n1x - n2x * dot1) + vy * (n1y - n2y * dot1) + vz * (n1z - n2z * dot1)) / (1 - dot1 * dot1);
  99887. manifold.addPoint(v1x + n1x * t + nx * depth * 0.5, v1y + n1y * t + ny * depth * 0.5, v1z + n1z * t + nz * depth * 0.5, nx, ny, nz, depth, false);
  99888. return;
  99889. }
  99890. // now detect face-face collision...
  99891. // target quad
  99892. var q1x;
  99893. var q1y;
  99894. var q1z;
  99895. var q2x;
  99896. var q2y;
  99897. var q2z;
  99898. var q3x;
  99899. var q3y;
  99900. var q3z;
  99901. var q4x;
  99902. var q4y;
  99903. var q4z;
  99904. // search support face and vertex
  99905. var minDot = 1;
  99906. var dot = 0;
  99907. var minDotIndex = 0;
  99908. if (swap) {
  99909. dot = a1x * nx + a1y * ny + a1z * nz;
  99910. if (dot < minDot) {
  99911. minDot = dot;
  99912. minDotIndex = 0;
  99913. }
  99914. if (-dot < minDot) {
  99915. minDot = -dot;
  99916. minDotIndex = 1;
  99917. }
  99918. dot = a2x * nx + a2y * ny + a2z * nz;
  99919. if (dot < minDot) {
  99920. minDot = dot;
  99921. minDotIndex = 2;
  99922. }
  99923. if (-dot < minDot) {
  99924. minDot = -dot;
  99925. minDotIndex = 3;
  99926. }
  99927. dot = a3x * nx + a3y * ny + a3z * nz;
  99928. if (dot < minDot) {
  99929. minDot = dot;
  99930. minDotIndex = 4;
  99931. }
  99932. if (-dot < minDot) {
  99933. minDot = -dot;
  99934. minDotIndex = 5;
  99935. }
  99936. if (minDotIndex == 0) {// x+ face
  99937. q1x = V1[0]; q1y = V1[1]; q1z = V1[2];//vertex1
  99938. q2x = V1[6]; q2y = V1[7]; q2z = V1[8];//vertex3
  99939. q3x = V1[9]; q3y = V1[10]; q3z = V1[11];//vertex4
  99940. q4x = V1[3]; q4y = V1[4]; q4z = V1[5];//vertex2
  99941. }
  99942. else if (minDotIndex == 1) {// x- face
  99943. q1x = V1[15]; q1y = V1[16]; q1z = V1[17];//vertex6
  99944. q2x = V1[21]; q2y = V1[22]; q2z = V1[23];//vertex8
  99945. q3x = V1[18]; q3y = V1[19]; q3z = V1[20];//vertex7
  99946. q4x = V1[12]; q4y = V1[13]; q4z = V1[14];//vertex5
  99947. }
  99948. else if (minDotIndex == 2) {// y+ face
  99949. q1x = V1[12]; q1y = V1[13]; q1z = V1[14];//vertex5
  99950. q2x = V1[0]; q2y = V1[1]; q2z = V1[2];//vertex1
  99951. q3x = V1[3]; q3y = V1[4]; q3z = V1[5];//vertex2
  99952. q4x = V1[15]; q4y = V1[16]; q4z = V1[17];//vertex6
  99953. }
  99954. else if (minDotIndex == 3) {// y- face
  99955. q1x = V1[21]; q1y = V1[22]; q1z = V1[23];//vertex8
  99956. q2x = V1[9]; q2y = V1[10]; q2z = V1[11];//vertex4
  99957. q3x = V1[6]; q3y = V1[7]; q3z = V1[8];//vertex3
  99958. q4x = V1[18]; q4y = V1[19]; q4z = V1[20];//vertex7
  99959. }
  99960. else if (minDotIndex == 4) {// z+ face
  99961. q1x = V1[12]; q1y = V1[13]; q1z = V1[14];//vertex5
  99962. q2x = V1[18]; q2y = V1[19]; q2z = V1[20];//vertex7
  99963. q3x = V1[6]; q3y = V1[7]; q3z = V1[8];//vertex3
  99964. q4x = V1[0]; q4y = V1[1]; q4z = V1[2];//vertex1
  99965. }
  99966. else if (minDotIndex == 5) {// z- face
  99967. q1x = V1[3]; q1y = V1[4]; q1z = V1[5];//vertex2
  99968. q2x = V1[6]; q2y = V1[7]; q2z = V1[8];//vertex4
  99969. q3x = V1[21]; q3y = V1[22]; q3z = V1[23];//vertex8
  99970. q4x = V1[15]; q4y = V1[16]; q4z = V1[17];//vertex6
  99971. }
  99972. } else {
  99973. dot = a4x * nx + a4y * ny + a4z * nz;
  99974. if (dot < minDot) {
  99975. minDot = dot;
  99976. minDotIndex = 0;
  99977. }
  99978. if (-dot < minDot) {
  99979. minDot = -dot;
  99980. minDotIndex = 1;
  99981. }
  99982. dot = a5x * nx + a5y * ny + a5z * nz;
  99983. if (dot < minDot) {
  99984. minDot = dot;
  99985. minDotIndex = 2;
  99986. }
  99987. if (-dot < minDot) {
  99988. minDot = -dot;
  99989. minDotIndex = 3;
  99990. }
  99991. dot = a6x * nx + a6y * ny + a6z * nz;
  99992. if (dot < minDot) {
  99993. minDot = dot;
  99994. minDotIndex = 4;
  99995. }
  99996. if (-dot < minDot) {
  99997. minDot = -dot;
  99998. minDotIndex = 5;
  99999. }
  100000. //______________________________________________________
  100001. if (minDotIndex == 0) {// x+ face
  100002. q1x = V2[0]; q1y = V2[1]; q1z = V2[2];//vertex1
  100003. q2x = V2[6]; q2y = V2[7]; q2z = V2[8];//vertex3
  100004. q3x = V2[9]; q3y = V2[10]; q3z = V2[11];//vertex4
  100005. q4x = V2[3]; q4y = V2[4]; q4z = V2[5];//vertex2
  100006. }
  100007. else if (minDotIndex == 1) {// x- face
  100008. q1x = V2[15]; q1y = V2[16]; q1z = V2[17];//vertex6
  100009. q2x = V2[21]; q2y = V2[22]; q2z = V2[23]; //vertex8
  100010. q3x = V2[18]; q3y = V2[19]; q3z = V2[20];//vertex7
  100011. q4x = V2[12]; q4y = V2[13]; q4z = V2[14];//vertex5
  100012. }
  100013. else if (minDotIndex == 2) {// y+ face
  100014. q1x = V2[12]; q1y = V2[13]; q1z = V2[14];//vertex5
  100015. q2x = V2[0]; q2y = V2[1]; q2z = V2[2];//vertex1
  100016. q3x = V2[3]; q3y = V2[4]; q3z = V2[5];//vertex2
  100017. q4x = V2[15]; q4y = V2[16]; q4z = V2[17];//vertex6
  100018. }
  100019. else if (minDotIndex == 3) {// y- face
  100020. q1x = V2[21]; q1y = V2[22]; q1z = V2[23];//vertex8
  100021. q2x = V2[9]; q2y = V2[10]; q2z = V2[11];//vertex4
  100022. q3x = V2[6]; q3y = V2[7]; q3z = V2[8];//vertex3
  100023. q4x = V2[18]; q4y = V2[19]; q4z = V2[20];//vertex7
  100024. }
  100025. else if (minDotIndex == 4) {// z+ face
  100026. q1x = V2[12]; q1y = V2[13]; q1z = V2[14];//vertex5
  100027. q2x = V2[18]; q2y = V2[19]; q2z = V2[20];//vertex7
  100028. q3x = V2[6]; q3y = V2[7]; q3z = V2[8];//vertex3
  100029. q4x = V2[0]; q4y = V2[1]; q4z = V2[2];//vertex1
  100030. }
  100031. else if (minDotIndex == 5) {// z- face
  100032. q1x = V2[3]; q1y = V2[4]; q1z = V2[5];//vertex2
  100033. q2x = V2[9]; q2y = V2[10]; q2z = V2[11];//vertex4
  100034. q3x = V2[21]; q3y = V2[22]; q3z = V2[23];//vertex8
  100035. q4x = V2[15]; q4y = V2[16]; q4z = V2[17];//vertex6
  100036. }
  100037. }
  100038. // clip vertices
  100039. var numClipVertices;
  100040. var numAddedClipVertices;
  100041. var index;
  100042. var x1;
  100043. var y1;
  100044. var z1;
  100045. var x2;
  100046. var y2;
  100047. var z2;
  100048. this.clipVertices1[0] = q1x;
  100049. this.clipVertices1[1] = q1y;
  100050. this.clipVertices1[2] = q1z;
  100051. this.clipVertices1[3] = q2x;
  100052. this.clipVertices1[4] = q2y;
  100053. this.clipVertices1[5] = q2z;
  100054. this.clipVertices1[6] = q3x;
  100055. this.clipVertices1[7] = q3y;
  100056. this.clipVertices1[8] = q3z;
  100057. this.clipVertices1[9] = q4x;
  100058. this.clipVertices1[10] = q4y;
  100059. this.clipVertices1[11] = q4z;
  100060. numAddedClipVertices = 0;
  100061. x1 = this.clipVertices1[9];
  100062. y1 = this.clipVertices1[10];
  100063. z1 = this.clipVertices1[11];
  100064. dot1 = (x1 - cx - s1x) * n1x + (y1 - cy - s1y) * n1y + (z1 - cz - s1z) * n1z;
  100065. //var i = 4;
  100066. //while(i--){
  100067. for (var i = 0; i < 4; i++) {
  100068. index = i * 3;
  100069. x2 = this.clipVertices1[index];
  100070. y2 = this.clipVertices1[index + 1];
  100071. z2 = this.clipVertices1[index + 2];
  100072. dot2 = (x2 - cx - s1x) * n1x + (y2 - cy - s1y) * n1y + (z2 - cz - s1z) * n1z;
  100073. if (dot1 > 0) {
  100074. if (dot2 > 0) {
  100075. index = numAddedClipVertices * 3;
  100076. numAddedClipVertices++;
  100077. this.clipVertices2[index] = x2;
  100078. this.clipVertices2[index + 1] = y2;
  100079. this.clipVertices2[index + 2] = z2;
  100080. } else {
  100081. index = numAddedClipVertices * 3;
  100082. numAddedClipVertices++;
  100083. t = dot1 / (dot1 - dot2);
  100084. this.clipVertices2[index] = x1 + (x2 - x1) * t;
  100085. this.clipVertices2[index + 1] = y1 + (y2 - y1) * t;
  100086. this.clipVertices2[index + 2] = z1 + (z2 - z1) * t;
  100087. }
  100088. } else {
  100089. if (dot2 > 0) {
  100090. index = numAddedClipVertices * 3;
  100091. numAddedClipVertices++;
  100092. t = dot1 / (dot1 - dot2);
  100093. this.clipVertices2[index] = x1 + (x2 - x1) * t;
  100094. this.clipVertices2[index + 1] = y1 + (y2 - y1) * t;
  100095. this.clipVertices2[index + 2] = z1 + (z2 - z1) * t;
  100096. index = numAddedClipVertices * 3;
  100097. numAddedClipVertices++;
  100098. this.clipVertices2[index] = x2;
  100099. this.clipVertices2[index + 1] = y2;
  100100. this.clipVertices2[index + 2] = z2;
  100101. }
  100102. }
  100103. x1 = x2;
  100104. y1 = y2;
  100105. z1 = z2;
  100106. dot1 = dot2;
  100107. }
  100108. numClipVertices = numAddedClipVertices;
  100109. if (numClipVertices == 0) return;
  100110. numAddedClipVertices = 0;
  100111. index = (numClipVertices - 1) * 3;
  100112. x1 = this.clipVertices2[index];
  100113. y1 = this.clipVertices2[index + 1];
  100114. z1 = this.clipVertices2[index + 2];
  100115. dot1 = (x1 - cx - s2x) * n2x + (y1 - cy - s2y) * n2y + (z1 - cz - s2z) * n2z;
  100116. //i = numClipVertices;
  100117. //while(i--){
  100118. for (i = 0; i < numClipVertices; i++) {
  100119. index = i * 3;
  100120. x2 = this.clipVertices2[index];
  100121. y2 = this.clipVertices2[index + 1];
  100122. z2 = this.clipVertices2[index + 2];
  100123. dot2 = (x2 - cx - s2x) * n2x + (y2 - cy - s2y) * n2y + (z2 - cz - s2z) * n2z;
  100124. if (dot1 > 0) {
  100125. if (dot2 > 0) {
  100126. index = numAddedClipVertices * 3;
  100127. numAddedClipVertices++;
  100128. this.clipVertices1[index] = x2;
  100129. this.clipVertices1[index + 1] = y2;
  100130. this.clipVertices1[index + 2] = z2;
  100131. } else {
  100132. index = numAddedClipVertices * 3;
  100133. numAddedClipVertices++;
  100134. t = dot1 / (dot1 - dot2);
  100135. this.clipVertices1[index] = x1 + (x2 - x1) * t;
  100136. this.clipVertices1[index + 1] = y1 + (y2 - y1) * t;
  100137. this.clipVertices1[index + 2] = z1 + (z2 - z1) * t;
  100138. }
  100139. } else {
  100140. if (dot2 > 0) {
  100141. index = numAddedClipVertices * 3;
  100142. numAddedClipVertices++;
  100143. t = dot1 / (dot1 - dot2);
  100144. this.clipVertices1[index] = x1 + (x2 - x1) * t;
  100145. this.clipVertices1[index + 1] = y1 + (y2 - y1) * t;
  100146. this.clipVertices1[index + 2] = z1 + (z2 - z1) * t;
  100147. index = numAddedClipVertices * 3;
  100148. numAddedClipVertices++;
  100149. this.clipVertices1[index] = x2;
  100150. this.clipVertices1[index + 1] = y2;
  100151. this.clipVertices1[index + 2] = z2;
  100152. }
  100153. }
  100154. x1 = x2;
  100155. y1 = y2;
  100156. z1 = z2;
  100157. dot1 = dot2;
  100158. }
  100159. numClipVertices = numAddedClipVertices;
  100160. if (numClipVertices == 0) return;
  100161. numAddedClipVertices = 0;
  100162. index = (numClipVertices - 1) * 3;
  100163. x1 = this.clipVertices1[index];
  100164. y1 = this.clipVertices1[index + 1];
  100165. z1 = this.clipVertices1[index + 2];
  100166. dot1 = (x1 - cx + s1x) * -n1x + (y1 - cy + s1y) * -n1y + (z1 - cz + s1z) * -n1z;
  100167. //i = numClipVertices;
  100168. //while(i--){
  100169. for (i = 0; i < numClipVertices; i++) {
  100170. index = i * 3;
  100171. x2 = this.clipVertices1[index];
  100172. y2 = this.clipVertices1[index + 1];
  100173. z2 = this.clipVertices1[index + 2];
  100174. dot2 = (x2 - cx + s1x) * -n1x + (y2 - cy + s1y) * -n1y + (z2 - cz + s1z) * -n1z;
  100175. if (dot1 > 0) {
  100176. if (dot2 > 0) {
  100177. index = numAddedClipVertices * 3;
  100178. numAddedClipVertices++;
  100179. this.clipVertices2[index] = x2;
  100180. this.clipVertices2[index + 1] = y2;
  100181. this.clipVertices2[index + 2] = z2;
  100182. } else {
  100183. index = numAddedClipVertices * 3;
  100184. numAddedClipVertices++;
  100185. t = dot1 / (dot1 - dot2);
  100186. this.clipVertices2[index] = x1 + (x2 - x1) * t;
  100187. this.clipVertices2[index + 1] = y1 + (y2 - y1) * t;
  100188. this.clipVertices2[index + 2] = z1 + (z2 - z1) * t;
  100189. }
  100190. } else {
  100191. if (dot2 > 0) {
  100192. index = numAddedClipVertices * 3;
  100193. numAddedClipVertices++;
  100194. t = dot1 / (dot1 - dot2);
  100195. this.clipVertices2[index] = x1 + (x2 - x1) * t;
  100196. this.clipVertices2[index + 1] = y1 + (y2 - y1) * t;
  100197. this.clipVertices2[index + 2] = z1 + (z2 - z1) * t;
  100198. index = numAddedClipVertices * 3;
  100199. numAddedClipVertices++;
  100200. this.clipVertices2[index] = x2;
  100201. this.clipVertices2[index + 1] = y2;
  100202. this.clipVertices2[index + 2] = z2;
  100203. }
  100204. }
  100205. x1 = x2;
  100206. y1 = y2;
  100207. z1 = z2;
  100208. dot1 = dot2;
  100209. }
  100210. numClipVertices = numAddedClipVertices;
  100211. if (numClipVertices == 0) return;
  100212. numAddedClipVertices = 0;
  100213. index = (numClipVertices - 1) * 3;
  100214. x1 = this.clipVertices2[index];
  100215. y1 = this.clipVertices2[index + 1];
  100216. z1 = this.clipVertices2[index + 2];
  100217. dot1 = (x1 - cx + s2x) * -n2x + (y1 - cy + s2y) * -n2y + (z1 - cz + s2z) * -n2z;
  100218. //i = numClipVertices;
  100219. //while(i--){
  100220. for (i = 0; i < numClipVertices; i++) {
  100221. index = i * 3;
  100222. x2 = this.clipVertices2[index];
  100223. y2 = this.clipVertices2[index + 1];
  100224. z2 = this.clipVertices2[index + 2];
  100225. dot2 = (x2 - cx + s2x) * -n2x + (y2 - cy + s2y) * -n2y + (z2 - cz + s2z) * -n2z;
  100226. if (dot1 > 0) {
  100227. if (dot2 > 0) {
  100228. index = numAddedClipVertices * 3;
  100229. numAddedClipVertices++;
  100230. this.clipVertices1[index] = x2;
  100231. this.clipVertices1[index + 1] = y2;
  100232. this.clipVertices1[index + 2] = z2;
  100233. } else {
  100234. index = numAddedClipVertices * 3;
  100235. numAddedClipVertices++;
  100236. t = dot1 / (dot1 - dot2);
  100237. this.clipVertices1[index] = x1 + (x2 - x1) * t;
  100238. this.clipVertices1[index + 1] = y1 + (y2 - y1) * t;
  100239. this.clipVertices1[index + 2] = z1 + (z2 - z1) * t;
  100240. }
  100241. } else {
  100242. if (dot2 > 0) {
  100243. index = numAddedClipVertices * 3;
  100244. numAddedClipVertices++;
  100245. t = dot1 / (dot1 - dot2);
  100246. this.clipVertices1[index] = x1 + (x2 - x1) * t;
  100247. this.clipVertices1[index + 1] = y1 + (y2 - y1) * t;
  100248. this.clipVertices1[index + 2] = z1 + (z2 - z1) * t;
  100249. index = numAddedClipVertices * 3;
  100250. numAddedClipVertices++;
  100251. this.clipVertices1[index] = x2;
  100252. this.clipVertices1[index + 1] = y2;
  100253. this.clipVertices1[index + 2] = z2;
  100254. }
  100255. }
  100256. x1 = x2;
  100257. y1 = y2;
  100258. z1 = z2;
  100259. dot1 = dot2;
  100260. }
  100261. numClipVertices = numAddedClipVertices;
  100262. if (swap) {
  100263. var tb = b1;
  100264. b1 = b2;
  100265. b2 = tb;
  100266. }
  100267. if (numClipVertices == 0) return;
  100268. var flipped = b1 != shape1;
  100269. if (numClipVertices > 4) {
  100270. x1 = (q1x + q2x + q3x + q4x) * 0.25;
  100271. y1 = (q1y + q2y + q3y + q4y) * 0.25;
  100272. z1 = (q1z + q2z + q3z + q4z) * 0.25;
  100273. n1x = q1x - x1;
  100274. n1y = q1y - y1;
  100275. n1z = q1z - z1;
  100276. n2x = q2x - x1;
  100277. n2y = q2y - y1;
  100278. n2z = q2z - z1;
  100279. var index1 = 0;
  100280. var index2 = 0;
  100281. var index3 = 0;
  100282. var index4 = 0;
  100283. var maxDot = -this.INF;
  100284. minDot = this.INF;
  100285. //i = numClipVertices;
  100286. //while(i--){
  100287. for (i = 0; i < numClipVertices; i++) {
  100288. this.used[i] = false;
  100289. index = i * 3;
  100290. x1 = this.clipVertices1[index];
  100291. y1 = this.clipVertices1[index + 1];
  100292. z1 = this.clipVertices1[index + 2];
  100293. dot = x1 * n1x + y1 * n1y + z1 * n1z;
  100294. if (dot < minDot) {
  100295. minDot = dot;
  100296. index1 = i;
  100297. }
  100298. if (dot > maxDot) {
  100299. maxDot = dot;
  100300. index3 = i;
  100301. }
  100302. }
  100303. this.used[index1] = true;
  100304. this.used[index3] = true;
  100305. maxDot = -this.INF;
  100306. minDot = this.INF;
  100307. //i = numClipVertices;
  100308. //while(i--){
  100309. for (i = 0; i < numClipVertices; i++) {
  100310. if (this.used[i]) continue;
  100311. index = i * 3;
  100312. x1 = this.clipVertices1[index];
  100313. y1 = this.clipVertices1[index + 1];
  100314. z1 = this.clipVertices1[index + 2];
  100315. dot = x1 * n2x + y1 * n2y + z1 * n2z;
  100316. if (dot < minDot) {
  100317. minDot = dot;
  100318. index2 = i;
  100319. }
  100320. if (dot > maxDot) {
  100321. maxDot = dot;
  100322. index4 = i;
  100323. }
  100324. }
  100325. index = index1 * 3;
  100326. x1 = this.clipVertices1[index];
  100327. y1 = this.clipVertices1[index + 1];
  100328. z1 = this.clipVertices1[index + 2];
  100329. dot = (x1 - cx) * nx + (y1 - cy) * ny + (z1 - cz) * nz;
  100330. if (dot < 0) manifold.addPoint(x1, y1, z1, nx, ny, nz, dot, flipped);
  100331. index = index2 * 3;
  100332. x1 = this.clipVertices1[index];
  100333. y1 = this.clipVertices1[index + 1];
  100334. z1 = this.clipVertices1[index + 2];
  100335. dot = (x1 - cx) * nx + (y1 - cy) * ny + (z1 - cz) * nz;
  100336. if (dot < 0) manifold.addPoint(x1, y1, z1, nx, ny, nz, dot, flipped);
  100337. index = index3 * 3;
  100338. x1 = this.clipVertices1[index];
  100339. y1 = this.clipVertices1[index + 1];
  100340. z1 = this.clipVertices1[index + 2];
  100341. dot = (x1 - cx) * nx + (y1 - cy) * ny + (z1 - cz) * nz;
  100342. if (dot < 0) manifold.addPoint(x1, y1, z1, nx, ny, nz, dot, flipped);
  100343. index = index4 * 3;
  100344. x1 = this.clipVertices1[index];
  100345. y1 = this.clipVertices1[index + 1];
  100346. z1 = this.clipVertices1[index + 2];
  100347. dot = (x1 - cx) * nx + (y1 - cy) * ny + (z1 - cz) * nz;
  100348. if (dot < 0) manifold.addPoint(x1, y1, z1, nx, ny, nz, dot, flipped);
  100349. } else {
  100350. //i = numClipVertices;
  100351. //while(i--){
  100352. for (i = 0; i < numClipVertices; i++) {
  100353. index = i * 3;
  100354. x1 = this.clipVertices1[index];
  100355. y1 = this.clipVertices1[index + 1];
  100356. z1 = this.clipVertices1[index + 2];
  100357. dot = (x1 - cx) * nx + (y1 - cy) * ny + (z1 - cz) * nz;
  100358. if (dot < 0) manifold.addPoint(x1, y1, z1, nx, ny, nz, dot, flipped);
  100359. }
  100360. }
  100361. };
  100362. /**
  100363. * A collision detector which detects collisions between sphere and box.
  100364. * @author saharan
  100365. */
  100366. OIMO.SphereBoxCollisionDetector = function (flip) {
  100367. OIMO.CollisionDetector.call(this);
  100368. this.flip = flip;
  100369. };
  100370. OIMO.SphereBoxCollisionDetector.prototype = Object.create(OIMO.CollisionDetector.prototype);
  100371. OIMO.SphereBoxCollisionDetector.prototype.constructor = OIMO.SphereBoxCollisionDetector;
  100372. OIMO.SphereBoxCollisionDetector.prototype.detectCollision = function (shape1, shape2, manifold) {
  100373. var s;
  100374. var b;
  100375. if (this.flip) {
  100376. s = (shape2);
  100377. b = (shape1);
  100378. } else {
  100379. s = (shape1);
  100380. b = (shape2);
  100381. }
  100382. var D = b.dimentions;
  100383. var ps = s.position;
  100384. var psx = ps.x;
  100385. var psy = ps.y;
  100386. var psz = ps.z;
  100387. var pb = b.position;
  100388. var pbx = pb.x;
  100389. var pby = pb.y;
  100390. var pbz = pb.z;
  100391. var rad = s.radius;
  100392. var hw = b.halfWidth;
  100393. var hh = b.halfHeight;
  100394. var hd = b.halfDepth;
  100395. var dx = psx - pbx;
  100396. var dy = psy - pby;
  100397. var dz = psz - pbz;
  100398. var sx = D[0] * dx + D[1] * dy + D[2] * dz;
  100399. var sy = D[3] * dx + D[4] * dy + D[5] * dz;
  100400. var sz = D[6] * dx + D[7] * dy + D[8] * dz;
  100401. var cx;
  100402. var cy;
  100403. var cz;
  100404. var len;
  100405. var invLen;
  100406. var overlap = 0;
  100407. if (sx > hw) {
  100408. sx = hw;
  100409. } else if (sx < -hw) {
  100410. sx = -hw;
  100411. } else {
  100412. overlap = 1;
  100413. }
  100414. if (sy > hh) {
  100415. sy = hh;
  100416. } else if (sy < -hh) {
  100417. sy = -hh;
  100418. } else {
  100419. overlap |= 2;
  100420. }
  100421. if (sz > hd) {
  100422. sz = hd;
  100423. } else if (sz < -hd) {
  100424. sz = -hd;
  100425. } else {
  100426. overlap |= 4;
  100427. }
  100428. if (overlap == 7) {
  100429. // center of sphere is in the box
  100430. if (sx < 0) {
  100431. dx = hw + sx;
  100432. } else {
  100433. dx = hw - sx;
  100434. }
  100435. if (sy < 0) {
  100436. dy = hh + sy;
  100437. } else {
  100438. dy = hh - sy;
  100439. }
  100440. if (sz < 0) {
  100441. dz = hd + sz;
  100442. } else {
  100443. dz = hd - sz;
  100444. }
  100445. if (dx < dy) {
  100446. if (dx < dz) {
  100447. len = dx - hw;
  100448. if (sx < 0) {
  100449. sx = -hw;
  100450. dx = D[0];
  100451. dy = D[1];
  100452. dz = D[2];
  100453. } else {
  100454. sx = hw;
  100455. dx = -D[0];
  100456. dy = -D[1];
  100457. dz = -D[2];
  100458. }
  100459. } else {
  100460. len = dz - hd;
  100461. if (sz < 0) {
  100462. sz = -hd;
  100463. dx = D[6];
  100464. dy = D[7];
  100465. dz = D[8];
  100466. } else {
  100467. sz = hd;
  100468. dx = -D[6];
  100469. dy = -D[7];
  100470. dz = -D[8];
  100471. }
  100472. }
  100473. } else {
  100474. if (dy < dz) {
  100475. len = dy - hh;
  100476. if (sy < 0) {
  100477. sy = -hh;
  100478. dx = D[3];
  100479. dy = D[4];
  100480. dz = D[5];
  100481. } else {
  100482. sy = hh;
  100483. dx = -D[3];
  100484. dy = -D[4];
  100485. dz = -D[5];
  100486. }
  100487. } else {
  100488. len = dz - hd;
  100489. if (sz < 0) {
  100490. sz = -hd;
  100491. dx = D[6];
  100492. dy = D[7];
  100493. dz = D[8];
  100494. } else {
  100495. sz = hd;
  100496. dx = -D[6];
  100497. dy = -D[7];
  100498. dz = -D[8];
  100499. }
  100500. }
  100501. }
  100502. cx = pbx + sx * D[0] + sy * D[3] + sz * D[6];
  100503. cy = pby + sx * D[1] + sy * D[4] + sz * D[7];
  100504. cz = pbz + sx * D[2] + sy * D[5] + sz * D[8];
  100505. manifold.addPoint(psx + rad * dx, psy + rad * dy, psz + rad * dz, dx, dy, dz, len - rad, this.flip);
  100506. } else {
  100507. cx = pbx + sx * D[0] + sy * D[3] + sz * D[6];
  100508. cy = pby + sx * D[1] + sy * D[4] + sz * D[7];
  100509. cz = pbz + sx * D[2] + sy * D[5] + sz * D[8];
  100510. dx = cx - ps.x;
  100511. dy = cy - ps.y;
  100512. dz = cz - ps.z;
  100513. len = dx * dx + dy * dy + dz * dz;
  100514. if (len > 0 && len < rad * rad) {
  100515. len = OIMO.sqrt(len);
  100516. invLen = 1 / len;
  100517. dx *= invLen;
  100518. dy *= invLen;
  100519. dz *= invLen;
  100520. manifold.addPoint(psx + rad * dx, psy + rad * dy, psz + rad * dz, dx, dy, dz, len - rad, this.flip);
  100521. }
  100522. }
  100523. };
  100524. /**
  100525. * A collision detector which detects collisions between two spheres.
  100526. * @author saharan
  100527. */
  100528. OIMO.SphereSphereCollisionDetector = function () {
  100529. OIMO.CollisionDetector.call(this);
  100530. };
  100531. OIMO.SphereSphereCollisionDetector.prototype = Object.create(OIMO.CollisionDetector.prototype);
  100532. OIMO.SphereSphereCollisionDetector.prototype.constructor = OIMO.SphereSphereCollisionDetector;
  100533. OIMO.SphereSphereCollisionDetector.prototype.detectCollision = function (shape1, shape2, manifold) {
  100534. var s1 = shape1;
  100535. var s2 = shape2;
  100536. var p1 = s1.position;
  100537. var p2 = s2.position;
  100538. var dx = p2.x - p1.x;
  100539. var dy = p2.y - p1.y;
  100540. var dz = p2.z - p1.z;
  100541. var len = dx * dx + dy * dy + dz * dz;
  100542. var r1 = s1.radius;
  100543. var r2 = s2.radius;
  100544. var rad = r1 + r2;
  100545. if (len > 0 && len < rad * rad) {
  100546. len = OIMO.sqrt(len);
  100547. var invLen = 1 / len;
  100548. dx *= invLen;
  100549. dy *= invLen;
  100550. dz *= invLen;
  100551. manifold.addPoint(p1.x + dx * r1, p1.y + dy * r1, p1.z + dz * r1, dx, dy, dz, len - rad, false);
  100552. }
  100553. };
  100554. OIMO.BoxCylinderCollisionDetector = function (flip) {
  100555. OIMO.CollisionDetector.call(this);
  100556. this.flip = flip;
  100557. };
  100558. OIMO.BoxCylinderCollisionDetector.prototype = Object.create(OIMO.CollisionDetector.prototype);
  100559. OIMO.BoxCylinderCollisionDetector.prototype.constructor = OIMO.BoxCylinderCollisionDetector;
  100560. OIMO.BoxCylinderCollisionDetector.prototype.getSep = function (c1, c2, sep, pos, dep) {
  100561. var t1x;
  100562. var t1y;
  100563. var t1z;
  100564. var t2x;
  100565. var t2y;
  100566. var t2z;
  100567. var sup = new OIMO.Vec3();
  100568. var len;
  100569. var p1x;
  100570. var p1y;
  100571. var p1z;
  100572. var p2x;
  100573. var p2y;
  100574. var p2z;
  100575. var v01x = c1.position.x;
  100576. var v01y = c1.position.y;
  100577. var v01z = c1.position.z;
  100578. var v02x = c2.position.x;
  100579. var v02y = c2.position.y;
  100580. var v02z = c2.position.z;
  100581. var v0x = v02x - v01x;
  100582. var v0y = v02y - v01y;
  100583. var v0z = v02z - v01z;
  100584. if (v0x * v0x + v0y * v0y + v0z * v0z == 0) v0y = 0.001;
  100585. var nx = -v0x;
  100586. var ny = -v0y;
  100587. var nz = -v0z;
  100588. this.supportPointB(c1, -nx, -ny, -nz, sup);
  100589. var v11x = sup.x;
  100590. var v11y = sup.y;
  100591. var v11z = sup.z;
  100592. this.supportPointC(c2, nx, ny, nz, sup);
  100593. var v12x = sup.x;
  100594. var v12y = sup.y;
  100595. var v12z = sup.z;
  100596. var v1x = v12x - v11x;
  100597. var v1y = v12y - v11y;
  100598. var v1z = v12z - v11z;
  100599. if (v1x * nx + v1y * ny + v1z * nz <= 0) {
  100600. return false;
  100601. }
  100602. nx = v1y * v0z - v1z * v0y;
  100603. ny = v1z * v0x - v1x * v0z;
  100604. nz = v1x * v0y - v1y * v0x;
  100605. if (nx * nx + ny * ny + nz * nz == 0) {
  100606. sep.init(v1x - v0x, v1y - v0y, v1z - v0z);
  100607. sep.normalize(sep);
  100608. pos.init((v11x + v12x) * 0.5, (v11y + v12y) * 0.5, (v11z + v12z) * 0.5);
  100609. return true;
  100610. }
  100611. this.supportPointB(c1, -nx, -ny, -nz, sup);
  100612. var v21x = sup.x;
  100613. var v21y = sup.y;
  100614. var v21z = sup.z;
  100615. this.supportPointC(c2, nx, ny, nz, sup);
  100616. var v22x = sup.x;
  100617. var v22y = sup.y;
  100618. var v22z = sup.z;
  100619. var v2x = v22x - v21x;
  100620. var v2y = v22y - v21y;
  100621. var v2z = v22z - v21z;
  100622. if (v2x * nx + v2y * ny + v2z * nz <= 0) {
  100623. return false;
  100624. }
  100625. t1x = v1x - v0x;
  100626. t1y = v1y - v0y;
  100627. t1z = v1z - v0z;
  100628. t2x = v2x - v0x;
  100629. t2y = v2y - v0y;
  100630. t2z = v2z - v0z;
  100631. nx = t1y * t2z - t1z * t2y;
  100632. ny = t1z * t2x - t1x * t2z;
  100633. nz = t1x * t2y - t1y * t2x;
  100634. if (nx * v0x + ny * v0y + nz * v0z > 0) {
  100635. t1x = v1x;
  100636. t1y = v1y;
  100637. t1z = v1z;
  100638. v1x = v2x;
  100639. v1y = v2y;
  100640. v1z = v2z;
  100641. v2x = t1x;
  100642. v2y = t1y;
  100643. v2z = t1z;
  100644. t1x = v11x;
  100645. t1y = v11y;
  100646. t1z = v11z;
  100647. v11x = v21x;
  100648. v11y = v21y;
  100649. v11z = v21z;
  100650. v21x = t1x;
  100651. v21y = t1y;
  100652. v21z = t1z;
  100653. t1x = v12x;
  100654. t1y = v12y;
  100655. t1z = v12z;
  100656. v12x = v22x;
  100657. v12y = v22y;
  100658. v12z = v22z;
  100659. v22x = t1x;
  100660. v22y = t1y;
  100661. v22z = t1z;
  100662. nx = -nx;
  100663. ny = -ny;
  100664. nz = -nz;
  100665. }
  100666. var iterations = 0;
  100667. while (true) {
  100668. if (++iterations > 100) {
  100669. return false;
  100670. }
  100671. this.supportPointB(c1, -nx, -ny, -nz, sup);
  100672. var v31x = sup.x;
  100673. var v31y = sup.y;
  100674. var v31z = sup.z;
  100675. this.supportPointC(c2, nx, ny, nz, sup);
  100676. var v32x = sup.x;
  100677. var v32y = sup.y;
  100678. var v32z = sup.z;
  100679. var v3x = v32x - v31x;
  100680. var v3y = v32y - v31y;
  100681. var v3z = v32z - v31z;
  100682. if (v3x * nx + v3y * ny + v3z * nz <= 0) {
  100683. return false;
  100684. }
  100685. if ((v1y * v3z - v1z * v3y) * v0x + (v1z * v3x - v1x * v3z) * v0y + (v1x * v3y - v1y * v3x) * v0z < 0) {
  100686. v2x = v3x;
  100687. v2y = v3y;
  100688. v2z = v3z;
  100689. v21x = v31x;
  100690. v21y = v31y;
  100691. v21z = v31z;
  100692. v22x = v32x;
  100693. v22y = v32y;
  100694. v22z = v32z;
  100695. t1x = v1x - v0x;
  100696. t1y = v1y - v0y;
  100697. t1z = v1z - v0z;
  100698. t2x = v3x - v0x;
  100699. t2y = v3y - v0y;
  100700. t2z = v3z - v0z;
  100701. nx = t1y * t2z - t1z * t2y;
  100702. ny = t1z * t2x - t1x * t2z;
  100703. nz = t1x * t2y - t1y * t2x;
  100704. continue;
  100705. }
  100706. if ((v3y * v2z - v3z * v2y) * v0x + (v3z * v2x - v3x * v2z) * v0y + (v3x * v2y - v3y * v2x) * v0z < 0) {
  100707. v1x = v3x;
  100708. v1y = v3y;
  100709. v1z = v3z;
  100710. v11x = v31x;
  100711. v11y = v31y;
  100712. v11z = v31z;
  100713. v12x = v32x;
  100714. v12y = v32y;
  100715. v12z = v32z;
  100716. t1x = v3x - v0x;
  100717. t1y = v3y - v0y;
  100718. t1z = v3z - v0z;
  100719. t2x = v2x - v0x;
  100720. t2y = v2y - v0y;
  100721. t2z = v2z - v0z;
  100722. nx = t1y * t2z - t1z * t2y;
  100723. ny = t1z * t2x - t1x * t2z;
  100724. nz = t1x * t2y - t1y * t2x;
  100725. continue;
  100726. }
  100727. var hit = false;
  100728. while (true) {
  100729. t1x = v2x - v1x;
  100730. t1y = v2y - v1y;
  100731. t1z = v2z - v1z;
  100732. t2x = v3x - v1x;
  100733. t2y = v3y - v1y;
  100734. t2z = v3z - v1z;
  100735. nx = t1y * t2z - t1z * t2y;
  100736. ny = t1z * t2x - t1x * t2z;
  100737. nz = t1x * t2y - t1y * t2x;
  100738. len = 1 / OIMO.sqrt(nx * nx + ny * ny + nz * nz);
  100739. nx *= len;
  100740. ny *= len;
  100741. nz *= len;
  100742. if (nx * v1x + ny * v1y + nz * v1z >= 0 && !hit) {
  100743. var b0 = (v1y * v2z - v1z * v2y) * v3x + (v1z * v2x - v1x * v2z) * v3y + (v1x * v2y - v1y * v2x) * v3z;
  100744. var b1 = (v3y * v2z - v3z * v2y) * v0x + (v3z * v2x - v3x * v2z) * v0y + (v3x * v2y - v3y * v2x) * v0z;
  100745. var b2 = (v0y * v1z - v0z * v1y) * v3x + (v0z * v1x - v0x * v1z) * v3y + (v0x * v1y - v0y * v1x) * v3z;
  100746. var b3 = (v2y * v1z - v2z * v1y) * v0x + (v2z * v1x - v2x * v1z) * v0y + (v2x * v1y - v2y * v1x) * v0z;
  100747. var sum = b0 + b1 + b2 + b3;
  100748. if (sum <= 0) {
  100749. b0 = 0;
  100750. b1 = (v2y * v3z - v2z * v3y) * nx + (v2z * v3x - v2x * v3z) * ny + (v2x * v3y - v2y * v3x) * nz;
  100751. b2 = (v3y * v2z - v3z * v2y) * nx + (v3z * v2x - v3x * v2z) * ny + (v3x * v2y - v3y * v2x) * nz;
  100752. b3 = (v1y * v2z - v1z * v2y) * nx + (v1z * v2x - v1x * v2z) * ny + (v1x * v2y - v1y * v2x) * nz;
  100753. sum = b1 + b2 + b3;
  100754. }
  100755. var inv = 1 / sum;
  100756. p1x = (v01x * b0 + v11x * b1 + v21x * b2 + v31x * b3) * inv;
  100757. p1y = (v01y * b0 + v11y * b1 + v21y * b2 + v31y * b3) * inv;
  100758. p1z = (v01z * b0 + v11z * b1 + v21z * b2 + v31z * b3) * inv;
  100759. p2x = (v02x * b0 + v12x * b1 + v22x * b2 + v32x * b3) * inv;
  100760. p2y = (v02y * b0 + v12y * b1 + v22y * b2 + v32y * b3) * inv;
  100761. p2z = (v02z * b0 + v12z * b1 + v22z * b2 + v32z * b3) * inv;
  100762. hit = true;
  100763. }
  100764. this.supportPointB(c1, -nx, -ny, -nz, sup);
  100765. var v41x = sup.x;
  100766. var v41y = sup.y;
  100767. var v41z = sup.z;
  100768. this.supportPointC(c2, nx, ny, nz, sup);
  100769. var v42x = sup.x;
  100770. var v42y = sup.y;
  100771. var v42z = sup.z;
  100772. var v4x = v42x - v41x;
  100773. var v4y = v42y - v41y;
  100774. var v4z = v42z - v41z;
  100775. var separation = -(v4x * nx + v4y * ny + v4z * nz);
  100776. if ((v4x - v3x) * nx + (v4y - v3y) * ny + (v4z - v3z) * nz <= 0.01 || separation >= 0) {
  100777. if (hit) {
  100778. sep.init(-nx, -ny, -nz);
  100779. pos.init((p1x + p2x) * 0.5, (p1y + p2y) * 0.5, (p1z + p2z) * 0.5);
  100780. dep.x = separation;
  100781. return true;
  100782. }
  100783. return false;
  100784. }
  100785. if (
  100786. (v4y * v1z - v4z * v1y) * v0x +
  100787. (v4z * v1x - v4x * v1z) * v0y +
  100788. (v4x * v1y - v4y * v1x) * v0z < 0
  100789. ) {
  100790. if (
  100791. (v4y * v2z - v4z * v2y) * v0x +
  100792. (v4z * v2x - v4x * v2z) * v0y +
  100793. (v4x * v2y - v4y * v2x) * v0z < 0
  100794. ) {
  100795. v1x = v4x;
  100796. v1y = v4y;
  100797. v1z = v4z;
  100798. v11x = v41x;
  100799. v11y = v41y;
  100800. v11z = v41z;
  100801. v12x = v42x;
  100802. v12y = v42y;
  100803. v12z = v42z;
  100804. } else {
  100805. v3x = v4x;
  100806. v3y = v4y;
  100807. v3z = v4z;
  100808. v31x = v41x;
  100809. v31y = v41y;
  100810. v31z = v41z;
  100811. v32x = v42x;
  100812. v32y = v42y;
  100813. v32z = v42z;
  100814. }
  100815. } else {
  100816. if (
  100817. (v4y * v3z - v4z * v3y) * v0x +
  100818. (v4z * v3x - v4x * v3z) * v0y +
  100819. (v4x * v3y - v4y * v3x) * v0z < 0
  100820. ) {
  100821. v2x = v4x;
  100822. v2y = v4y;
  100823. v2z = v4z;
  100824. v21x = v41x;
  100825. v21y = v41y;
  100826. v21z = v41z;
  100827. v22x = v42x;
  100828. v22y = v42y;
  100829. v22z = v42z;
  100830. } else {
  100831. v1x = v4x;
  100832. v1y = v4y;
  100833. v1z = v4z;
  100834. v11x = v41x;
  100835. v11y = v41y;
  100836. v11z = v41z;
  100837. v12x = v42x;
  100838. v12y = v42y;
  100839. v12z = v42z;
  100840. }
  100841. }
  100842. }
  100843. }
  100844. //return false;
  100845. };
  100846. OIMO.BoxCylinderCollisionDetector.prototype.supportPointB = function (c, dx, dy, dz, out) {
  100847. var rot = c.rotation.elements;
  100848. var ldx = rot[0] * dx + rot[3] * dy + rot[6] * dz;
  100849. var ldy = rot[1] * dx + rot[4] * dy + rot[7] * dz;
  100850. var ldz = rot[2] * dx + rot[5] * dy + rot[8] * dz;
  100851. var w = c.halfWidth;
  100852. var h = c.halfHeight;
  100853. var d = c.halfDepth;
  100854. var ox;
  100855. var oy;
  100856. var oz;
  100857. if (ldx < 0) ox = -w;
  100858. else ox = w;
  100859. if (ldy < 0) oy = -h;
  100860. else oy = h;
  100861. if (ldz < 0) oz = -d;
  100862. else oz = d;
  100863. ldx = rot[0] * ox + rot[1] * oy + rot[2] * oz + c.position.x;
  100864. ldy = rot[3] * ox + rot[4] * oy + rot[5] * oz + c.position.y;
  100865. ldz = rot[6] * ox + rot[7] * oy + rot[8] * oz + c.position.z;
  100866. out.init(ldx, ldy, ldz);
  100867. };
  100868. OIMO.BoxCylinderCollisionDetector.prototype.supportPointC = function (c, dx, dy, dz, out) {
  100869. var rot = c.rotation.elements;
  100870. var ldx = rot[0] * dx + rot[3] * dy + rot[6] * dz;
  100871. var ldy = rot[1] * dx + rot[4] * dy + rot[7] * dz;
  100872. var ldz = rot[2] * dx + rot[5] * dy + rot[8] * dz;
  100873. var radx = ldx;
  100874. var radz = ldz;
  100875. var len = radx * radx + radz * radz;
  100876. var rad = c.radius;
  100877. var hh = c.halfHeight;
  100878. var ox;
  100879. var oy;
  100880. var oz;
  100881. if (len == 0) {
  100882. if (ldy < 0) {
  100883. ox = rad;
  100884. oy = -hh;
  100885. oz = 0;
  100886. } else {
  100887. ox = rad;
  100888. oy = hh;
  100889. oz = 0;
  100890. }
  100891. } else {
  100892. len = c.radius / OIMO.sqrt(len);
  100893. if (ldy < 0) {
  100894. ox = radx * len;
  100895. oy = -hh;
  100896. oz = radz * len;
  100897. } else {
  100898. ox = radx * len;
  100899. oy = hh;
  100900. oz = radz * len;
  100901. }
  100902. }
  100903. ldx = rot[0] * ox + rot[1] * oy + rot[2] * oz + c.position.x;
  100904. ldy = rot[3] * ox + rot[4] * oy + rot[5] * oz + c.position.y;
  100905. ldz = rot[6] * ox + rot[7] * oy + rot[8] * oz + c.position.z;
  100906. out.init(ldx, ldy, ldz);
  100907. };
  100908. OIMO.BoxCylinderCollisionDetector.prototype.detectCollision = function (shape1, shape2, manifold) {
  100909. var b;
  100910. var c;
  100911. if (this.flip) {
  100912. b = shape2;
  100913. c = shape1;
  100914. } else {
  100915. b = shape1;
  100916. c = shape2;
  100917. }
  100918. var sep = new OIMO.Vec3();
  100919. var pos = new OIMO.Vec3();
  100920. var dep = new OIMO.Vec3();
  100921. var co;
  100922. if (!this.getSep(b, c, sep, pos, dep)) return;
  100923. var pbx = b.position.x;
  100924. var pby = b.position.y;
  100925. var pbz = b.position.z;
  100926. var pcx = c.position.x;
  100927. var pcy = c.position.y;
  100928. var pcz = c.position.z;
  100929. var bw = b.halfWidth;
  100930. var bh = b.halfHeight;
  100931. var bd = b.halfDepth;
  100932. var ch = c.halfHeight;
  100933. var r = c.radius;
  100934. var D = b.dimentions;
  100935. var nwx = D[0];//b.normalDirectionWidth.x;
  100936. var nwy = D[1];//b.normalDirectionWidth.y;
  100937. var nwz = D[2];//b.normalDirectionWidth.z;
  100938. var nhx = D[3];//b.normalDirectionHeight.x;
  100939. var nhy = D[4];//b.normalDirectionHeight.y;
  100940. var nhz = D[5];//b.normalDirectionHeight.z;
  100941. var ndx = D[6];//b.normalDirectionDepth.x;
  100942. var ndy = D[7];//b.normalDirectionDepth.y;
  100943. var ndz = D[8];//b.normalDirectionDepth.z;
  100944. var dwx = D[9];//b.halfDirectionWidth.x;
  100945. var dwy = D[10];//b.halfDirectionWidth.y;
  100946. var dwz = D[11];//b.halfDirectionWidth.z;
  100947. var dhx = D[12];//b.halfDirectionHeight.x;
  100948. var dhy = D[13];//b.halfDirectionHeight.y;
  100949. var dhz = D[14];//b.halfDirectionHeight.z;
  100950. var ddx = D[15];//b.halfDirectionDepth.x;
  100951. var ddy = D[16];//b.halfDirectionDepth.y;
  100952. var ddz = D[17];//b.halfDirectionDepth.z;
  100953. var ncx = c.normalDirection.x;
  100954. var ncy = c.normalDirection.y;
  100955. var ncz = c.normalDirection.z;
  100956. var dcx = c.halfDirection.x;
  100957. var dcy = c.halfDirection.y;
  100958. var dcz = c.halfDirection.z;
  100959. var nx = sep.x;
  100960. var ny = sep.y;
  100961. var nz = sep.z;
  100962. var dotw = nx * nwx + ny * nwy + nz * nwz;
  100963. var doth = nx * nhx + ny * nhy + nz * nhz;
  100964. var dotd = nx * ndx + ny * ndy + nz * ndz;
  100965. var dotc = nx * ncx + ny * ncy + nz * ncz;
  100966. var right1 = dotw > 0;
  100967. var right2 = doth > 0;
  100968. var right3 = dotd > 0;
  100969. var right4 = dotc > 0;
  100970. if (!right1) dotw = -dotw;
  100971. if (!right2) doth = -doth;
  100972. if (!right3) dotd = -dotd;
  100973. if (!right4) dotc = -dotc;
  100974. var state = 0;
  100975. if (dotc > 0.999) {
  100976. if (dotw > 0.999) {
  100977. if (dotw > dotc) state = 1;
  100978. else state = 4;
  100979. } else if (doth > 0.999) {
  100980. if (doth > dotc) state = 2;
  100981. else state = 4;
  100982. } else if (dotd > 0.999) {
  100983. if (dotd > dotc) state = 3;
  100984. else state = 4;
  100985. } else state = 4;
  100986. } else {
  100987. if (dotw > 0.999) state = 1;
  100988. else if (doth > 0.999) state = 2;
  100989. else if (dotd > 0.999) state = 3;
  100990. }
  100991. var cbx;
  100992. var cby;
  100993. var cbz;
  100994. var ccx;
  100995. var ccy;
  100996. var ccz;
  100997. var r00;
  100998. var r01;
  100999. var r02;
  101000. var r10;
  101001. var r11;
  101002. var r12;
  101003. var r20;
  101004. var r21;
  101005. var r22;
  101006. var px;
  101007. var py;
  101008. var pz;
  101009. var pd;
  101010. var dot;
  101011. var len;
  101012. var tx;
  101013. var ty;
  101014. var tz;
  101015. var td;
  101016. var dx;
  101017. var dy;
  101018. var dz;
  101019. var d1x;
  101020. var d1y;
  101021. var d1z;
  101022. var d2x;
  101023. var d2y;
  101024. var d2z;
  101025. var sx;
  101026. var sy;
  101027. var sz;
  101028. var sd;
  101029. var ex;
  101030. var ey;
  101031. var ez;
  101032. var ed;
  101033. var dot1;
  101034. var dot2;
  101035. var t1;
  101036. var t2;
  101037. var dir1x;
  101038. var dir1y;
  101039. var dir1z;
  101040. var dir2x;
  101041. var dir2y;
  101042. var dir2z;
  101043. var dir1l;
  101044. var dir2l;
  101045. if (state == 0) {
  101046. //manifold.addPoint(pos.x,pos.y,pos.z,nx,ny,nz,dep.x,b,c,0,0,false);
  101047. manifold.addPoint(pos.x, pos.y, pos.z, nx, ny, nz, dep.x, this.flip);
  101048. } else if (state == 4) {
  101049. if (right4) {
  101050. ccx = pcx - dcx;
  101051. ccy = pcy - dcy;
  101052. ccz = pcz - dcz;
  101053. nx = -ncx;
  101054. ny = -ncy;
  101055. nz = -ncz;
  101056. } else {
  101057. ccx = pcx + dcx;
  101058. ccy = pcy + dcy;
  101059. ccz = pcz + dcz;
  101060. nx = ncx;
  101061. ny = ncy;
  101062. nz = ncz;
  101063. }
  101064. var v1x;
  101065. var v1y;
  101066. var v1z;
  101067. var v2x;
  101068. var v2y;
  101069. var v2z;
  101070. var v3x;
  101071. var v3y;
  101072. var v3z;
  101073. var v4x;
  101074. var v4y;
  101075. var v4z;
  101076. dot = 1;
  101077. state = 0;
  101078. dot1 = nwx * nx + nwy * ny + nwz * nz;
  101079. if (dot1 < dot) {
  101080. dot = dot1;
  101081. state = 0;
  101082. }
  101083. if (-dot1 < dot) {
  101084. dot = -dot1;
  101085. state = 1;
  101086. }
  101087. dot1 = nhx * nx + nhy * ny + nhz * nz;
  101088. if (dot1 < dot) {
  101089. dot = dot1;
  101090. state = 2;
  101091. }
  101092. if (-dot1 < dot) {
  101093. dot = -dot1;
  101094. state = 3;
  101095. }
  101096. dot1 = ndx * nx + ndy * ny + ndz * nz;
  101097. if (dot1 < dot) {
  101098. dot = dot1;
  101099. state = 4;
  101100. }
  101101. if (-dot1 < dot) {
  101102. dot = -dot1;
  101103. state = 5;
  101104. }
  101105. var v = b.elements;
  101106. switch (state) {
  101107. case 0:
  101108. //v=b.vertex1;
  101109. v1x = v[0];//v.x;
  101110. v1y = v[1];//v.y;
  101111. v1z = v[2];//v.z;
  101112. //v=b.vertex3;
  101113. v2x = v[6];//v.x;
  101114. v2y = v[7];//v.y;
  101115. v2z = v[8];//v.z;
  101116. //v=b.vertex4;
  101117. v3x = v[9];//v.x;
  101118. v3y = v[10];//v.y;
  101119. v3z = v[11];//v.z;
  101120. //v=b.vertex2;
  101121. v4x = v[3];//v.x;
  101122. v4y = v[4];//v.y;
  101123. v4z = v[5];//v.z;
  101124. break;
  101125. case 1:
  101126. //v=b.vertex6;
  101127. v1x = v[15];//v.x;
  101128. v1y = v[16];//v.y;
  101129. v1z = v[17];//v.z;
  101130. //v=b.vertex8;
  101131. v2x = v[21];//v.x;
  101132. v2y = v[22];//v.y;
  101133. v2z = v[23];//v.z;
  101134. //v=b.vertex7;
  101135. v3x = v[18];//v.x;
  101136. v3y = v[19];//v.y;
  101137. v3z = v[20];//v.z;
  101138. //v=b.vertex5;
  101139. v4x = v[12];//v.x;
  101140. v4y = v[13];//v.y;
  101141. v4z = v[14];//v.z;
  101142. break;
  101143. case 2:
  101144. //v=b.vertex5;
  101145. v1x = v[12];//v.x;
  101146. v1y = v[13];//v.y;
  101147. v1z = v[14];//v.z;
  101148. //v=b.vertex1;
  101149. v2x = v[0];//v.x;
  101150. v2y = v[1];//v.y;
  101151. v2z = v[2];//v.z;
  101152. //v=b.vertex2;
  101153. v3x = v[3];//v.x;
  101154. v3y = v[4];//v.y;
  101155. v3z = v[5];//v.z;
  101156. //v=b.vertex6;
  101157. v4x = v[15];//v.x;
  101158. v4y = v[16];//v.y;
  101159. v4z = v[17];//v.z;
  101160. break;
  101161. case 3:
  101162. //v=b.vertex8;
  101163. v1x = v[21];//v.x;
  101164. v1y = v[22];//v.y;
  101165. v1z = v[23];//v.z;
  101166. //v=b.vertex4;
  101167. v2x = v[9];//v.x;
  101168. v2y = v[10];//v.y;
  101169. v2z = v[11];//v.z;
  101170. //v=b.vertex3;
  101171. v3x = v[6];//v.x;
  101172. v3y = v[7];//v.y;
  101173. v3z = v[8];//v.z;
  101174. //v=b.vertex7;
  101175. v4x = v[18];//v.x;
  101176. v4y = v[19];//v.y;
  101177. v4z = v[20];//v.z;
  101178. break;
  101179. case 4:
  101180. //v=b.vertex5;
  101181. v1x = v[12];//v.x;
  101182. v1y = v[13];//v.y;
  101183. v1z = v[14];//v.z;
  101184. //v=b.vertex7;
  101185. v2x = v[18];//v.x;
  101186. v2y = v[19];//v.y;
  101187. v2z = v[20];//v.z;
  101188. //v=b.vertex3;
  101189. v3x = v[6];//v.x;
  101190. v3y = v[7];//v.y;
  101191. v3z = v[8];//v.z;
  101192. //v=b.vertex1;
  101193. v4x = v[0];//v.x;
  101194. v4y = v[1];//v.y;
  101195. v4z = v[2];//v.z;
  101196. break;
  101197. case 5:
  101198. //v=b.vertex2;
  101199. v1x = v[3];//v.x;
  101200. v1y = v[4];//v.y;
  101201. v1z = v[5];//v.z;
  101202. //v=b.vertex4;
  101203. v2x = v[9];//v.x;
  101204. v2y = v[10];//v.y;
  101205. v2z = v[11];//v.z;
  101206. //v=b.vertex8;
  101207. v3x = v[21];//v.x;
  101208. v3y = v[22];//v.y;
  101209. v3z = v[23];//v.z;
  101210. //v=b.vertex6;
  101211. v4x = v[15];//v.x;
  101212. v4y = v[16];//v.y;
  101213. v4z = v[17];//v.z;
  101214. break;
  101215. }
  101216. pd = nx * (v1x - ccx) + ny * (v1y - ccy) + nz * (v1z - ccz);
  101217. if (pd <= 0) manifold.addPoint(v1x, v1y, v1z, -nx, -ny, -nz, pd, this.flip);
  101218. pd = nx * (v2x - ccx) + ny * (v2y - ccy) + nz * (v2z - ccz);
  101219. if (pd <= 0) manifold.addPoint(v2x, v2y, v2z, -nx, -ny, -nz, pd, this.flip);
  101220. pd = nx * (v3x - ccx) + ny * (v3y - ccy) + nz * (v3z - ccz);
  101221. if (pd <= 0) manifold.addPoint(v3x, v3y, v3z, -nx, -ny, -nz, pd, this.flip);
  101222. pd = nx * (v4x - ccx) + ny * (v4y - ccy) + nz * (v4z - ccz);
  101223. if (pd <= 0) manifold.addPoint(v4x, v4y, v4z, -nx, -ny, -nz, pd, this.flip);
  101224. } else {
  101225. switch (state) {
  101226. case 1:
  101227. if (right1) {
  101228. cbx = pbx + dwx;
  101229. cby = pby + dwy;
  101230. cbz = pbz + dwz;
  101231. nx = nwx;
  101232. ny = nwy;
  101233. nz = nwz;
  101234. } else {
  101235. cbx = pbx - dwx;
  101236. cby = pby - dwy;
  101237. cbz = pbz - dwz;
  101238. nx = -nwx;
  101239. ny = -nwy;
  101240. nz = -nwz;
  101241. }
  101242. dir1x = nhx;
  101243. dir1y = nhy;
  101244. dir1z = nhz;
  101245. dir1l = bh;
  101246. dir2x = ndx;
  101247. dir2y = ndy;
  101248. dir2z = ndz;
  101249. dir2l = bd;
  101250. break;
  101251. case 2:
  101252. if (right2) {
  101253. cbx = pbx + dhx;
  101254. cby = pby + dhy;
  101255. cbz = pbz + dhz;
  101256. nx = nhx;
  101257. ny = nhy;
  101258. nz = nhz;
  101259. } else {
  101260. cbx = pbx - dhx;
  101261. cby = pby - dhy;
  101262. cbz = pbz - dhz;
  101263. nx = -nhx;
  101264. ny = -nhy;
  101265. nz = -nhz;
  101266. }
  101267. dir1x = nwx;
  101268. dir1y = nwy;
  101269. dir1z = nwz;
  101270. dir1l = bw;
  101271. dir2x = ndx;
  101272. dir2y = ndy;
  101273. dir2z = ndz;
  101274. dir2l = bd;
  101275. break;
  101276. case 3:
  101277. if (right3) {
  101278. cbx = pbx + ddx;
  101279. cby = pby + ddy;
  101280. cbz = pbz + ddz;
  101281. nx = ndx;
  101282. ny = ndy;
  101283. nz = ndz;
  101284. } else {
  101285. cbx = pbx - ddx;
  101286. cby = pby - ddy;
  101287. cbz = pbz - ddz;
  101288. nx = -ndx;
  101289. ny = -ndy;
  101290. nz = -ndz;
  101291. }
  101292. dir1x = nwx;
  101293. dir1y = nwy;
  101294. dir1z = nwz;
  101295. dir1l = bw;
  101296. dir2x = nhx;
  101297. dir2y = nhy;
  101298. dir2z = nhz;
  101299. dir2l = bh;
  101300. break;
  101301. }
  101302. dot = nx * ncx + ny * ncy + nz * ncz;
  101303. if (dot < 0) len = ch;
  101304. else len = -ch;
  101305. ccx = pcx + len * ncx;
  101306. ccy = pcy + len * ncy;
  101307. ccz = pcz + len * ncz;
  101308. if (dotc >= 0.999999) {
  101309. tx = -ny;
  101310. ty = nz;
  101311. tz = nx;
  101312. } else {
  101313. tx = nx;
  101314. ty = ny;
  101315. tz = nz;
  101316. }
  101317. len = tx * ncx + ty * ncy + tz * ncz;
  101318. dx = len * ncx - tx;
  101319. dy = len * ncy - ty;
  101320. dz = len * ncz - tz;
  101321. len = OIMO.sqrt(dx * dx + dy * dy + dz * dz);
  101322. if (len == 0) return;
  101323. len = r / len;
  101324. dx *= len;
  101325. dy *= len;
  101326. dz *= len;
  101327. tx = ccx + dx;
  101328. ty = ccy + dy;
  101329. tz = ccz + dz;
  101330. if (dot < -0.96 || dot > 0.96) {
  101331. r00 = ncx * ncx * 1.5 - 0.5;
  101332. r01 = ncx * ncy * 1.5 - ncz * 0.866025403;
  101333. r02 = ncx * ncz * 1.5 + ncy * 0.866025403;
  101334. r10 = ncy * ncx * 1.5 + ncz * 0.866025403;
  101335. r11 = ncy * ncy * 1.5 - 0.5;
  101336. r12 = ncy * ncz * 1.5 - ncx * 0.866025403;
  101337. r20 = ncz * ncx * 1.5 - ncy * 0.866025403;
  101338. r21 = ncz * ncy * 1.5 + ncx * 0.866025403;
  101339. r22 = ncz * ncz * 1.5 - 0.5;
  101340. px = tx;
  101341. py = ty;
  101342. pz = tz;
  101343. pd = nx * (px - cbx) + ny * (py - cby) + nz * (pz - cbz);
  101344. tx = px - pd * nx - cbx;
  101345. ty = py - pd * ny - cby;
  101346. tz = pz - pd * nz - cbz;
  101347. sd = dir1x * tx + dir1y * ty + dir1z * tz;
  101348. ed = dir2x * tx + dir2y * ty + dir2z * tz;
  101349. if (sd < -dir1l) sd = -dir1l;
  101350. else if (sd > dir1l) sd = dir1l;
  101351. if (ed < -dir2l) ed = -dir2l;
  101352. else if (ed > dir2l) ed = dir2l;
  101353. tx = sd * dir1x + ed * dir2x;
  101354. ty = sd * dir1y + ed * dir2y;
  101355. tz = sd * dir1z + ed * dir2z;
  101356. px = cbx + tx;
  101357. py = cby + ty;
  101358. pz = cbz + tz;
  101359. manifold.addPoint(px, py, pz, nx, ny, nz, pd, this.flip);
  101360. px = dx * r00 + dy * r01 + dz * r02;
  101361. py = dx * r10 + dy * r11 + dz * r12;
  101362. pz = dx * r20 + dy * r21 + dz * r22;
  101363. px = (dx = px) + ccx;
  101364. py = (dy = py) + ccy;
  101365. pz = (dz = pz) + ccz;
  101366. pd = nx * (px - cbx) + ny * (py - cby) + nz * (pz - cbz);
  101367. if (pd <= 0) {
  101368. tx = px - pd * nx - cbx;
  101369. ty = py - pd * ny - cby;
  101370. tz = pz - pd * nz - cbz;
  101371. sd = dir1x * tx + dir1y * ty + dir1z * tz;
  101372. ed = dir2x * tx + dir2y * ty + dir2z * tz;
  101373. if (sd < -dir1l) sd = -dir1l;
  101374. else if (sd > dir1l) sd = dir1l;
  101375. if (ed < -dir2l) ed = -dir2l;
  101376. else if (ed > dir2l) ed = dir2l;
  101377. tx = sd * dir1x + ed * dir2x;
  101378. ty = sd * dir1y + ed * dir2y;
  101379. tz = sd * dir1z + ed * dir2z;
  101380. px = cbx + tx;
  101381. py = cby + ty;
  101382. pz = cbz + tz;
  101383. //manifold.addPoint(px,py,pz,nx,ny,nz,pd,b,c,2,0,false);
  101384. manifold.addPoint(px, py, pz, nx, ny, nz, pd, this.flip);
  101385. }
  101386. px = dx * r00 + dy * r01 + dz * r02;
  101387. py = dx * r10 + dy * r11 + dz * r12;
  101388. pz = dx * r20 + dy * r21 + dz * r22;
  101389. px = (dx = px) + ccx;
  101390. py = (dy = py) + ccy;
  101391. pz = (dz = pz) + ccz;
  101392. pd = nx * (px - cbx) + ny * (py - cby) + nz * (pz - cbz);
  101393. if (pd <= 0) {
  101394. tx = px - pd * nx - cbx;
  101395. ty = py - pd * ny - cby;
  101396. tz = pz - pd * nz - cbz;
  101397. sd = dir1x * tx + dir1y * ty + dir1z * tz;
  101398. ed = dir2x * tx + dir2y * ty + dir2z * tz;
  101399. if (sd < -dir1l) sd = -dir1l;
  101400. else if (sd > dir1l) sd = dir1l;
  101401. if (ed < -dir2l) ed = -dir2l;
  101402. else if (ed > dir2l) ed = dir2l;
  101403. tx = sd * dir1x + ed * dir2x;
  101404. ty = sd * dir1y + ed * dir2y;
  101405. tz = sd * dir1z + ed * dir2z;
  101406. px = cbx + tx;
  101407. py = cby + ty;
  101408. pz = cbz + tz;
  101409. //manifold.addPoint(px,py,pz,nx,ny,nz,pd,b,c,3,0,false);
  101410. manifold.addPoint(px, py, pz, nx, ny, nz, pd, this.flip);
  101411. }
  101412. } else {
  101413. sx = tx;
  101414. sy = ty;
  101415. sz = tz;
  101416. sd = nx * (sx - cbx) + ny * (sy - cby) + nz * (sz - cbz);
  101417. sx -= sd * nx;
  101418. sy -= sd * ny;
  101419. sz -= sd * nz;
  101420. if (dot > 0) {
  101421. ex = tx + dcx * 2;
  101422. ey = ty + dcy * 2;
  101423. ez = tz + dcz * 2;
  101424. } else {
  101425. ex = tx - dcx * 2;
  101426. ey = ty - dcy * 2;
  101427. ez = tz - dcz * 2;
  101428. }
  101429. ed = nx * (ex - cbx) + ny * (ey - cby) + nz * (ez - cbz);
  101430. ex -= ed * nx;
  101431. ey -= ed * ny;
  101432. ez -= ed * nz;
  101433. d1x = sx - cbx;
  101434. d1y = sy - cby;
  101435. d1z = sz - cbz;
  101436. d2x = ex - cbx;
  101437. d2y = ey - cby;
  101438. d2z = ez - cbz;
  101439. tx = ex - sx;
  101440. ty = ey - sy;
  101441. tz = ez - sz;
  101442. td = ed - sd;
  101443. dotw = d1x * dir1x + d1y * dir1y + d1z * dir1z;
  101444. doth = d2x * dir1x + d2y * dir1y + d2z * dir1z;
  101445. dot1 = dotw - dir1l;
  101446. dot2 = doth - dir1l;
  101447. if (dot1 > 0) {
  101448. if (dot2 > 0) return;
  101449. t1 = dot1 / (dot1 - dot2);
  101450. sx = sx + tx * t1;
  101451. sy = sy + ty * t1;
  101452. sz = sz + tz * t1;
  101453. sd = sd + td * t1;
  101454. d1x = sx - cbx;
  101455. d1y = sy - cby;
  101456. d1z = sz - cbz;
  101457. dotw = d1x * dir1x + d1y * dir1y + d1z * dir1z;
  101458. tx = ex - sx;
  101459. ty = ey - sy;
  101460. tz = ez - sz;
  101461. td = ed - sd;
  101462. } else if (dot2 > 0) {
  101463. t1 = dot1 / (dot1 - dot2);
  101464. ex = sx + tx * t1;
  101465. ey = sy + ty * t1;
  101466. ez = sz + tz * t1;
  101467. ed = sd + td * t1;
  101468. d2x = ex - cbx;
  101469. d2y = ey - cby;
  101470. d2z = ez - cbz;
  101471. doth = d2x * dir1x + d2y * dir1y + d2z * dir1z;
  101472. tx = ex - sx;
  101473. ty = ey - sy;
  101474. tz = ez - sz;
  101475. td = ed - sd;
  101476. }
  101477. dot1 = dotw + dir1l;
  101478. dot2 = doth + dir1l;
  101479. if (dot1 < 0) {
  101480. if (dot2 < 0) return;
  101481. t1 = dot1 / (dot1 - dot2);
  101482. sx = sx + tx * t1;
  101483. sy = sy + ty * t1;
  101484. sz = sz + tz * t1;
  101485. sd = sd + td * t1;
  101486. d1x = sx - cbx;
  101487. d1y = sy - cby;
  101488. d1z = sz - cbz;
  101489. tx = ex - sx;
  101490. ty = ey - sy;
  101491. tz = ez - sz;
  101492. td = ed - sd;
  101493. } else if (dot2 < 0) {
  101494. t1 = dot1 / (dot1 - dot2);
  101495. ex = sx + tx * t1;
  101496. ey = sy + ty * t1;
  101497. ez = sz + tz * t1;
  101498. ed = sd + td * t1;
  101499. d2x = ex - cbx;
  101500. d2y = ey - cby;
  101501. d2z = ez - cbz;
  101502. tx = ex - sx;
  101503. ty = ey - sy;
  101504. tz = ez - sz;
  101505. td = ed - sd;
  101506. }
  101507. dotw = d1x * dir2x + d1y * dir2y + d1z * dir2z;
  101508. doth = d2x * dir2x + d2y * dir2y + d2z * dir2z;
  101509. dot1 = dotw - dir2l;
  101510. dot2 = doth - dir2l;
  101511. if (dot1 > 0) {
  101512. if (dot2 > 0) return;
  101513. t1 = dot1 / (dot1 - dot2);
  101514. sx = sx + tx * t1;
  101515. sy = sy + ty * t1;
  101516. sz = sz + tz * t1;
  101517. sd = sd + td * t1;
  101518. d1x = sx - cbx;
  101519. d1y = sy - cby;
  101520. d1z = sz - cbz;
  101521. dotw = d1x * dir2x + d1y * dir2y + d1z * dir2z;
  101522. tx = ex - sx;
  101523. ty = ey - sy;
  101524. tz = ez - sz;
  101525. td = ed - sd;
  101526. } else if (dot2 > 0) {
  101527. t1 = dot1 / (dot1 - dot2);
  101528. ex = sx + tx * t1;
  101529. ey = sy + ty * t1;
  101530. ez = sz + tz * t1;
  101531. ed = sd + td * t1;
  101532. d2x = ex - cbx;
  101533. d2y = ey - cby;
  101534. d2z = ez - cbz;
  101535. doth = d2x * dir2x + d2y * dir2y + d2z * dir2z;
  101536. tx = ex - sx;
  101537. ty = ey - sy;
  101538. tz = ez - sz;
  101539. td = ed - sd;
  101540. }
  101541. dot1 = dotw + dir2l;
  101542. dot2 = doth + dir2l;
  101543. if (dot1 < 0) {
  101544. if (dot2 < 0) return;
  101545. t1 = dot1 / (dot1 - dot2);
  101546. sx = sx + tx * t1;
  101547. sy = sy + ty * t1;
  101548. sz = sz + tz * t1;
  101549. sd = sd + td * t1;
  101550. } else if (dot2 < 0) {
  101551. t1 = dot1 / (dot1 - dot2);
  101552. ex = sx + tx * t1;
  101553. ey = sy + ty * t1;
  101554. ez = sz + tz * t1;
  101555. ed = sd + td * t1;
  101556. }
  101557. if (sd < 0) {
  101558. //manifold.addPoint(sx,sy,sz,nx,ny,nz,sd,b,c,1,0,false);
  101559. manifold.addPoint(sx, sy, sz, nx, ny, nz, sd, this.flip);
  101560. }
  101561. if (ed < 0) {
  101562. //manifold.addPoint(ex,ey,ez,nx,ny,nz,ed,b,c,4,0,false);
  101563. manifold.addPoint(ex, ey, ez, nx, ny, nz, ed, this.flip);
  101564. }
  101565. }
  101566. }
  101567. };
  101568. OIMO.CylinderCylinderCollisionDetector = function () {
  101569. OIMO.CollisionDetector.call(this);
  101570. };
  101571. OIMO.CylinderCylinderCollisionDetector.prototype = Object.create(OIMO.CollisionDetector.prototype);
  101572. OIMO.CylinderCylinderCollisionDetector.prototype.constructor = OIMO.CylinderCylinderCollisionDetector;
  101573. OIMO.CylinderCylinderCollisionDetector.prototype.getSep = function (c1, c2, sep, pos, dep) {
  101574. var t1x;
  101575. var t1y;
  101576. var t1z;
  101577. var t2x;
  101578. var t2y;
  101579. var t2z;
  101580. var sup = new OIMO.Vec3();
  101581. var len;
  101582. var p1x;
  101583. var p1y;
  101584. var p1z;
  101585. var p2x;
  101586. var p2y;
  101587. var p2z;
  101588. var v01x = c1.position.x;
  101589. var v01y = c1.position.y;
  101590. var v01z = c1.position.z;
  101591. var v02x = c2.position.x;
  101592. var v02y = c2.position.y;
  101593. var v02z = c2.position.z;
  101594. var v0x = v02x - v01x;
  101595. var v0y = v02y - v01y;
  101596. var v0z = v02z - v01z;
  101597. if (v0x * v0x + v0y * v0y + v0z * v0z == 0) v0y = 0.001;
  101598. var nx = -v0x;
  101599. var ny = -v0y;
  101600. var nz = -v0z;
  101601. this.supportPoint(c1, -nx, -ny, -nz, sup);
  101602. var v11x = sup.x;
  101603. var v11y = sup.y;
  101604. var v11z = sup.z;
  101605. this.supportPoint(c2, nx, ny, nz, sup);
  101606. var v12x = sup.x;
  101607. var v12y = sup.y;
  101608. var v12z = sup.z;
  101609. var v1x = v12x - v11x;
  101610. var v1y = v12y - v11y;
  101611. var v1z = v12z - v11z;
  101612. if (v1x * nx + v1y * ny + v1z * nz <= 0) {
  101613. return false;
  101614. }
  101615. nx = v1y * v0z - v1z * v0y;
  101616. ny = v1z * v0x - v1x * v0z;
  101617. nz = v1x * v0y - v1y * v0x;
  101618. if (nx * nx + ny * ny + nz * nz == 0) {
  101619. sep.init(v1x - v0x, v1y - v0y, v1z - v0z);
  101620. sep.normalize(sep);
  101621. pos.init((v11x + v12x) * 0.5, (v11y + v12y) * 0.5, (v11z + v12z) * 0.5);
  101622. return true;
  101623. }
  101624. this.supportPoint(c1, -nx, -ny, -nz, sup);
  101625. var v21x = sup.x;
  101626. var v21y = sup.y;
  101627. var v21z = sup.z;
  101628. this.supportPoint(c2, nx, ny, nz, sup);
  101629. var v22x = sup.x;
  101630. var v22y = sup.y;
  101631. var v22z = sup.z;
  101632. var v2x = v22x - v21x;
  101633. var v2y = v22y - v21y;
  101634. var v2z = v22z - v21z;
  101635. if (v2x * nx + v2y * ny + v2z * nz <= 0) {
  101636. return false;
  101637. }
  101638. t1x = v1x - v0x;
  101639. t1y = v1y - v0y;
  101640. t1z = v1z - v0z;
  101641. t2x = v2x - v0x;
  101642. t2y = v2y - v0y;
  101643. t2z = v2z - v0z;
  101644. nx = t1y * t2z - t1z * t2y;
  101645. ny = t1z * t2x - t1x * t2z;
  101646. nz = t1x * t2y - t1y * t2x;
  101647. if (nx * v0x + ny * v0y + nz * v0z > 0) {
  101648. t1x = v1x;
  101649. t1y = v1y;
  101650. t1z = v1z;
  101651. v1x = v2x;
  101652. v1y = v2y;
  101653. v1z = v2z;
  101654. v2x = t1x;
  101655. v2y = t1y;
  101656. v2z = t1z;
  101657. t1x = v11x;
  101658. t1y = v11y;
  101659. t1z = v11z;
  101660. v11x = v21x;
  101661. v11y = v21y;
  101662. v11z = v21z;
  101663. v21x = t1x;
  101664. v21y = t1y;
  101665. v21z = t1z;
  101666. t1x = v12x;
  101667. t1y = v12y;
  101668. t1z = v12z;
  101669. v12x = v22x;
  101670. v12y = v22y;
  101671. v12z = v22z;
  101672. v22x = t1x;
  101673. v22y = t1y;
  101674. v22z = t1z;
  101675. nx = -nx;
  101676. ny = -ny;
  101677. nz = -nz;
  101678. }
  101679. var iterations = 0;
  101680. while (true) {
  101681. if (++iterations > 100) {
  101682. return false;
  101683. }
  101684. this.supportPoint(c1, -nx, -ny, -nz, sup);
  101685. var v31x = sup.x;
  101686. var v31y = sup.y;
  101687. var v31z = sup.z;
  101688. this.supportPoint(c2, nx, ny, nz, sup);
  101689. var v32x = sup.x;
  101690. var v32y = sup.y;
  101691. var v32z = sup.z;
  101692. var v3x = v32x - v31x;
  101693. var v3y = v32y - v31y;
  101694. var v3z = v32z - v31z;
  101695. if (v3x * nx + v3y * ny + v3z * nz <= 0) {
  101696. return false;
  101697. }
  101698. if ((v1y * v3z - v1z * v3y) * v0x + (v1z * v3x - v1x * v3z) * v0y + (v1x * v3y - v1y * v3x) * v0z < 0) {
  101699. v2x = v3x;
  101700. v2y = v3y;
  101701. v2z = v3z;
  101702. v21x = v31x;
  101703. v21y = v31y;
  101704. v21z = v31z;
  101705. v22x = v32x;
  101706. v22y = v32y;
  101707. v22z = v32z;
  101708. t1x = v1x - v0x;
  101709. t1y = v1y - v0y;
  101710. t1z = v1z - v0z;
  101711. t2x = v3x - v0x;
  101712. t2y = v3y - v0y;
  101713. t2z = v3z - v0z;
  101714. nx = t1y * t2z - t1z * t2y;
  101715. ny = t1z * t2x - t1x * t2z;
  101716. nz = t1x * t2y - t1y * t2x;
  101717. continue;
  101718. }
  101719. if ((v3y * v2z - v3z * v2y) * v0x + (v3z * v2x - v3x * v2z) * v0y + (v3x * v2y - v3y * v2x) * v0z < 0) {
  101720. v1x = v3x;
  101721. v1y = v3y;
  101722. v1z = v3z;
  101723. v11x = v31x;
  101724. v11y = v31y;
  101725. v11z = v31z;
  101726. v12x = v32x;
  101727. v12y = v32y;
  101728. v12z = v32z;
  101729. t1x = v3x - v0x;
  101730. t1y = v3y - v0y;
  101731. t1z = v3z - v0z;
  101732. t2x = v2x - v0x;
  101733. t2y = v2y - v0y;
  101734. t2z = v2z - v0z;
  101735. nx = t1y * t2z - t1z * t2y;
  101736. ny = t1z * t2x - t1x * t2z;
  101737. nz = t1x * t2y - t1y * t2x;
  101738. continue;
  101739. }
  101740. var hit = false;
  101741. while (true) {
  101742. t1x = v2x - v1x;
  101743. t1y = v2y - v1y;
  101744. t1z = v2z - v1z;
  101745. t2x = v3x - v1x;
  101746. t2y = v3y - v1y;
  101747. t2z = v3z - v1z;
  101748. nx = t1y * t2z - t1z * t2y;
  101749. ny = t1z * t2x - t1x * t2z;
  101750. nz = t1x * t2y - t1y * t2x;
  101751. len = 1 / OIMO.sqrt(nx * nx + ny * ny + nz * nz);
  101752. nx *= len;
  101753. ny *= len;
  101754. nz *= len;
  101755. if (nx * v1x + ny * v1y + nz * v1z >= 0 && !hit) {
  101756. var b0 = (v1y * v2z - v1z * v2y) * v3x + (v1z * v2x - v1x * v2z) * v3y + (v1x * v2y - v1y * v2x) * v3z;
  101757. var b1 = (v3y * v2z - v3z * v2y) * v0x + (v3z * v2x - v3x * v2z) * v0y + (v3x * v2y - v3y * v2x) * v0z;
  101758. var b2 = (v0y * v1z - v0z * v1y) * v3x + (v0z * v1x - v0x * v1z) * v3y + (v0x * v1y - v0y * v1x) * v3z;
  101759. var b3 = (v2y * v1z - v2z * v1y) * v0x + (v2z * v1x - v2x * v1z) * v0y + (v2x * v1y - v2y * v1x) * v0z;
  101760. var sum = b0 + b1 + b2 + b3;
  101761. if (sum <= 0) {
  101762. b0 = 0;
  101763. b1 = (v2y * v3z - v2z * v3y) * nx + (v2z * v3x - v2x * v3z) * ny + (v2x * v3y - v2y * v3x) * nz;
  101764. b2 = (v3y * v2z - v3z * v2y) * nx + (v3z * v2x - v3x * v2z) * ny + (v3x * v2y - v3y * v2x) * nz;
  101765. b3 = (v1y * v2z - v1z * v2y) * nx + (v1z * v2x - v1x * v2z) * ny + (v1x * v2y - v1y * v2x) * nz;
  101766. sum = b1 + b2 + b3;
  101767. }
  101768. var inv = 1 / sum;
  101769. p1x = (v01x * b0 + v11x * b1 + v21x * b2 + v31x * b3) * inv;
  101770. p1y = (v01y * b0 + v11y * b1 + v21y * b2 + v31y * b3) * inv;
  101771. p1z = (v01z * b0 + v11z * b1 + v21z * b2 + v31z * b3) * inv;
  101772. p2x = (v02x * b0 + v12x * b1 + v22x * b2 + v32x * b3) * inv;
  101773. p2y = (v02y * b0 + v12y * b1 + v22y * b2 + v32y * b3) * inv;
  101774. p2z = (v02z * b0 + v12z * b1 + v22z * b2 + v32z * b3) * inv;
  101775. hit = true;
  101776. }
  101777. this.supportPoint(c1, -nx, -ny, -nz, sup);
  101778. var v41x = sup.x;
  101779. var v41y = sup.y;
  101780. var v41z = sup.z;
  101781. this.supportPoint(c2, nx, ny, nz, sup);
  101782. var v42x = sup.x;
  101783. var v42y = sup.y;
  101784. var v42z = sup.z;
  101785. var v4x = v42x - v41x;
  101786. var v4y = v42y - v41y;
  101787. var v4z = v42z - v41z;
  101788. var separation = -(v4x * nx + v4y * ny + v4z * nz);
  101789. if ((v4x - v3x) * nx + (v4y - v3y) * ny + (v4z - v3z) * nz <= 0.01 || separation >= 0) {
  101790. if (hit) {
  101791. sep.init(-nx, -ny, -nz);
  101792. pos.init((p1x + p2x) * 0.5, (p1y + p2y) * 0.5, (p1z + p2z) * 0.5);
  101793. dep.x = separation;
  101794. return true;
  101795. }
  101796. return false;
  101797. }
  101798. if (
  101799. (v4y * v1z - v4z * v1y) * v0x +
  101800. (v4z * v1x - v4x * v1z) * v0y +
  101801. (v4x * v1y - v4y * v1x) * v0z < 0
  101802. ) {
  101803. if (
  101804. (v4y * v2z - v4z * v2y) * v0x +
  101805. (v4z * v2x - v4x * v2z) * v0y +
  101806. (v4x * v2y - v4y * v2x) * v0z < 0
  101807. ) {
  101808. v1x = v4x;
  101809. v1y = v4y;
  101810. v1z = v4z;
  101811. v11x = v41x;
  101812. v11y = v41y;
  101813. v11z = v41z;
  101814. v12x = v42x;
  101815. v12y = v42y;
  101816. v12z = v42z;
  101817. } else {
  101818. v3x = v4x;
  101819. v3y = v4y;
  101820. v3z = v4z;
  101821. v31x = v41x;
  101822. v31y = v41y;
  101823. v31z = v41z;
  101824. v32x = v42x;
  101825. v32y = v42y;
  101826. v32z = v42z;
  101827. }
  101828. } else {
  101829. if (
  101830. (v4y * v3z - v4z * v3y) * v0x +
  101831. (v4z * v3x - v4x * v3z) * v0y +
  101832. (v4x * v3y - v4y * v3x) * v0z < 0
  101833. ) {
  101834. v2x = v4x;
  101835. v2y = v4y;
  101836. v2z = v4z;
  101837. v21x = v41x;
  101838. v21y = v41y;
  101839. v21z = v41z;
  101840. v22x = v42x;
  101841. v22y = v42y;
  101842. v22z = v42z;
  101843. } else {
  101844. v1x = v4x;
  101845. v1y = v4y;
  101846. v1z = v4z;
  101847. v11x = v41x;
  101848. v11y = v41y;
  101849. v11z = v41z;
  101850. v12x = v42x;
  101851. v12y = v42y;
  101852. v12z = v42z;
  101853. }
  101854. }
  101855. }
  101856. }
  101857. //return false;
  101858. };
  101859. OIMO.CylinderCylinderCollisionDetector.prototype.supportPoint = function (c, dx, dy, dz, out) {
  101860. var rot = c.rotation.elements;
  101861. var ldx = rot[0] * dx + rot[3] * dy + rot[6] * dz;
  101862. var ldy = rot[1] * dx + rot[4] * dy + rot[7] * dz;
  101863. var ldz = rot[2] * dx + rot[5] * dy + rot[8] * dz;
  101864. var radx = ldx;
  101865. var radz = ldz;
  101866. var len = radx * radx + radz * radz;
  101867. var rad = c.radius;
  101868. var hh = c.halfHeight;
  101869. var ox;
  101870. var oy;
  101871. var oz;
  101872. if (len == 0) {
  101873. if (ldy < 0) {
  101874. ox = rad;
  101875. oy = -hh;
  101876. oz = 0;
  101877. } else {
  101878. ox = rad;
  101879. oy = hh;
  101880. oz = 0;
  101881. }
  101882. } else {
  101883. len = c.radius / OIMO.sqrt(len);
  101884. if (ldy < 0) {
  101885. ox = radx * len;
  101886. oy = -hh;
  101887. oz = radz * len;
  101888. } else {
  101889. ox = radx * len;
  101890. oy = hh;
  101891. oz = radz * len;
  101892. }
  101893. }
  101894. ldx = rot[0] * ox + rot[1] * oy + rot[2] * oz + c.position.x;
  101895. ldy = rot[3] * ox + rot[4] * oy + rot[5] * oz + c.position.y;
  101896. ldz = rot[6] * ox + rot[7] * oy + rot[8] * oz + c.position.z;
  101897. out.init(ldx, ldy, ldz);
  101898. };
  101899. OIMO.CylinderCylinderCollisionDetector.prototype.detectCollision = function (shape1, shape2, manifold) {
  101900. var c1;
  101901. var c2;
  101902. if (shape1.id < shape2.id) {
  101903. c1 = shape1;
  101904. c2 = shape2;
  101905. } else {
  101906. c1 = shape2;
  101907. c2 = shape1;
  101908. }
  101909. var p1 = c1.position;
  101910. var p2 = c2.position;
  101911. var p1x = p1.x;
  101912. var p1y = p1.y;
  101913. var p1z = p1.z;
  101914. var p2x = p2.x;
  101915. var p2y = p2.y;
  101916. var p2z = p2.z;
  101917. var h1 = c1.halfHeight;
  101918. var h2 = c2.halfHeight;
  101919. var n1 = c1.normalDirection;
  101920. var n2 = c2.normalDirection;
  101921. var d1 = c1.halfDirection;
  101922. var d2 = c2.halfDirection;
  101923. var r1 = c1.radius;
  101924. var r2 = c2.radius;
  101925. var n1x = n1.x;
  101926. var n1y = n1.y;
  101927. var n1z = n1.z;
  101928. var n2x = n2.x;
  101929. var n2y = n2.y;
  101930. var n2z = n2.z;
  101931. var d1x = d1.x;
  101932. var d1y = d1.y;
  101933. var d1z = d1.z;
  101934. var d2x = d2.x;
  101935. var d2y = d2.y;
  101936. var d2z = d2.z;
  101937. var dx = p1x - p2x;
  101938. var dy = p1y - p2y;
  101939. var dz = p1z - p2z;
  101940. var len;
  101941. var len1;
  101942. var len2;
  101943. var c;
  101944. var c1x;
  101945. var c1y;
  101946. var c1z;
  101947. var c2x;
  101948. var c2y;
  101949. var c2z;
  101950. var tx;
  101951. var ty;
  101952. var tz;
  101953. var sx;
  101954. var sy;
  101955. var sz;
  101956. var ex;
  101957. var ey;
  101958. var ez;
  101959. var depth1;
  101960. var depth2;
  101961. var dot;
  101962. var t1;
  101963. var t2;
  101964. var sep = new OIMO.Vec3();
  101965. var pos = new OIMO.Vec3();
  101966. var dep = new OIMO.Vec3();
  101967. if (!this.getSep(c1, c2, sep, pos, dep)) return;
  101968. var dot1 = sep.x * n1x + sep.y * n1y + sep.z * n1z;
  101969. var dot2 = sep.x * n2x + sep.y * n2y + sep.z * n2z;
  101970. var right1 = dot1 > 0;
  101971. var right2 = dot2 > 0;
  101972. if (!right1) dot1 = -dot1;
  101973. if (!right2) dot2 = -dot2;
  101974. var state = 0;
  101975. if (dot1 > 0.999 || dot2 > 0.999) {
  101976. if (dot1 > dot2) state = 1;
  101977. else state = 2;
  101978. }
  101979. var nx;
  101980. var ny;
  101981. var nz;
  101982. var depth = dep.x;
  101983. var r00;
  101984. var r01;
  101985. var r02;
  101986. var r10;
  101987. var r11;
  101988. var r12;
  101989. var r20;
  101990. var r21;
  101991. var r22;
  101992. var px;
  101993. var py;
  101994. var pz;
  101995. var pd;
  101996. var a;
  101997. var b;
  101998. var e;
  101999. var f;
  102000. nx = sep.x;
  102001. ny = sep.y;
  102002. nz = sep.z;
  102003. switch (state) {
  102004. case 0:
  102005. manifold.addPoint(pos.x, pos.y, pos.z, nx, ny, nz, depth, false);
  102006. break;
  102007. case 1:
  102008. if (right1) {
  102009. c1x = p1x + d1x;
  102010. c1y = p1y + d1y;
  102011. c1z = p1z + d1z;
  102012. nx = n1x;
  102013. ny = n1y;
  102014. nz = n1z;
  102015. } else {
  102016. c1x = p1x - d1x;
  102017. c1y = p1y - d1y;
  102018. c1z = p1z - d1z;
  102019. nx = -n1x;
  102020. ny = -n1y;
  102021. nz = -n1z;
  102022. }
  102023. dot = nx * n2x + ny * n2y + nz * n2z;
  102024. if (dot < 0) len = h2;
  102025. else len = -h2;
  102026. c2x = p2x + len * n2x;
  102027. c2y = p2y + len * n2y;
  102028. c2z = p2z + len * n2z;
  102029. if (dot2 >= 0.999999) {
  102030. tx = -ny;
  102031. ty = nz;
  102032. tz = nx;
  102033. } else {
  102034. tx = nx;
  102035. ty = ny;
  102036. tz = nz;
  102037. }
  102038. len = tx * n2x + ty * n2y + tz * n2z;
  102039. dx = len * n2x - tx;
  102040. dy = len * n2y - ty;
  102041. dz = len * n2z - tz;
  102042. len = OIMO.sqrt(dx * dx + dy * dy + dz * dz);
  102043. if (len == 0) break;
  102044. len = r2 / len;
  102045. dx *= len;
  102046. dy *= len;
  102047. dz *= len;
  102048. tx = c2x + dx;
  102049. ty = c2y + dy;
  102050. tz = c2z + dz;
  102051. if (dot < -0.96 || dot > 0.96) {
  102052. r00 = n2x * n2x * 1.5 - 0.5;
  102053. r01 = n2x * n2y * 1.5 - n2z * 0.866025403;
  102054. r02 = n2x * n2z * 1.5 + n2y * 0.866025403;
  102055. r10 = n2y * n2x * 1.5 + n2z * 0.866025403;
  102056. r11 = n2y * n2y * 1.5 - 0.5;
  102057. r12 = n2y * n2z * 1.5 - n2x * 0.866025403;
  102058. r20 = n2z * n2x * 1.5 - n2y * 0.866025403;
  102059. r21 = n2z * n2y * 1.5 + n2x * 0.866025403;
  102060. r22 = n2z * n2z * 1.5 - 0.5;
  102061. px = tx;
  102062. py = ty;
  102063. pz = tz;
  102064. pd = nx * (px - c1x) + ny * (py - c1y) + nz * (pz - c1z);
  102065. tx = px - pd * nx - c1x;
  102066. ty = py - pd * ny - c1y;
  102067. tz = pz - pd * nz - c1z;
  102068. len = tx * tx + ty * ty + tz * tz;
  102069. if (len > r1 * r1) {
  102070. len = r1 / OIMO.sqrt(len);
  102071. tx *= len;
  102072. ty *= len;
  102073. tz *= len;
  102074. }
  102075. px = c1x + tx;
  102076. py = c1y + ty;
  102077. pz = c1z + tz;
  102078. manifold.addPoint(px, py, pz, nx, ny, nz, pd, false);
  102079. px = dx * r00 + dy * r01 + dz * r02;
  102080. py = dx * r10 + dy * r11 + dz * r12;
  102081. pz = dx * r20 + dy * r21 + dz * r22;
  102082. px = (dx = px) + c2x;
  102083. py = (dy = py) + c2y;
  102084. pz = (dz = pz) + c2z;
  102085. pd = nx * (px - c1x) + ny * (py - c1y) + nz * (pz - c1z);
  102086. if (pd <= 0) {
  102087. tx = px - pd * nx - c1x;
  102088. ty = py - pd * ny - c1y;
  102089. tz = pz - pd * nz - c1z;
  102090. len = tx * tx + ty * ty + tz * tz;
  102091. if (len > r1 * r1) {
  102092. len = r1 / OIMO.sqrt(len);
  102093. tx *= len;
  102094. ty *= len;
  102095. tz *= len;
  102096. }
  102097. px = c1x + tx;
  102098. py = c1y + ty;
  102099. pz = c1z + tz;
  102100. manifold.addPoint(px, py, pz, nx, ny, nz, pd, false);
  102101. }
  102102. px = dx * r00 + dy * r01 + dz * r02;
  102103. py = dx * r10 + dy * r11 + dz * r12;
  102104. pz = dx * r20 + dy * r21 + dz * r22;
  102105. px = (dx = px) + c2x;
  102106. py = (dy = py) + c2y;
  102107. pz = (dz = pz) + c2z;
  102108. pd = nx * (px - c1x) + ny * (py - c1y) + nz * (pz - c1z);
  102109. if (pd <= 0) {
  102110. tx = px - pd * nx - c1x;
  102111. ty = py - pd * ny - c1y;
  102112. tz = pz - pd * nz - c1z;
  102113. len = tx * tx + ty * ty + tz * tz;
  102114. if (len > r1 * r1) {
  102115. len = r1 / OIMO.sqrt(len);
  102116. tx *= len;
  102117. ty *= len;
  102118. tz *= len;
  102119. }
  102120. px = c1x + tx;
  102121. py = c1y + ty;
  102122. pz = c1z + tz;
  102123. manifold.addPoint(px, py, pz, nx, ny, nz, pd, false);
  102124. }
  102125. } else {
  102126. sx = tx;
  102127. sy = ty;
  102128. sz = tz;
  102129. depth1 = nx * (sx - c1x) + ny * (sy - c1y) + nz * (sz - c1z);
  102130. sx -= depth1 * nx;
  102131. sy -= depth1 * ny;
  102132. sz -= depth1 * nz;
  102133. if (dot > 0) {
  102134. ex = tx + n2x * h2 * 2;
  102135. ey = ty + n2y * h2 * 2;
  102136. ez = tz + n2z * h2 * 2;
  102137. } else {
  102138. ex = tx - n2x * h2 * 2;
  102139. ey = ty - n2y * h2 * 2;
  102140. ez = tz - n2z * h2 * 2;
  102141. }
  102142. depth2 = nx * (ex - c1x) + ny * (ey - c1y) + nz * (ez - c1z);
  102143. ex -= depth2 * nx;
  102144. ey -= depth2 * ny;
  102145. ez -= depth2 * nz;
  102146. dx = c1x - sx;
  102147. dy = c1y - sy;
  102148. dz = c1z - sz;
  102149. tx = ex - sx;
  102150. ty = ey - sy;
  102151. tz = ez - sz;
  102152. a = dx * dx + dy * dy + dz * dz;
  102153. b = dx * tx + dy * ty + dz * tz;
  102154. e = tx * tx + ty * ty + tz * tz;
  102155. f = b * b - e * (a - r1 * r1);
  102156. if (f < 0) break;
  102157. f = OIMO.sqrt(f);
  102158. t1 = (b + f) / e;
  102159. t2 = (b - f) / e;
  102160. if (t2 < t1) {
  102161. len = t1;
  102162. t1 = t2;
  102163. t2 = len;
  102164. }
  102165. if (t2 > 1) t2 = 1;
  102166. if (t1 < 0) t1 = 0;
  102167. tx = sx + (ex - sx) * t1;
  102168. ty = sy + (ey - sy) * t1;
  102169. tz = sz + (ez - sz) * t1;
  102170. ex = sx + (ex - sx) * t2;
  102171. ey = sy + (ey - sy) * t2;
  102172. ez = sz + (ez - sz) * t2;
  102173. sx = tx;
  102174. sy = ty;
  102175. sz = tz;
  102176. len = depth1 + (depth2 - depth1) * t1;
  102177. depth2 = depth1 + (depth2 - depth1) * t2;
  102178. depth1 = len;
  102179. if (depth1 < 0) manifold.addPoint(sx, sy, sz, nx, ny, nz, pd, false);
  102180. if (depth2 < 0) manifold.addPoint(ex, ey, ez, nx, ny, nz, pd, false);
  102181. }
  102182. break;
  102183. case 2:
  102184. if (right2) {
  102185. c2x = p2x - d2x;
  102186. c2y = p2y - d2y;
  102187. c2z = p2z - d2z;
  102188. nx = -n2x;
  102189. ny = -n2y;
  102190. nz = -n2z;
  102191. } else {
  102192. c2x = p2x + d2x;
  102193. c2y = p2y + d2y;
  102194. c2z = p2z + d2z;
  102195. nx = n2x;
  102196. ny = n2y;
  102197. nz = n2z;
  102198. }
  102199. dot = nx * n1x + ny * n1y + nz * n1z;
  102200. if (dot < 0) len = h1;
  102201. else len = -h1;
  102202. c1x = p1x + len * n1x;
  102203. c1y = p1y + len * n1y;
  102204. c1z = p1z + len * n1z;
  102205. if (dot1 >= 0.999999) {
  102206. tx = -ny;
  102207. ty = nz;
  102208. tz = nx;
  102209. } else {
  102210. tx = nx;
  102211. ty = ny;
  102212. tz = nz;
  102213. }
  102214. len = tx * n1x + ty * n1y + tz * n1z;
  102215. dx = len * n1x - tx;
  102216. dy = len * n1y - ty;
  102217. dz = len * n1z - tz;
  102218. len = OIMO.sqrt(dx * dx + dy * dy + dz * dz);
  102219. if (len == 0) break;
  102220. len = r1 / len;
  102221. dx *= len;
  102222. dy *= len;
  102223. dz *= len;
  102224. tx = c1x + dx;
  102225. ty = c1y + dy;
  102226. tz = c1z + dz;
  102227. if (dot < -0.96 || dot > 0.96) {
  102228. r00 = n1x * n1x * 1.5 - 0.5;
  102229. r01 = n1x * n1y * 1.5 - n1z * 0.866025403;
  102230. r02 = n1x * n1z * 1.5 + n1y * 0.866025403;
  102231. r10 = n1y * n1x * 1.5 + n1z * 0.866025403;
  102232. r11 = n1y * n1y * 1.5 - 0.5;
  102233. r12 = n1y * n1z * 1.5 - n1x * 0.866025403;
  102234. r20 = n1z * n1x * 1.5 - n1y * 0.866025403;
  102235. r21 = n1z * n1y * 1.5 + n1x * 0.866025403;
  102236. r22 = n1z * n1z * 1.5 - 0.5;
  102237. px = tx;
  102238. py = ty;
  102239. pz = tz;
  102240. pd = nx * (px - c2x) + ny * (py - c2y) + nz * (pz - c2z);
  102241. tx = px - pd * nx - c2x;
  102242. ty = py - pd * ny - c2y;
  102243. tz = pz - pd * nz - c2z;
  102244. len = tx * tx + ty * ty + tz * tz;
  102245. if (len > r2 * r2) {
  102246. len = r2 / OIMO.sqrt(len);
  102247. tx *= len;
  102248. ty *= len;
  102249. tz *= len;
  102250. }
  102251. px = c2x + tx;
  102252. py = c2y + ty;
  102253. pz = c2z + tz;
  102254. manifold.addPoint(px, py, pz, -nx, -ny, -nz, pd, false);
  102255. px = dx * r00 + dy * r01 + dz * r02;
  102256. py = dx * r10 + dy * r11 + dz * r12;
  102257. pz = dx * r20 + dy * r21 + dz * r22;
  102258. px = (dx = px) + c1x;
  102259. py = (dy = py) + c1y;
  102260. pz = (dz = pz) + c1z;
  102261. pd = nx * (px - c2x) + ny * (py - c2y) + nz * (pz - c2z);
  102262. if (pd <= 0) {
  102263. tx = px - pd * nx - c2x;
  102264. ty = py - pd * ny - c2y;
  102265. tz = pz - pd * nz - c2z;
  102266. len = tx * tx + ty * ty + tz * tz;
  102267. if (len > r2 * r2) {
  102268. len = r2 / OIMO.sqrt(len);
  102269. tx *= len;
  102270. ty *= len;
  102271. tz *= len;
  102272. }
  102273. px = c2x + tx;
  102274. py = c2y + ty;
  102275. pz = c2z + tz;
  102276. manifold.addPoint(px, py, pz, -nx, -ny, -nz, pd, false);
  102277. }
  102278. px = dx * r00 + dy * r01 + dz * r02;
  102279. py = dx * r10 + dy * r11 + dz * r12;
  102280. pz = dx * r20 + dy * r21 + dz * r22;
  102281. px = (dx = px) + c1x;
  102282. py = (dy = py) + c1y;
  102283. pz = (dz = pz) + c1z;
  102284. pd = nx * (px - c2x) + ny * (py - c2y) + nz * (pz - c2z);
  102285. if (pd <= 0) {
  102286. tx = px - pd * nx - c2x;
  102287. ty = py - pd * ny - c2y;
  102288. tz = pz - pd * nz - c2z;
  102289. len = tx * tx + ty * ty + tz * tz;
  102290. if (len > r2 * r2) {
  102291. len = r2 / OIMO.sqrt(len);
  102292. tx *= len;
  102293. ty *= len;
  102294. tz *= len;
  102295. }
  102296. px = c2x + tx;
  102297. py = c2y + ty;
  102298. pz = c2z + tz;
  102299. manifold.addPoint(px, py, pz, -nx, -ny, -nz, pd, false);
  102300. }
  102301. } else {
  102302. sx = tx;
  102303. sy = ty;
  102304. sz = tz;
  102305. depth1 = nx * (sx - c2x) + ny * (sy - c2y) + nz * (sz - c2z);
  102306. sx -= depth1 * nx;
  102307. sy -= depth1 * ny;
  102308. sz -= depth1 * nz;
  102309. if (dot > 0) {
  102310. ex = tx + n1x * h1 * 2;
  102311. ey = ty + n1y * h1 * 2;
  102312. ez = tz + n1z * h1 * 2;
  102313. } else {
  102314. ex = tx - n1x * h1 * 2;
  102315. ey = ty - n1y * h1 * 2;
  102316. ez = tz - n1z * h1 * 2;
  102317. }
  102318. depth2 = nx * (ex - c2x) + ny * (ey - c2y) + nz * (ez - c2z);
  102319. ex -= depth2 * nx;
  102320. ey -= depth2 * ny;
  102321. ez -= depth2 * nz;
  102322. dx = c2x - sx;
  102323. dy = c2y - sy;
  102324. dz = c2z - sz;
  102325. tx = ex - sx;
  102326. ty = ey - sy;
  102327. tz = ez - sz;
  102328. a = dx * dx + dy * dy + dz * dz;
  102329. b = dx * tx + dy * ty + dz * tz;
  102330. e = tx * tx + ty * ty + tz * tz;
  102331. f = b * b - e * (a - r2 * r2);
  102332. if (f < 0) break;
  102333. f = OIMO.sqrt(f);
  102334. t1 = (b + f) / e;
  102335. t2 = (b - f) / e;
  102336. if (t2 < t1) {
  102337. len = t1;
  102338. t1 = t2;
  102339. t2 = len;
  102340. }
  102341. if (t2 > 1) t2 = 1;
  102342. if (t1 < 0) t1 = 0;
  102343. tx = sx + (ex - sx) * t1;
  102344. ty = sy + (ey - sy) * t1;
  102345. tz = sz + (ez - sz) * t1;
  102346. ex = sx + (ex - sx) * t2;
  102347. ey = sy + (ey - sy) * t2;
  102348. ez = sz + (ez - sz) * t2;
  102349. sx = tx;
  102350. sy = ty;
  102351. sz = tz;
  102352. len = depth1 + (depth2 - depth1) * t1;
  102353. depth2 = depth1 + (depth2 - depth1) * t2;
  102354. depth1 = len;
  102355. if (depth1 < 0) {
  102356. manifold.addPoint(sx, sy, sz, -nx, -ny, -nz, depth1, false);
  102357. }
  102358. if (depth2 < 0) {
  102359. manifold.addPoint(ex, ey, ez, -nx, -ny, -nz, depth2, false);
  102360. }
  102361. }
  102362. break;
  102363. }
  102364. };
  102365. OIMO.SphereCylinderCollisionDetector = function (flip) {
  102366. OIMO.CollisionDetector.call(this);
  102367. this.flip = flip;
  102368. };
  102369. OIMO.SphereCylinderCollisionDetector.prototype = Object.create(OIMO.CollisionDetector.prototype);
  102370. OIMO.SphereCylinderCollisionDetector.prototype.constructor = OIMO.SphereCylinderCollisionDetector;
  102371. OIMO.SphereCylinderCollisionDetector.prototype.detectCollision = function (shape1, shape2, manifold) {
  102372. var s;
  102373. var c;
  102374. if (this.flip) {
  102375. s = shape2;
  102376. c = shape1;
  102377. } else {
  102378. s = shape1;
  102379. c = shape2;
  102380. }
  102381. var ps = s.position;
  102382. var psx = ps.x;
  102383. var psy = ps.y;
  102384. var psz = ps.z;
  102385. var pc = c.position;
  102386. var pcx = pc.x;
  102387. var pcy = pc.y;
  102388. var pcz = pc.z;
  102389. var dirx = c.normalDirection.x;
  102390. var diry = c.normalDirection.y;
  102391. var dirz = c.normalDirection.z;
  102392. var rads = s.radius;
  102393. var radc = c.radius;
  102394. var rad2 = rads + radc;
  102395. var halfh = c.halfHeight;
  102396. var dx = psx - pcx;
  102397. var dy = psy - pcy;
  102398. var dz = psz - pcz;
  102399. var dot = dx * dirx + dy * diry + dz * dirz;
  102400. if (dot < -halfh - rads || dot > halfh + rads) return;
  102401. var cx = pcx + dot * dirx;
  102402. var cy = pcy + dot * diry;
  102403. var cz = pcz + dot * dirz;
  102404. var d2x = psx - cx;
  102405. var d2y = psy - cy;
  102406. var d2z = psz - cz;
  102407. var len = d2x * d2x + d2y * d2y + d2z * d2z;
  102408. if (len > rad2 * rad2) return;
  102409. if (len > radc * radc) {
  102410. len = radc / OIMO.sqrt(len);
  102411. d2x *= len;
  102412. d2y *= len;
  102413. d2z *= len;
  102414. }
  102415. if (dot < -halfh) dot = -halfh;
  102416. else if (dot > halfh) dot = halfh;
  102417. cx = pcx + dot * dirx + d2x;
  102418. cy = pcy + dot * diry + d2y;
  102419. cz = pcz + dot * dirz + d2z;
  102420. dx = cx - psx;
  102421. dy = cy - psy;
  102422. dz = cz - psz;
  102423. len = dx * dx + dy * dy + dz * dz;
  102424. var invLen;
  102425. if (len > 0 && len < rads * rads) {
  102426. len = OIMO.sqrt(len);
  102427. invLen = 1 / len;
  102428. dx *= invLen;
  102429. dy *= invLen;
  102430. dz *= invLen;
  102431. ///result.addContactInfo(psx+dx*rads,psy+dy*rads,psz+dz*rads,dx,dy,dz,len-rads,s,c,0,0,false);
  102432. manifold.addPoint(psx + dx * rads, psy + dy * rads, psz + dz * rads, dx, dy, dz, len - rads, this.flip);
  102433. }
  102434. };
  102435. /**
  102436. * Class for checking collisions between 2 tetras,
  102437. * a shape that is made with 4 vertices and 4 faces
  102438. * arranged in triangles. With this algorigthm, soft
  102439. * body physics are possible and easier to implement.
  102440. * @author xprogram
  102441. */
  102442. OIMO.TetraTetraCollisionDetector = function () {
  102443. OIMO.CollisionDetector.call(this);
  102444. };
  102445. OIMO.TetraTetraCollisionDetector.prototype = Object.create(OIMO.CollisionDetector.prototype);
  102446. OIMO.TetraTetraCollisionDetector.prototype.constructor = OIMO.TetraTetraCollisionDetector;
  102447. OIMO.TetraTetraCollisionDetector.prototype.detectCollision = function (tet1, tet2, manifold) {
  102448. /*
  102449. * What we are doing:
  102450. * Each tetra is represented by four 3D triangles. The only
  102451. * quick way of finding if another tetra is within the other
  102452. * tetra is to see if a single vertex is within the triangles
  102453. * of the other tetra. So, for example, a tetra is represented
  102454. * by points B, C, D and E with triangles BCD, BCE, DCE and BDE.
  102455. * There is another tetra with a vertex A which was detected for
  102456. * collision by the broadphase. Now, if the point A is between ALL
  102457. * triangles of the other tetra (BCD, BCE, etc.) then the collision
  102458. * is valid and we can pass point A to the manifold. Since the only
  102459. * points on the tetra are the 4 vertices, collision detection is
  102460. * not so complex. However, it can be time-consuming because we
  102461. * need to split the 3D triangles into three 2D triangles each for
  102462. * collision detection.
  102463. */
  102464. var i, j, vec, fs1 = tet1.faces, vs1 = tet1.verts, fs2 = tet2.faces, vs2 = tet2.verts;
  102465. var j1, j2, j3, ts = 0; // Triangle vertices `j1`, `j2` and `j3`
  102466. // fs is undeclared
  102467. var fs = fs1;
  102468. for (i = 0; i < 4; i++) {
  102469. vec = vs1[i];
  102470. for (j = 0; j < 4; j++) {
  102471. j1 = vs2[fs[i].a];
  102472. j2 = vs2[fs[i].b];
  102473. j3 = vs2[fs[i].c];
  102474. if (
  102475. tricheck(pt(vec.x, vec.y), pt(j1.x, j1.y), pt(j2.x, j2.y), pt(j3.x, j3.y)) &&
  102476. tricheck(pt(vec.x, vec.z), pt(j1.x, j1.z), pt(j2.x, j2.z), pt(j3.x, j3.z)) &&
  102477. tricheck(pt(vec.z, vec.y), pt(j1.z, j1.y), pt(j2.z, j2.y), pt(j3.z, j3.y))
  102478. )
  102479. ts++;
  102480. if (ts === 4) // Only add point if it is inside all 4 triangles
  102481. manifold.addPoint(vec);
  102482. }
  102483. }
  102484. };
  102485. // Taken from: http://jsfiddle.net/PerroAZUL/zdaY8/1/
  102486. function tricheck(p, p0, p1, p2) {
  102487. var A = 0.5 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  102488. var sg = A < 0 ? -1 : 1;
  102489. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sg;
  102490. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sg;
  102491. return s > 0 && t > 0 && (s + t) < 2 * A * sg;
  102492. }
  102493. function pt(x, y) { return { x: x, y: y }; }
  102494. /**
  102495. * An axis-aligned bounding box.
  102496. * @author saharan
  102497. * @author lo-th
  102498. */
  102499. OIMO.AABB = function (minX, maxX, minY, maxY, minZ, maxZ) {
  102500. this.elements = new OIMO_ARRAY_TYPE(6);
  102501. var te = this.elements;
  102502. te[0] = minX || 0; te[1] = minY || 0; te[2] = minZ || 0;
  102503. te[3] = maxX || 0; te[4] = maxY || 0; te[5] = maxZ || 0;
  102504. };
  102505. OIMO.AABB.prototype = {
  102506. constructor: OIMO.AABB,
  102507. set: function (minX, maxX, minY, maxY, minZ, maxZ) {
  102508. var te = this.elements;
  102509. te[0] = minX; te[3] = maxX;
  102510. te[1] = minY; te[4] = maxY;
  102511. te[2] = minZ; te[5] = maxZ;
  102512. return this;
  102513. },
  102514. intersectTest: function (aabb) {
  102515. var te = this.elements;
  102516. var ue = aabb.elements;
  102517. return te[0] > ue[3] || te[1] > ue[4] || te[2] > ue[5] || te[3] < ue[0] || te[4] < ue[1] || te[5] < ue[2];
  102518. },
  102519. intersectTestTwo: function (aabb) {
  102520. var te = this.elements;
  102521. var ue = aabb.elements;
  102522. return te[0] < ue[0] || te[1] < ue[1] || te[2] < ue[2] || te[3] > ue[3] || te[4] > ue[4] || te[5] > ue[5];
  102523. },
  102524. clone: function () {
  102525. return new this.constructor().fromArray(this.elements);
  102526. },
  102527. copy: function (aabb, margin) {
  102528. var m = margin || 0;
  102529. var me = aabb.elements;
  102530. this.set(me[0] - m, me[3] + m, me[1] - m, me[4] + m, me[2] - m, me[5] + m);
  102531. return this;
  102532. },
  102533. fromArray: function (array) {
  102534. this.elements.set(array);
  102535. return this;
  102536. },
  102537. // Set this AABB to the combined AABB of aabb1 and aabb2.
  102538. combine: function (aabb1, aabb2) {
  102539. var a = aabb1.elements;
  102540. var b = aabb2.elements;
  102541. var te = this.elements;
  102542. te[0] = a[0] < b[0] ? a[0] : b[0];
  102543. te[1] = a[1] < b[1] ? a[1] : b[1];
  102544. te[2] = a[2] < b[2] ? a[2] : b[2];
  102545. te[3] = a[3] > b[3] ? a[3] : b[3];
  102546. te[4] = a[4] > b[4] ? a[4] : b[4];
  102547. te[5] = a[5] > b[5] ? a[5] : b[5];
  102548. return this;
  102549. },
  102550. // Get the surface area.
  102551. surfaceArea: function () {
  102552. var te = this.elements;
  102553. var a = te[3] - te[0];
  102554. var h = te[4] - te[1];
  102555. var d = te[5] - te[2];
  102556. return 2 * (a * (h + d) + h * d);
  102557. },
  102558. // Get whether the AABB intersects with the point or not.
  102559. intersectsWithPoint: function (x, y, z) {
  102560. var te = this.elements;
  102561. return x >= te[0] && x <= te[3] && y >= te[1] && y <= te[4] && z >= te[2] && z <= te[5];
  102562. },
  102563. /**
  102564. * Set the AABB from an array
  102565. * of vertices. From THREE.
  102566. * @author mrdoob
  102567. * @author xprogram
  102568. */
  102569. setFromPoints: function (arr) {
  102570. this.makeEmpty();
  102571. for (var i = 0; i < arr.length; i++) {
  102572. this.expandByPoint(arr[i]);
  102573. }
  102574. },
  102575. makeEmpty: function () {
  102576. this.set(-Infinity, -Infinity, -Infinity, Infinity, Infinity, Infinity);
  102577. },
  102578. expandByPoint: function (pt) {
  102579. var te = this.elements;
  102580. this.set(
  102581. OIMO.min(te[0], pt.x), OIMO.min(te[1], pt.y), OIMO.min(te[2], pt.z),
  102582. OIMO.max(te[3], pt.x), OIMO.max(te[4], pt.y), OIMO.max(te[5], pt.z)
  102583. );
  102584. }
  102585. };
  102586. /**
  102587. * A proxy is used for broad-phase collecting pairs that can be colliding.
  102588. */
  102589. OIMO.Proxy = function (shape) {
  102590. // The parent shape.
  102591. this.shape = shape;
  102592. // The axis-aligned bounding box.
  102593. this.aabb = shape.aabb;
  102594. };
  102595. OIMO.Proxy.prototype = {
  102596. constructor: OIMO.Proxy,
  102597. // Update the proxy.
  102598. update: function () {
  102599. OIMO.Error("Proxy", "Inheritance error.");
  102600. }
  102601. };
  102602. /**
  102603. * A basic implementation of proxies.
  102604. * @author saharan
  102605. */
  102606. OIMO.BasicProxy = function (shape) {
  102607. OIMO.Proxy.call(this, shape);
  102608. this.id = OIMO.proxyID++;
  102609. };
  102610. OIMO.BasicProxy.prototype = Object.create(OIMO.Proxy.prototype);
  102611. OIMO.BasicProxy.prototype.constructor = OIMO.BasicProxy;
  102612. OIMO.BasicProxy.prototype.update = function () {
  102613. };
  102614. /**
  102615. * The broad-phase is used for collecting all possible pairs for collision.
  102616. */
  102617. OIMO.BroadPhase = function () {
  102618. this.types = OIMO.BR_NULL;
  102619. this.numPairChecks = 0;
  102620. this.numPairs = 0;
  102621. this.pairs = [];
  102622. };
  102623. OIMO.BroadPhase.prototype = {
  102624. constructor: OIMO.BroadPhase,
  102625. /**
  102626. * Create a new proxy.
  102627. * @param shape
  102628. * @return
  102629. */
  102630. createProxy: function (shape) {
  102631. OIMO.Error("BroadPhase", "Inheritance error.");
  102632. },
  102633. /**
  102634. * Add the proxy into the broad-phase.
  102635. * @param proxy
  102636. */
  102637. addProxy: function (proxy) {
  102638. OIMO.Error("BroadPhase", "Inheritance error.");
  102639. },
  102640. /**
  102641. * Remove the proxy from the broad-phase.
  102642. * @param proxy
  102643. */
  102644. removeProxy: function (proxy) {
  102645. OIMO.Error("BroadPhase", "Inheritance error.");
  102646. },
  102647. /**
  102648. * Returns whether the pair is available or not.
  102649. * @param s1
  102650. * @param s2
  102651. * @return
  102652. */
  102653. isAvailablePair: function (s1, s2) {
  102654. var b1 = s1.parent;
  102655. var b2 = s2.parent;
  102656. if (b1 == b2 || // same parents
  102657. (!b1.isDynamic && !b2.isDynamic) || // static or kinematic object
  102658. (s1.belongsTo & s2.collidesWith) == 0 ||
  102659. (s2.belongsTo & s1.collidesWith) == 0 // collision filtering
  102660. ) { return false; }
  102661. var js;
  102662. if (b1.numJoints < b2.numJoints) js = b1.jointLink;
  102663. else js = b2.jointLink;
  102664. while (js !== null) {
  102665. var joint = js.joint;
  102666. if (!joint.allowCollision && ((joint.body1 == b1 && joint.body2 == b2) || (joint.body1 == b2 && joint.body2 == b1))) { return false; }
  102667. js = js.next;
  102668. }
  102669. return true;
  102670. },
  102671. // Detect overlapping pairs.
  102672. detectPairs: function () {
  102673. // clear old
  102674. this.pairs = [];
  102675. this.numPairs = 0;
  102676. this.numPairChecks = 0;
  102677. this.collectPairs();
  102678. },
  102679. collectPairs: function () {
  102680. OIMO.Error("BroadPhase", "Inheritance error.");
  102681. },
  102682. addPair: function (s1, s2) {
  102683. var pair = new OIMO.Pair(s1, s2);
  102684. this.pairs.push(pair);
  102685. this.numPairs++;
  102686. }
  102687. };
  102688. /**
  102689. * A broad-phase algorithm with brute-force search.
  102690. * This always checks for all possible pairs.
  102691. */
  102692. OIMO.BruteForceBroadPhase = function () {
  102693. OIMO.BroadPhase.call(this);
  102694. this.types = OIMO.BR_BRUTE_FORCE;;
  102695. //this.numProxies=0;
  102696. ///this.maxProxies = 256;
  102697. this.proxies = [];
  102698. //this.proxies.length = 256;
  102699. };
  102700. OIMO.BruteForceBroadPhase.prototype = Object.create(OIMO.BroadPhase.prototype);
  102701. OIMO.BruteForceBroadPhase.prototype.constructor = OIMO.BruteForceBroadPhase;
  102702. OIMO.BruteForceBroadPhase.prototype.createProxy = function (shape) {
  102703. return new OIMO.BasicProxy(shape);
  102704. };
  102705. OIMO.BruteForceBroadPhase.prototype.addProxy = function (proxy) {
  102706. /*if(this.numProxies==this.maxProxies){
  102707. //this.maxProxies<<=1;
  102708. this.maxProxies*=2;
  102709. var newProxies=[];
  102710. newProxies.length = this.maxProxies;
  102711. var i = this.numProxies;
  102712. while(i--){
  102713. //for(var i=0, l=this.numProxies;i<l;i++){
  102714. newProxies[i]=this.proxies[i];
  102715. }
  102716. this.proxies=newProxies;
  102717. }*/
  102718. //this.proxies[this.numProxies++] = proxy;
  102719. this.proxies.push(proxy);
  102720. //this.numProxies++;
  102721. };
  102722. OIMO.BruteForceBroadPhase.prototype.removeProxy = function (proxy) {
  102723. var n = this.proxies.indexOf(proxy);
  102724. if (n > -1) {
  102725. this.proxies.splice(n, 1);
  102726. //this.numProxies--;
  102727. }
  102728. /*var i = this.numProxies;
  102729. while(i--){
  102730. //for(var i=0, l=this.numProxies;i<l;i++){
  102731. if(this.proxies[i] == proxy){
  102732. this.proxies[i] = this.proxies[--this.numProxies];
  102733. this.proxies[this.numProxies] = null;
  102734. return;
  102735. }
  102736. }*/
  102737. };
  102738. OIMO.BruteForceBroadPhase.prototype.collectPairs = function () {
  102739. var i = 0, j, p1, p2;
  102740. var px = this.proxies;
  102741. var l = px.length;//this.numProxies;
  102742. //var ar1 = [];
  102743. //var ar2 = [];
  102744. //for( i = px.length ; i-- ; ar1[ i ] = px[ i ] ){};
  102745. //for( i = px.length ; i-- ; ar2[ i ] = px[ i ] ){};
  102746. //var ar1 = JSON.parse(JSON.stringify(this.proxies))
  102747. //var ar2 = JSON.parse(JSON.stringify(this.proxies))
  102748. this.numPairChecks = l * (l - 1) >> 1;
  102749. //this.numPairChecks=this.numProxies*(this.numProxies-1)*0.5;
  102750. while (i < l) {
  102751. p1 = px[i++];
  102752. j = i + 1;
  102753. while (j < l) {
  102754. p2 = px[j++];
  102755. if (p1.aabb.intersectTest(p2.aabb) || !this.isAvailablePair(p1.shape, p2.shape)) continue;
  102756. this.addPair(p1.shape, p2.shape);
  102757. }
  102758. }
  102759. };
  102760. /**
  102761. * A pair of shapes that may collide.
  102762. * @author saharan
  102763. */
  102764. OIMO.Pair = function (s1, s2) {
  102765. // The first shape.
  102766. this.shape1 = s1 || null;
  102767. // The second shape.
  102768. this.shape2 = s2 || null;
  102769. };
  102770. /**
  102771. * A projection axis for sweep and prune broad-phase.
  102772. * @author saharan
  102773. */
  102774. OIMO.SAPAxis = function () {
  102775. this.numElements = 0;
  102776. this.bufferSize = 256;
  102777. this.elements = [];
  102778. this.elements.length = this.bufferSize;
  102779. this.stack = new OIMO_ARRAY_TYPE(64);
  102780. };
  102781. OIMO.SAPAxis.prototype = {
  102782. constructor: OIMO.SAPAxis,
  102783. addElements: function (min, max) {
  102784. if (this.numElements + 2 >= this.bufferSize) {
  102785. //this.bufferSize<<=1;
  102786. this.bufferSize *= 2;
  102787. var newElements = [];
  102788. var i = this.numElements;
  102789. while (i--) {
  102790. //for(var i=0, l=this.numElements; i<l; i++){
  102791. newElements[i] = this.elements[i];
  102792. }
  102793. }
  102794. this.elements[this.numElements++] = min;
  102795. this.elements[this.numElements++] = max;
  102796. },
  102797. removeElements: function (min, max) {
  102798. var minIndex = -1;
  102799. var maxIndex = -1;
  102800. for (var i = 0, l = this.numElements; i < l; i++) {
  102801. var e = this.elements[i];
  102802. if (e == min || e == max) {
  102803. if (minIndex == -1) {
  102804. minIndex = i;
  102805. } else {
  102806. maxIndex = i;
  102807. break;
  102808. }
  102809. }
  102810. }
  102811. for (i = minIndex + 1, l = maxIndex; i < l; i++) {
  102812. this.elements[i - 1] = this.elements[i];
  102813. }
  102814. for (i = maxIndex + 1, l = this.numElements; i < l; i++) {
  102815. this.elements[i - 2] = this.elements[i];
  102816. }
  102817. this.elements[--this.numElements] = null;
  102818. this.elements[--this.numElements] = null;
  102819. },
  102820. sort: function () {
  102821. var count = 0;
  102822. var threshold = 1;
  102823. while ((this.numElements >> threshold) != 0) threshold++;
  102824. threshold = threshold * this.numElements >> 2;
  102825. count = 0;
  102826. var giveup = false;
  102827. var elements = this.elements;
  102828. for (var i = 1, l = this.numElements; i < l; i++) { // try insertion sort
  102829. var tmp = elements[i];
  102830. var pivot = tmp.value;
  102831. var tmp2 = elements[i - 1];
  102832. if (tmp2.value > pivot) {
  102833. var j = i;
  102834. do {
  102835. elements[j] = tmp2;
  102836. if (--j == 0) break;
  102837. tmp2 = elements[j - 1];
  102838. } while (tmp2.value > pivot);
  102839. elements[j] = tmp;
  102840. count += i - j;
  102841. if (count > threshold) {
  102842. giveup = true; // stop and use quick sort
  102843. break;
  102844. }
  102845. }
  102846. }
  102847. if (!giveup) return;
  102848. count = 2; var stack = this.stack;
  102849. stack[0] = 0;
  102850. stack[1] = this.numElements - 1;
  102851. while (count > 0) {
  102852. var right = stack[--count];
  102853. var left = stack[--count];
  102854. var diff = right - left;
  102855. if (diff > 16) { // quick sort
  102856. //var mid=left+(diff>>1);
  102857. var mid = left + (OIMO.floor(diff * 0.5));
  102858. tmp = elements[mid];
  102859. elements[mid] = elements[right];
  102860. elements[right] = tmp;
  102861. pivot = tmp.value;
  102862. i = left - 1;
  102863. j = right;
  102864. while (true) {
  102865. var ei;
  102866. var ej;
  102867. do { ei = elements[++i]; } while (ei.value < pivot);
  102868. do { ej = elements[--j]; } while (pivot < ej.value && j != left);
  102869. if (i >= j) break;
  102870. elements[i] = ej;
  102871. elements[j] = ei;
  102872. }
  102873. elements[right] = elements[i];
  102874. elements[i] = tmp;
  102875. if (i - left > right - i) {
  102876. stack[count++] = left;
  102877. stack[count++] = i - 1;
  102878. stack[count++] = i + 1;
  102879. stack[count++] = right;
  102880. } else {
  102881. stack[count++] = i + 1;
  102882. stack[count++] = right;
  102883. stack[count++] = left;
  102884. stack[count++] = i - 1;
  102885. }
  102886. } else {
  102887. for (i = left + 1; i <= right; i++) {
  102888. tmp = elements[i];
  102889. pivot = tmp.value;
  102890. tmp2 = elements[i - 1];
  102891. if (tmp2.value > pivot) {
  102892. j = i;
  102893. do {
  102894. elements[j] = tmp2;
  102895. if (--j == 0) break;
  102896. tmp2 = elements[j - 1];
  102897. } while (tmp2.value > pivot);
  102898. elements[j] = tmp;
  102899. }
  102900. }
  102901. }
  102902. }
  102903. },
  102904. calculateTestCount: function () {
  102905. var num = 1;
  102906. var sum = 0;
  102907. for (var i = 1, l = this.numElements; i < l; i++) {
  102908. if (this.elements[i].max) {
  102909. num--;
  102910. } else {
  102911. sum += num;
  102912. num++;
  102913. }
  102914. }
  102915. return sum;
  102916. }
  102917. }
  102918. /**
  102919. * A broad-phase collision detection algorithm using sweep and prune.
  102920. * @author saharan
  102921. * @author lo-th
  102922. */
  102923. OIMO.SAPBroadPhase = function () {
  102924. OIMO.BroadPhase.call(this);
  102925. this.types = OIMO.BR_SWEEP_AND_PRUNE;
  102926. this.numElementsD = 0;
  102927. this.numElementsS = 0;
  102928. // dynamic proxies
  102929. this.axesD = [
  102930. new OIMO.SAPAxis(),
  102931. new OIMO.SAPAxis(),
  102932. new OIMO.SAPAxis()
  102933. ];
  102934. // static or sleeping proxies
  102935. this.axesS = [
  102936. new OIMO.SAPAxis(),
  102937. new OIMO.SAPAxis(),
  102938. new OIMO.SAPAxis()
  102939. ];
  102940. this.index1 = 0;
  102941. this.index2 = 1;
  102942. };
  102943. OIMO.SAPBroadPhase.prototype = Object.create(OIMO.BroadPhase.prototype);
  102944. OIMO.SAPBroadPhase.prototype.constructor = OIMO.SAPBroadPhase;
  102945. OIMO.SAPBroadPhase.prototype.createProxy = function (shape) {
  102946. return new OIMO.SAPProxy(this, shape);
  102947. };
  102948. OIMO.SAPBroadPhase.prototype.addProxy = function (proxy) {
  102949. var p = proxy;
  102950. if (p.isDynamic()) {
  102951. this.axesD[0].addElements(p.min[0], p.max[0]);
  102952. this.axesD[1].addElements(p.min[1], p.max[1]);
  102953. this.axesD[2].addElements(p.min[2], p.max[2]);
  102954. p.belongsTo = 1;
  102955. this.numElementsD += 2;
  102956. } else {
  102957. this.axesS[0].addElements(p.min[0], p.max[0]);
  102958. this.axesS[1].addElements(p.min[1], p.max[1]);
  102959. this.axesS[2].addElements(p.min[2], p.max[2]);
  102960. p.belongsTo = 2;
  102961. this.numElementsS += 2;
  102962. }
  102963. };
  102964. OIMO.SAPBroadPhase.prototype.removeProxy = function (proxy) {
  102965. var p = proxy;
  102966. if (p.belongsTo == 0) return;
  102967. /*else if ( p.belongsTo == 1 ) {
  102968. this.axesD[0].removeElements( p.min[0], p.max[0] );
  102969. this.axesD[1].removeElements( p.min[1], p.max[1] );
  102970. this.axesD[2].removeElements( p.min[2], p.max[2] );
  102971. this.numElementsD -= 2;
  102972. } else if ( p.belongsTo == 2 ) {
  102973. this.axesS[0].removeElements( p.min[0], p.max[0] );
  102974. this.axesS[1].removeElements( p.min[1], p.max[1] );
  102975. this.axesS[2].removeElements( p.min[2], p.max[2] );
  102976. this.numElementsS -= 2;
  102977. }*/
  102978. switch (p.belongsTo) {
  102979. case 1:
  102980. this.axesD[0].removeElements(p.min[0], p.max[0]);
  102981. this.axesD[1].removeElements(p.min[1], p.max[1]);
  102982. this.axesD[2].removeElements(p.min[2], p.max[2]);
  102983. this.numElementsD -= 2;
  102984. break;
  102985. case 2:
  102986. this.axesS[0].removeElements(p.min[0], p.max[0]);
  102987. this.axesS[1].removeElements(p.min[1], p.max[1]);
  102988. this.axesS[2].removeElements(p.min[2], p.max[2]);
  102989. this.numElementsS -= 2;
  102990. break;
  102991. }
  102992. p.belongsTo = 0;
  102993. };
  102994. OIMO.SAPBroadPhase.prototype.collectPairs = function () {
  102995. if (this.numElementsD == 0) return;
  102996. var axis1 = this.axesD[this.index1];
  102997. var axis2 = this.axesD[this.index2];
  102998. axis1.sort();
  102999. axis2.sort();
  103000. var count1 = axis1.calculateTestCount();
  103001. var count2 = axis2.calculateTestCount();
  103002. var elementsD;
  103003. var elementsS;
  103004. if (count1 <= count2) {// select the best axis
  103005. axis2 = this.axesS[this.index1];
  103006. axis2.sort();
  103007. elementsD = axis1.elements;
  103008. elementsS = axis2.elements;
  103009. } else {
  103010. axis1 = this.axesS[this.index2];
  103011. axis1.sort();
  103012. elementsD = axis2.elements;
  103013. elementsS = axis1.elements;
  103014. this.index1 ^= this.index2;
  103015. this.index2 ^= this.index1;
  103016. this.index1 ^= this.index2;
  103017. }
  103018. var activeD;
  103019. var activeS;
  103020. var p = 0;
  103021. var q = 0;
  103022. while (p < this.numElementsD) {
  103023. var e1;
  103024. var dyn;
  103025. if (q == this.numElementsS) {
  103026. e1 = elementsD[p];
  103027. dyn = true;
  103028. p++;
  103029. } else {
  103030. var d = elementsD[p];
  103031. var s = elementsS[q];
  103032. if (d.value < s.value) {
  103033. e1 = d;
  103034. dyn = true;
  103035. p++;
  103036. } else {
  103037. e1 = s;
  103038. dyn = false;
  103039. q++;
  103040. }
  103041. }
  103042. if (!e1.max) {
  103043. var s1 = e1.proxy.shape;
  103044. var min1 = e1.min1.value;
  103045. var max1 = e1.max1.value;
  103046. var min2 = e1.min2.value;
  103047. var max2 = e1.max2.value;
  103048. for (var e2 = activeD; e2 != null; e2 = e2.pair) {// test for dynamic
  103049. var s2 = e2.proxy.shape;
  103050. this.numPairChecks++;
  103051. if (min1 > e2.max1.value || max1 < e2.min1.value || min2 > e2.max2.value || max2 < e2.min2.value || !this.isAvailablePair(s1, s2)) continue;
  103052. this.addPair(s1, s2);
  103053. }
  103054. if (dyn) {
  103055. for (e2 = activeS; e2 != null; e2 = e2.pair) {// test for static
  103056. s2 = e2.proxy.shape;
  103057. this.numPairChecks++;
  103058. if (min1 > e2.max1.value || max1 < e2.min1.value || min2 > e2.max2.value || max2 < e2.min2.value || !this.isAvailablePair(s1, s2)) continue;
  103059. this.addPair(s1, s2);
  103060. }
  103061. e1.pair = activeD;
  103062. activeD = e1;
  103063. } else {
  103064. e1.pair = activeS;
  103065. activeS = e1;
  103066. }
  103067. } else {
  103068. var min = e1.pair;
  103069. if (dyn) {
  103070. if (min == activeD) {
  103071. activeD = activeD.pair;
  103072. continue;
  103073. } else {
  103074. e1 = activeD;
  103075. }
  103076. } else {
  103077. if (min == activeS) {
  103078. activeS = activeS.pair;
  103079. continue;
  103080. } else {
  103081. e1 = activeS;
  103082. }
  103083. }
  103084. do {
  103085. e2 = e1.pair;
  103086. if (e2 == min) {
  103087. e1.pair = e2.pair;
  103088. break;
  103089. }
  103090. e1 = e2;
  103091. } while (e1 != null);
  103092. }
  103093. }
  103094. this.index2 = (this.index1 | this.index2) ^ 3;
  103095. };
  103096. /**
  103097. * An element of proxies.
  103098. * @author saharan
  103099. */
  103100. OIMO.SAPElement = function (proxy, max) {
  103101. // The parent proxy
  103102. this.proxy = proxy;
  103103. // The pair element.
  103104. this.pair = null;
  103105. // The minimum element on other axis.
  103106. this.min1 = null;
  103107. // The maximum element on other axis.
  103108. this.max1 = null;
  103109. // The minimum element on other axis.
  103110. this.min2 = null;
  103111. // The maximum element on other axis.
  103112. this.max2 = null;
  103113. // Whether the element has maximum value or not.
  103114. this.max = max;
  103115. // The value of the element.
  103116. this.value = 0;
  103117. };
  103118. /**
  103119. * A proxy for sweep and prune broad-phase.
  103120. * @author saharan
  103121. * @author lo-th
  103122. */
  103123. OIMO.SAPProxy = function (sap, shape) {
  103124. OIMO.Proxy.call(this, shape);
  103125. // Type of the axis to which the proxy belongs to. [0:none, 1:dynamic, 2:static]
  103126. this.belongsTo = 0;
  103127. // The maximum elements on each axis.
  103128. this.max = [];
  103129. // The minimum elements on each axis.
  103130. this.min = [];
  103131. this.sap = sap;
  103132. this.min[0] = new OIMO.SAPElement(this, false);
  103133. this.max[0] = new OIMO.SAPElement(this, true);
  103134. this.min[1] = new OIMO.SAPElement(this, false);
  103135. this.max[1] = new OIMO.SAPElement(this, true);
  103136. this.min[2] = new OIMO.SAPElement(this, false);
  103137. this.max[2] = new OIMO.SAPElement(this, true);
  103138. this.max[0].pair = this.min[0];
  103139. this.max[1].pair = this.min[1];
  103140. this.max[2].pair = this.min[2];
  103141. this.min[0].min1 = this.min[1];
  103142. this.min[0].max1 = this.max[1];
  103143. this.min[0].min2 = this.min[2];
  103144. this.min[0].max2 = this.max[2];
  103145. this.min[1].min1 = this.min[0];
  103146. this.min[1].max1 = this.max[0];
  103147. this.min[1].min2 = this.min[2];
  103148. this.min[1].max2 = this.max[2];
  103149. this.min[2].min1 = this.min[0];
  103150. this.min[2].max1 = this.max[0];
  103151. this.min[2].min2 = this.min[1];
  103152. this.min[2].max2 = this.max[1];
  103153. };
  103154. OIMO.SAPProxy.prototype = Object.create(OIMO.Proxy.prototype);
  103155. OIMO.SAPProxy.prototype.constructor = OIMO.SAPProxy;
  103156. // Returns whether the proxy is dynamic or not.
  103157. OIMO.SAPProxy.prototype.isDynamic = function () {
  103158. var body = this.shape.parent;
  103159. return body.isDynamic && !body.sleeping;
  103160. };
  103161. OIMO.SAPProxy.prototype.update = function () {
  103162. var te = this.aabb.elements;
  103163. this.min[0].value = te[0];
  103164. this.min[1].value = te[1];
  103165. this.min[2].value = te[2];
  103166. this.max[0].value = te[3];
  103167. this.max[1].value = te[4];
  103168. this.max[2].value = te[5];
  103169. if (this.belongsTo == 1 && !this.isDynamic() || this.belongsTo == 2 && this.isDynamic()) {
  103170. this.sap.removeProxy(this);
  103171. this.sap.addProxy(this);
  103172. }
  103173. };
  103174. /**
  103175. * A dynamic bounding volume tree for the broad-phase algorithm.
  103176. * @author saharan
  103177. * @author lo-th
  103178. */
  103179. OIMO.DBVT = function () {
  103180. // The root of the tree.
  103181. this.root = null;
  103182. this.freeNodes = [];
  103183. this.freeNodes.length = 16384;
  103184. this.numFreeNodes = 0;
  103185. this.aabb = new OIMO.AABB();
  103186. };
  103187. OIMO.DBVT.prototype = {
  103188. constructor: OIMO.DBVT,
  103189. /**
  103190. * Move a leaf.
  103191. * @param leaf
  103192. */
  103193. moveLeaf: function (leaf) {
  103194. this.deleteLeaf(leaf);
  103195. this.insertLeaf(leaf);
  103196. },
  103197. /**
  103198. * Insert a leaf to the tree.
  103199. * @param node
  103200. */
  103201. insertLeaf: function (leaf) {
  103202. if (this.root == null) {
  103203. this.root = leaf;
  103204. return;
  103205. }
  103206. var lb = leaf.aabb;
  103207. var sibling = this.root;
  103208. var oldArea;
  103209. var newArea;
  103210. while (sibling.proxy == null) { // descend the node to search the best pair
  103211. var c1 = sibling.child1;
  103212. var c2 = sibling.child2;
  103213. var b = sibling.aabb;
  103214. var c1b = c1.aabb;
  103215. var c2b = c2.aabb;
  103216. oldArea = b.surfaceArea();
  103217. this.aabb.combine(lb, b);
  103218. newArea = this.aabb.surfaceArea();
  103219. var creatingCost = newArea * 2;
  103220. var incrementalCost = (newArea - oldArea) * 2; // cost of creating a new pair with the node
  103221. var discendingCost1 = incrementalCost;
  103222. this.aabb.combine(lb, c1b);
  103223. if (c1.proxy != null) {
  103224. // leaf cost = area(combined aabb)
  103225. discendingCost1 += this.aabb.surfaceArea();
  103226. } else {
  103227. // node cost = area(combined aabb) - area(old aabb)
  103228. discendingCost1 += this.aabb.surfaceArea() - c1b.surfaceArea();
  103229. }
  103230. var discendingCost2 = incrementalCost;
  103231. this.aabb.combine(lb, c2b);
  103232. if (c2.proxy != null) {
  103233. // leaf cost = area(combined aabb)
  103234. discendingCost2 += this.aabb.surfaceArea();
  103235. } else {
  103236. // node cost = area(combined aabb) - area(old aabb)
  103237. discendingCost2 += this.aabb.surfaceArea() - c2b.surfaceArea();
  103238. }
  103239. if (discendingCost1 < discendingCost2) {
  103240. if (creatingCost < discendingCost1) {
  103241. break;// stop descending
  103242. } else {
  103243. sibling = c1;// descend into first child
  103244. }
  103245. } else {
  103246. if (creatingCost < discendingCost2) {
  103247. break;// stop descending
  103248. } else {
  103249. sibling = c2;// descend into second child
  103250. }
  103251. }
  103252. }
  103253. var oldParent = sibling.parent;
  103254. var newParent;
  103255. if (this.numFreeNodes > 0) {
  103256. newParent = this.freeNodes[--this.numFreeNodes];
  103257. } else {
  103258. newParent = new OIMO.DBVTNode();
  103259. }
  103260. newParent.parent = oldParent;
  103261. newParent.child1 = leaf;
  103262. newParent.child2 = sibling;
  103263. newParent.aabb.combine(leaf.aabb, sibling.aabb);
  103264. newParent.height = sibling.height + 1;
  103265. sibling.parent = newParent;
  103266. leaf.parent = newParent;
  103267. if (sibling == this.root) {
  103268. // replace root
  103269. this.root = newParent;
  103270. } else {
  103271. // replace child
  103272. if (oldParent.child1 == sibling) {
  103273. oldParent.child1 = newParent;
  103274. } else {
  103275. oldParent.child2 = newParent;
  103276. }
  103277. }
  103278. // update whole tree
  103279. do {
  103280. newParent = this.balance(newParent);
  103281. this.fix(newParent);
  103282. newParent = newParent.parent;
  103283. } while (newParent != null);
  103284. },
  103285. getBalance: function (node) {
  103286. if (node.proxy != null) return 0;
  103287. return node.child1.height - node.child2.height;
  103288. },
  103289. /*print:function(node,indent,text){
  103290. var hasChild=node.proxy==null;
  103291. if(hasChild)text=this.print(node.child1,indent+1,text);
  103292. for(var i=indent*2;i>=0;i--){
  103293. text+=" ";
  103294. }
  103295. text+=(hasChild?this.getBalance(node):"["+node.proxy.aabb.minX+"]")+"\n";
  103296. if(hasChild)text=this.print(node.child2,indent+1,text);
  103297. return text;
  103298. },*/
  103299. /**
  103300. * Delete a leaf from the tree.
  103301. * @param node
  103302. */
  103303. deleteLeaf: function (leaf) {
  103304. if (leaf == this.root) {
  103305. this.root = null;
  103306. return;
  103307. }
  103308. var parent = leaf.parent;
  103309. var sibling;
  103310. if (parent.child1 == leaf) {
  103311. sibling = parent.child2;
  103312. } else {
  103313. sibling = parent.child1;
  103314. }
  103315. if (parent == this.root) {
  103316. this.root = sibling;
  103317. sibling.parent = null;
  103318. return;
  103319. }
  103320. var grandParent = parent.parent;
  103321. sibling.parent = grandParent;
  103322. if (grandParent.child1 == parent) {
  103323. grandParent.child1 = sibling;
  103324. } else {
  103325. grandParent.child2 = sibling;
  103326. }
  103327. if (this.numFreeNodes < 16384) {
  103328. this.freeNodes[this.numFreeNodes++] = parent;
  103329. }
  103330. do {
  103331. grandParent = this.balance(grandParent);
  103332. this.fix(grandParent);
  103333. grandParent = grandParent.parent;
  103334. } while (grandParent != null);
  103335. },
  103336. balance: function (node) {
  103337. var nh = node.height;
  103338. if (nh < 2) {
  103339. return node;
  103340. }
  103341. var p = node.parent;
  103342. var l = node.child1;
  103343. var r = node.child2;
  103344. var lh = l.height;
  103345. var rh = r.height;
  103346. var balance = lh - rh;
  103347. var t;// for bit operation
  103348. // [ N ]
  103349. // / \
  103350. // [ L ] [ R ]
  103351. // / \ / \
  103352. // [L-L] [L-R] [R-L] [R-R]
  103353. // Is the tree balanced?
  103354. if (balance > 1) {
  103355. var ll = l.child1;
  103356. var lr = l.child2;
  103357. var llh = ll.height;
  103358. var lrh = lr.height;
  103359. // Is L-L higher than L-R?
  103360. if (llh > lrh) {
  103361. // set N to L-R
  103362. l.child2 = node;
  103363. node.parent = l;
  103364. // [ L ]
  103365. // / \
  103366. // [L-L] [ N ]
  103367. // / \ / \
  103368. // [...] [...] [ L ] [ R ]
  103369. // set L-R
  103370. node.child1 = lr;
  103371. lr.parent = node;
  103372. // [ L ]
  103373. // / \
  103374. // [L-L] [ N ]
  103375. // / \ / \
  103376. // [...] [...] [L-R] [ R ]
  103377. // fix bounds and heights
  103378. node.aabb.combine(lr.aabb, r.aabb);
  103379. t = lrh - rh;
  103380. node.height = lrh - (t & t >> 31) + 1;
  103381. l.aabb.combine(ll.aabb, node.aabb);
  103382. t = llh - nh;
  103383. l.height = llh - (t & t >> 31) + 1;
  103384. } else {
  103385. // set N to L-L
  103386. l.child1 = node;
  103387. node.parent = l;
  103388. // [ L ]
  103389. // / \
  103390. // [ N ] [L-R]
  103391. // / \ / \
  103392. // [ L ] [ R ] [...] [...]
  103393. // set L-L
  103394. node.child1 = ll;
  103395. ll.parent = node;
  103396. // [ L ]
  103397. // / \
  103398. // [ N ] [L-R]
  103399. // / \ / \
  103400. // [L-L] [ R ] [...] [...]
  103401. // fix bounds and heights
  103402. node.aabb.combine(ll.aabb, r.aabb);
  103403. t = llh - rh;
  103404. node.height = llh - (t & t >> 31) + 1;
  103405. l.aabb.combine(node.aabb, lr.aabb);
  103406. t = nh - lrh;
  103407. l.height = nh - (t & t >> 31) + 1;
  103408. }
  103409. // set new parent of L
  103410. if (p != null) {
  103411. if (p.child1 == node) {
  103412. p.child1 = l;
  103413. } else {
  103414. p.child2 = l;
  103415. }
  103416. } else {
  103417. this.root = l;
  103418. }
  103419. l.parent = p;
  103420. return l;
  103421. } else if (balance < -1) {
  103422. var rl = r.child1;
  103423. var rr = r.child2;
  103424. var rlh = rl.height;
  103425. var rrh = rr.height;
  103426. // Is R-L higher than R-R?
  103427. if (rlh > rrh) {
  103428. // set N to R-R
  103429. r.child2 = node;
  103430. node.parent = r;
  103431. // [ R ]
  103432. // / \
  103433. // [R-L] [ N ]
  103434. // / \ / \
  103435. // [...] [...] [ L ] [ R ]
  103436. // set R-R
  103437. node.child2 = rr;
  103438. rr.parent = node;
  103439. // [ R ]
  103440. // / \
  103441. // [R-L] [ N ]
  103442. // / \ / \
  103443. // [...] [...] [ L ] [R-R]
  103444. // fix bounds and heights
  103445. node.aabb.combine(l.aabb, rr.aabb);
  103446. t = lh - rrh;
  103447. node.height = lh - (t & t >> 31) + 1;
  103448. r.aabb.combine(rl.aabb, node.aabb);
  103449. t = rlh - nh;
  103450. r.height = rlh - (t & t >> 31) + 1;
  103451. } else {
  103452. // set N to R-L
  103453. r.child1 = node;
  103454. node.parent = r;
  103455. // [ R ]
  103456. // / \
  103457. // [ N ] [R-R]
  103458. // / \ / \
  103459. // [ L ] [ R ] [...] [...]
  103460. // set R-L
  103461. node.child2 = rl;
  103462. rl.parent = node;
  103463. // [ R ]
  103464. // / \
  103465. // [ N ] [R-R]
  103466. // / \ / \
  103467. // [ L ] [R-L] [...] [...]
  103468. // fix bounds and heights
  103469. node.aabb.combine(l.aabb, rl.aabb);
  103470. t = lh - rlh;
  103471. node.height = lh - (t & t >> 31) + 1;
  103472. r.aabb.combine(node.aabb, rr.aabb);
  103473. t = nh - rrh;
  103474. r.height = nh - (t & t >> 31) + 1;
  103475. }
  103476. // set new parent of R
  103477. if (p != null) {
  103478. if (p.child1 == node) {
  103479. p.child1 = r;
  103480. } else {
  103481. p.child2 = r;
  103482. }
  103483. } else {
  103484. this.root = r;
  103485. }
  103486. r.parent = p;
  103487. return r;
  103488. }
  103489. return node;
  103490. },
  103491. fix: function (node) {
  103492. var c1 = node.child1;
  103493. var c2 = node.child2;
  103494. node.aabb.combine(c1.aabb, c2.aabb);
  103495. //var h1 = c1.height;
  103496. //var h2 = c2.height;
  103497. node.height = c1.height < c2.height ? c2.height + 1 : c1.height + 1;
  103498. /*if( h1 < h2 ) {
  103499. node.height = h2+1;
  103500. }else{
  103501. node.height = h1+1;
  103502. }*/
  103503. }
  103504. }
  103505. /**
  103506. * A broad-phase algorithm using dynamic bounding volume tree.
  103507. * @author saharan
  103508. * @author lo-th
  103509. */
  103510. OIMO.DBVTBroadPhase = function () {
  103511. OIMO.BroadPhase.call(this);
  103512. this.types = OIMO.BR_BOUNDING_VOLUME_TREE;
  103513. this.tree = new OIMO.DBVT();
  103514. this.stack = [];
  103515. this.leaves = [];
  103516. this.numLeaves = 0;
  103517. };
  103518. OIMO.DBVTBroadPhase.prototype = Object.create(OIMO.BroadPhase.prototype);
  103519. OIMO.DBVTBroadPhase.prototype.constructor = OIMO.DBVTBroadPhase;
  103520. OIMO.DBVTBroadPhase.prototype.createProxy = function (shape) {
  103521. return new OIMO.DBVTProxy(shape);
  103522. };
  103523. OIMO.DBVTBroadPhase.prototype.addProxy = function (proxy) {
  103524. this.tree.insertLeaf(proxy.leaf);
  103525. this.leaves.push(proxy.leaf);
  103526. this.numLeaves++;
  103527. };
  103528. OIMO.DBVTBroadPhase.prototype.removeProxy = function (proxy) {
  103529. this.tree.deleteLeaf(proxy.leaf);
  103530. var n = this.leaves.indexOf(proxy.leaf);
  103531. if (n > -1) {
  103532. this.leaves.splice(n, 1);
  103533. this.numLeaves--;
  103534. }
  103535. };
  103536. OIMO.DBVTBroadPhase.prototype.collectPairs = function () {
  103537. if (this.numLeaves < 2) return;
  103538. var leaf, margin = 0.1, i = this.numLeaves;
  103539. while (i--) {
  103540. leaf = this.leaves[i];
  103541. if (leaf.proxy.aabb.intersectTestTwo(leaf.aabb)) {
  103542. leaf.aabb.copy(leaf.proxy.aabb, margin);
  103543. this.tree.deleteLeaf(leaf);
  103544. this.tree.insertLeaf(leaf);
  103545. this.collide(leaf, this.tree.root);
  103546. }
  103547. }
  103548. };
  103549. OIMO.DBVTBroadPhase.prototype.collide = function (node1, node2) {
  103550. var stackCount = 2;
  103551. var s1, s2, n1, n2, l1, l2;
  103552. this.stack[0] = node1;
  103553. this.stack[1] = node2;
  103554. while (stackCount > 0) {
  103555. n1 = this.stack[--stackCount];
  103556. n2 = this.stack[--stackCount];
  103557. l1 = n1.proxy != null;
  103558. l2 = n2.proxy != null;
  103559. this.numPairChecks++;
  103560. if (l1 && l2) {
  103561. s1 = n1.proxy.shape;
  103562. s2 = n2.proxy.shape;
  103563. if (s1 == s2 || s1.aabb.intersectTest(s2.aabb) || !this.isAvailablePair(s1, s2)) continue;
  103564. this.addPair(s1, s2);
  103565. } else {
  103566. if (n1.aabb.intersectTest(n2.aabb)) continue;
  103567. /*if(stackCount+4>=this.maxStack){// expand the stack
  103568. //this.maxStack<<=1;
  103569. this.maxStack*=2;
  103570. var newStack = [];// vector
  103571. newStack.length = this.maxStack;
  103572. for(var i=0;i<stackCount;i++){
  103573. newStack[i] = this.stack[i];
  103574. }
  103575. this.stack = newStack;
  103576. }*/
  103577. if (l2 || !l1 && (n1.aabb.surfaceArea() > n2.aabb.surfaceArea())) {
  103578. this.stack[stackCount++] = n1.child1;
  103579. this.stack[stackCount++] = n2;
  103580. this.stack[stackCount++] = n1.child2;
  103581. this.stack[stackCount++] = n2;
  103582. } else {
  103583. this.stack[stackCount++] = n1;
  103584. this.stack[stackCount++] = n2.child1;
  103585. this.stack[stackCount++] = n1;
  103586. this.stack[stackCount++] = n2.child2;
  103587. }
  103588. }
  103589. }
  103590. };
  103591. /**
  103592. * A node of the dynamic bounding volume tree.
  103593. * @author saharan
  103594. */
  103595. OIMO.DBVTNode = function () {
  103596. // The first child node of this node.
  103597. this.child1 = null;
  103598. // The second child node of this node.
  103599. this.child2 = null;
  103600. // The parent node of this tree.
  103601. this.parent = null;
  103602. // The proxy of this node. This has no value if this node is not leaf.
  103603. this.proxy = null;
  103604. // The maximum distance from leaf nodes.
  103605. this.height = 0;
  103606. // The AABB of this node.
  103607. this.aabb = new OIMO.AABB();
  103608. };
  103609. /**
  103610. * A proxy for dynamic bounding volume tree broad-phase.
  103611. * @author saharan
  103612. */
  103613. OIMO.DBVTProxy = function (shape) {
  103614. OIMO.Proxy.call(this, shape);
  103615. // The leaf of the proxy.
  103616. this.leaf = new OIMO.DBVTNode();
  103617. this.leaf.proxy = this;
  103618. };
  103619. OIMO.DBVTProxy.prototype = Object.create(OIMO.Proxy.prototype);
  103620. OIMO.DBVTProxy.prototype.constructor = OIMO.DBVTProxy;
  103621. OIMO.DBVTProxy.prototype.update = function () {
  103622. };
  103623. OIMO.World.prototype.add = function (obj) {
  103624. obj = obj || {};
  103625. var type = obj.type || "box";
  103626. if (typeof type === 'string') type = [type];// single shape
  103627. if (type[0].substring(0, 5) == 'joint') { // is joint
  103628. if (type[0] === 'joint') type[0] = 'jointHinge';
  103629. var axe1 = obj.axe1 || [1, 0, 0];
  103630. var axe2 = obj.axe2 || [1, 0, 0];
  103631. var pos1 = obj.pos1 || [0, 0, 0];
  103632. var pos2 = obj.pos2 || [0, 0, 0];
  103633. pos1 = pos1.map(function (x) { return x * OIMO.INV_SCALE; });
  103634. pos2 = pos2.map(function (x) { return x * OIMO.INV_SCALE; });
  103635. var min, max;
  103636. if (type[0] === "jointDistance") {
  103637. min = obj.min || 0;
  103638. max = obj.max || 10;
  103639. min = min * OIMO.INV_SCALE;
  103640. max = max * OIMO.INV_SCALE;
  103641. } else {
  103642. min = obj.min || 57.29578;
  103643. max = obj.max || 0;
  103644. min = min * OIMO.degtorad;
  103645. max = max * OIMO.degtorad;
  103646. }
  103647. var limit = obj.limit || null;
  103648. var spring = obj.spring || null;
  103649. var motor = obj.motor || null;
  103650. // joint setting
  103651. var jc = new OIMO.JointConfig();
  103652. jc.allowCollision = obj.collision || false;;
  103653. jc.localAxis1.init(axe1[0], axe1[1], axe1[2]);
  103654. jc.localAxis2.init(axe2[0], axe2[1], axe2[2]);
  103655. jc.localAnchorPoint1.init(pos1[0], pos1[1], pos1[2]);
  103656. jc.localAnchorPoint2.init(pos2[0], pos2[1], pos2[2]);
  103657. if (typeof obj.body1 == 'string' || obj.body1 instanceof String) obj.body1 = this.getByName(obj.body1);
  103658. if (typeof obj.body2 == 'string' || obj.body2 instanceof String) obj.body2 = this.getByName(obj.body2);
  103659. jc.body1 = obj.body1;
  103660. jc.body2 = obj.body2;
  103661. var joint;
  103662. switch (type[0]) {
  103663. case "jointDistance": joint = new OIMO.DistanceJoint(jc, min, max);
  103664. if (spring !== null) joint.limitMotor.setSpring(spring[0], spring[1]);
  103665. if (motor !== null) joint.limitMotor.setSpring(motor[0], motor[1]);
  103666. break;
  103667. case "jointHinge": joint = new OIMO.HingeJoint(jc, min, max);
  103668. if (spring !== null) joint.limitMotor.setSpring(spring[0], spring[1]);// soften the joint ex: 100, 0.2
  103669. if (motor !== null) joint.limitMotor.setSpring(motor[0], motor[1]);
  103670. break;
  103671. case "jointPrisme": joint = new OIMO.PrismaticJoint(jc, min, max); break;
  103672. case "jointSlide": joint = new OIMO.SliderJoint(jc, min, max); break;
  103673. case "jointBall": joint = new OIMO.BallAndSocketJoint(jc); break;
  103674. case "jointWheel": joint = new OIMO.WheelJoint(jc);
  103675. if (limit !== null) joint.rotationalLimitMotor1.setLimit(limit[0], limit[1]);
  103676. if (spring !== null) joint.rotationalLimitMotor1.setSpring(spring[0], spring[1]);
  103677. if (motor !== null) joint.rotationalLimitMotor1.setSpring(motor[0], motor[1]);
  103678. break;
  103679. }
  103680. joint.name = obj.name || '';
  103681. // finaly add to physics world
  103682. this.addJoint(joint);
  103683. return joint;
  103684. } else { // is body
  103685. // I'm dynamique or not
  103686. var move = obj.move || false;
  103687. // I can sleep or not
  103688. var noSleep = obj.noSleep || false;
  103689. // My start position
  103690. var p = obj.pos || [0, 0, 0];
  103691. p = p.map(function (x) { return x * OIMO.INV_SCALE; });
  103692. // My size
  103693. var s = obj.size || [1, 1, 1];
  103694. s = s.map(function (x) { return x * OIMO.INV_SCALE; });
  103695. // My rotation in degre
  103696. var rot = obj.rot || [0, 0, 0];
  103697. rot = rot.map(function (x) { return x * OIMO.degtorad; });
  103698. var r = [];
  103699. for (var i = 0; i < rot.length / 3; i++) {
  103700. var tmp = OIMO.EulerToAxis(rot[i + 0], rot[i + 1], rot[i + 2]);
  103701. r.push(tmp[0]); r.push(tmp[1]); r.push(tmp[2]); r.push(tmp[3]);
  103702. }
  103703. // My physics setting
  103704. var sc = new OIMO.ShapeConfig();
  103705. if (obj.sc !== undefined) sc = obj.sc;
  103706. if (obj.config) {
  103707. // The density of the shape.
  103708. sc.density = obj.config[0] === undefined ? 1 : obj.config[0];
  103709. // The coefficient of friction of the shape.
  103710. sc.friction = obj.config[1] === undefined ? 0.4 : obj.config[1];
  103711. // The coefficient of restitution of the shape.
  103712. sc.restitution = obj.config[2] === undefined ? 0.2 : obj.config[2];
  103713. // The bits of the collision groups to which the shape belongs.
  103714. sc.belongsTo = obj.config[3] || 1;
  103715. //sc.belongsTo = obj.config[3] === undefined ? 1 : obj.config[3];
  103716. // The bits of the collision groups with which the shape collides.
  103717. sc.collidesWith = obj.config[4] || 0xffffffff;
  103718. //sc.collidesWith = obj.config[4] === undefined ? 0xffffffff : obj.config[4];
  103719. }
  103720. // direct physics setting
  103721. if (obj.density !== undefined) sc.density = obj.density;
  103722. if (obj.friction !== undefined) sc.friction = obj.friction;
  103723. if (obj.restitution !== undefined) sc.restitution = obj.restitution;
  103724. if (obj.belongsTo !== undefined) sc.belongsTo = obj.belongsTo;
  103725. if (obj.collidesWith !== undefined) sc.collidesWith = obj.collidesWith;
  103726. if (obj.massPos) {
  103727. obj.massPos = obj.massPos.map(function (x) { return x * OIMO.INV_SCALE; });
  103728. sc.relativePosition.init(obj.massPos[0], obj.massPos[1], obj.massPos[2]);
  103729. }
  103730. if (obj.massRot) {
  103731. obj.massRot = obj.massRot.map(function (x) { return x * OIMO.degtorad; });
  103732. sc.relativeRotation = OIMO.EulerToMatrix(obj.massRot[0], obj.massRot[1], obj.massRot[2]);
  103733. }
  103734. // My rigidbody
  103735. var body = new OIMO.RigidBody(p[0], p[1], p[2], r[0], r[1], r[2], r[3]);
  103736. // My shapes
  103737. var shapes = [];
  103738. //if( typeof type === 'string' ) type = [type];// single shape
  103739. var n, n2;
  103740. for (var i = 0; i < type.length; i++) {
  103741. n = i * 3;
  103742. n2 = i * 4;
  103743. switch (type[i]) {
  103744. case "sphere": shapes[i] = new OIMO.SphereShape(sc, s[n]); break;
  103745. case "cylinder": shapes[i] = new OIMO.CylinderShape(sc, s[n], s[n + 1]); break;
  103746. case "box": shapes[i] = new OIMO.BoxShape(sc, s[n], s[n + 1], s[n + 2]); break;
  103747. }
  103748. body.addShape(shapes[i]);
  103749. if (i > 0) {
  103750. //shapes[i].position.init(p[0]+p[n+0], p[1]+p[n+1], p[2]+p[n+2] );
  103751. shapes[i].relativePosition = new OIMO.Vec3(p[n], p[n + 1], p[n + 2]);
  103752. if (r[n2 + 0]) shapes[i].relativeRotation = [r[n2], r[n2 + 1], r[n2 + 2], r[n2 + 3]];
  103753. }
  103754. }
  103755. // I'm static or i move
  103756. if (move) {
  103757. if (obj.massPos || obj.massRot) body.setupMass(0x1, false);
  103758. else body.setupMass(0x1, true);
  103759. if (noSleep) body.allowSleep = false;
  103760. else body.allowSleep = true;
  103761. } else {
  103762. body.setupMass(0x2);
  103763. }
  103764. body.name = obj.name || ' ';
  103765. // finaly add to physics world
  103766. this.addRigidBody(body);
  103767. return body;
  103768. }
  103769. }
  103770. //UMD simplified
  103771. var root = this;
  103772. if (!root['OIMO']) {
  103773. if (true)
  103774. module.exports = OIMO;
  103775. else if (typeof define === 'function' && define.amd)
  103776. define([], function () {
  103777. return OIMO;
  103778. });
  103779. else if (typeof exports === 'object')
  103780. exports["OIMO"] = OIMO;
  103781. else {
  103782. root["OIMO"] = OIMO;
  103783. }
  103784. }
  103785. /***/ }),
  103786. /* 19 */
  103787. /***/ (function(module, exports, __webpack_require__) {
  103788. "use strict";
  103789. Object.defineProperty(exports, "__esModule", { value: true });
  103790. var babylonjs_1 = __webpack_require__(0);
  103791. var helper_1 = __webpack_require__(2);
  103792. var TemplateManager = (function () {
  103793. function TemplateManager(containerElement) {
  103794. this.containerElement = containerElement;
  103795. this.templates = {};
  103796. this.onInit = new babylonjs_1.Observable();
  103797. this.onLoaded = new babylonjs_1.Observable();
  103798. this.onStateChange = new babylonjs_1.Observable();
  103799. this.onAllLoaded = new babylonjs_1.Observable();
  103800. this.onEventTriggered = new babylonjs_1.Observable();
  103801. this.eventManager = new eventManager_1.EventManager(this);
  103802. }
  103803. TemplateManager.prototype.initTemplate = function (templates) {
  103804. var _this = this;
  103805. var internalInit = function (dependencyMap, name, parentTemplate) {
  103806. var template = _this.templates[name];
  103807. var childrenTemplates = Object.keys(dependencyMap).map(function (childName) {
  103808. return internalInit(dependencyMap[childName], childName, template);
  103809. });
  103810. var addToParent = function () {
  103811. var containingElement = parentTemplate && parentTemplate.parent.querySelector(helper_1.camelToKebab(name)) || _this.containerElement;
  103812. template.appendTo(containingElement);
  103813. _this.checkLoadedState();
  103814. };
  103815. if (parentTemplate && !parentTemplate.parent) {
  103816. parentTemplate.onAppended.add(function () {
  103817. addToParent();
  103818. });
  103819. }
  103820. else {
  103821. addToParent();
  103822. }
  103823. return template;
  103824. };
  103825. return this.buildHTMLTree(templates).then(function (htmlTree) {
  103826. if (_this.templates['main']) {
  103827. internalInit(htmlTree, 'main');
  103828. }
  103829. else {
  103830. _this.checkLoadedState();
  103831. }
  103832. return;
  103833. });
  103834. };
  103835. TemplateManager.prototype.buildHTMLTree = function (templates) {
  103836. var _this = this;
  103837. var promises = Object.keys(templates).map(function (name) {
  103838. if (!templates[name])
  103839. return Promise.resolve(false);
  103840. var template = new Template(name, templates[name]);
  103841. template.onEventTriggered.add(function (eventData) { return _this.onEventTriggered.notifyObservers(eventData); });
  103842. _this.templates[name] = template;
  103843. return template.initPromise;
  103844. });
  103845. return Promise.all(promises).then(function () {
  103846. var templateStructure = {};
  103847. var buildTree = function (parentObject, name) {
  103848. _this.templates[name].isInHtmlTree = true;
  103849. var childNodes = _this.templates[name].getChildElements().filter(function (n) { return !!_this.templates[n]; });
  103850. childNodes.forEach(function (element) {
  103851. parentObject[element] = {};
  103852. buildTree(parentObject[element], element);
  103853. });
  103854. };
  103855. if (_this.templates['main']) {
  103856. buildTree(templateStructure, "main");
  103857. }
  103858. return templateStructure;
  103859. });
  103860. };
  103861. TemplateManager.prototype.getCanvas = function () {
  103862. return this.containerElement.querySelector('canvas');
  103863. };
  103864. TemplateManager.prototype.getTemplate = function (name) {
  103865. return this.templates[name];
  103866. };
  103867. TemplateManager.prototype.checkLoadedState = function () {
  103868. var _this = this;
  103869. var done = Object.keys(this.templates).length === 0 || Object.keys(this.templates).every(function (key) {
  103870. return (_this.templates[key].isLoaded && !!_this.templates[key].parent) || !_this.templates[key].isInHtmlTree;
  103871. });
  103872. if (done) {
  103873. this.onAllLoaded.notifyObservers(this);
  103874. }
  103875. };
  103876. TemplateManager.prototype.dispose = function () {
  103877. var _this = this;
  103878. Object.keys(this.templates).forEach(function (template) {
  103879. _this.templates[template].dispose();
  103880. });
  103881. this.onInit.clear();
  103882. this.onAllLoaded.clear();
  103883. this.onEventTriggered.clear();
  103884. this.onLoaded.clear();
  103885. this.onStateChange.clear();
  103886. };
  103887. return TemplateManager;
  103888. }());
  103889. exports.TemplateManager = TemplateManager;
  103890. var Handlebars = __webpack_require__(20);
  103891. var eventManager_1 = __webpack_require__(21);
  103892. Handlebars.registerHelper('eachInMap', function (map, block) {
  103893. var out = '';
  103894. Object.keys(map).map(function (prop) {
  103895. var data = map[prop];
  103896. if (typeof data === 'object') {
  103897. data.id = data.id || prop;
  103898. out += block.fn(data);
  103899. }
  103900. else {
  103901. out += block.fn({ id: prop, value: data });
  103902. }
  103903. });
  103904. return out;
  103905. });
  103906. var Template = (function () {
  103907. function Template(name, _configuration) {
  103908. var _this = this;
  103909. this.name = name;
  103910. this._configuration = _configuration;
  103911. this.onInit = new babylonjs_1.Observable();
  103912. this.onLoaded = new babylonjs_1.Observable();
  103913. this.onAppended = new babylonjs_1.Observable();
  103914. this.onStateChange = new babylonjs_1.Observable();
  103915. this.onEventTriggered = new babylonjs_1.Observable();
  103916. this.loadRequests = [];
  103917. this.isLoaded = false;
  103918. this.isShown = false;
  103919. this.isInHtmlTree = false;
  103920. this.onInit.notifyObservers(this);
  103921. var htmlContentPromise = this.getTemplateAsHtml(_configuration);
  103922. this.initPromise = htmlContentPromise.then(function (htmlTemplate) {
  103923. if (htmlTemplate) {
  103924. _this.htmlTemplate = htmlTemplate;
  103925. var compiledTemplate = Handlebars.compile(htmlTemplate);
  103926. var config = _this._configuration.params || {};
  103927. var rawHtml = compiledTemplate(config);
  103928. _this.fragment = document.createRange().createContextualFragment(rawHtml);
  103929. _this.isLoaded = true;
  103930. _this.isShown = true;
  103931. _this.onLoaded.notifyObservers(_this);
  103932. }
  103933. return _this;
  103934. });
  103935. }
  103936. Template.prototype.updateParams = function (params) {
  103937. this._configuration.params = params;
  103938. if (this.isLoaded) {
  103939. this.dispose();
  103940. }
  103941. var compiledTemplate = Handlebars.compile(this.htmlTemplate);
  103942. var config = this._configuration.params || {};
  103943. var rawHtml = compiledTemplate(config);
  103944. this.fragment = document.createRange().createContextualFragment(rawHtml);
  103945. if (this.parent) {
  103946. this.appendTo(this.parent, true);
  103947. }
  103948. };
  103949. Object.defineProperty(Template.prototype, "configuration", {
  103950. get: function () {
  103951. return this._configuration;
  103952. },
  103953. enumerable: true,
  103954. configurable: true
  103955. });
  103956. Template.prototype.getChildElements = function () {
  103957. var childrenArray = [];
  103958. var children = this.fragment.children;
  103959. if (!children) {
  103960. children = this.fragment.querySelectorAll('*');
  103961. }
  103962. for (var i = 0; i < children.length; ++i) {
  103963. childrenArray.push(helper_1.kebabToCamel(children.item(i).nodeName.toLowerCase()));
  103964. }
  103965. return childrenArray;
  103966. };
  103967. Template.prototype.appendTo = function (parent, forceRemove) {
  103968. var _this = this;
  103969. if (this.parent) {
  103970. if (forceRemove) {
  103971. this.parent.removeChild(this.fragment);
  103972. }
  103973. else {
  103974. return;
  103975. }
  103976. }
  103977. this.parent = parent;
  103978. if (this._configuration.id) {
  103979. this.parent.id = this._configuration.id;
  103980. }
  103981. this.fragment = this.parent.appendChild(this.fragment);
  103982. setTimeout(function () {
  103983. _this.registerEvents();
  103984. _this.onAppended.notifyObservers(_this);
  103985. });
  103986. };
  103987. Template.prototype.show = function (visibilityFunction) {
  103988. var _this = this;
  103989. if (this.isHiding)
  103990. return Promise.resolve(this);
  103991. return Promise.resolve().then(function () {
  103992. _this.isShowing = true;
  103993. if (visibilityFunction) {
  103994. return visibilityFunction(_this);
  103995. }
  103996. else {
  103997. _this.parent.style.display = 'flex';
  103998. return _this;
  103999. }
  104000. }).then(function () {
  104001. _this.isShown = true;
  104002. _this.isShowing = false;
  104003. _this.onStateChange.notifyObservers(_this);
  104004. return _this;
  104005. });
  104006. };
  104007. Template.prototype.hide = function (visibilityFunction) {
  104008. var _this = this;
  104009. if (this.isShowing)
  104010. return Promise.resolve(this);
  104011. return Promise.resolve().then(function () {
  104012. _this.isHiding = true;
  104013. if (visibilityFunction) {
  104014. return visibilityFunction(_this);
  104015. }
  104016. else {
  104017. _this.parent.style.display = 'hide';
  104018. return _this;
  104019. }
  104020. }).then(function () {
  104021. _this.isShown = false;
  104022. _this.isHiding = false;
  104023. _this.onStateChange.notifyObservers(_this);
  104024. return _this;
  104025. });
  104026. };
  104027. Template.prototype.dispose = function () {
  104028. this.onAppended.clear();
  104029. this.onEventTriggered.clear();
  104030. this.onInit.clear();
  104031. this.onLoaded.clear();
  104032. this.onStateChange.clear();
  104033. this.isLoaded = false;
  104034. this.parent.removeChild(this.fragment);
  104035. this.loadRequests.forEach(function (request) {
  104036. request.abort();
  104037. });
  104038. };
  104039. Template.prototype.getTemplateAsHtml = function (templateConfig) {
  104040. var _this = this;
  104041. if (!templateConfig) {
  104042. return Promise.reject('No templateConfig provided');
  104043. }
  104044. else if (templateConfig.html !== undefined) {
  104045. return Promise.resolve(templateConfig.html);
  104046. }
  104047. else {
  104048. var location_1 = getTemplateLocation(templateConfig);
  104049. if (helper_1.isUrl(location_1)) {
  104050. return new Promise(function (resolve, reject) {
  104051. var fileRequest = babylonjs_1.Tools.LoadFile(location_1, function (data) {
  104052. resolve(data);
  104053. }, undefined, undefined, false, function (request, error) {
  104054. reject(error);
  104055. });
  104056. _this.loadRequests.push(fileRequest);
  104057. });
  104058. }
  104059. else {
  104060. location_1 = location_1.replace('#', '');
  104061. var element = document.getElementById(location_1);
  104062. if (element) {
  104063. return Promise.resolve(element.innerHTML);
  104064. }
  104065. else {
  104066. return Promise.reject('Template ID not found');
  104067. }
  104068. }
  104069. }
  104070. };
  104071. Template.prototype.registerEvents = function () {
  104072. var _this = this;
  104073. this.registeredEvents = this.registeredEvents || [];
  104074. if (this.registeredEvents.length) {
  104075. this.registeredEvents.forEach(function (evt) {
  104076. evt.htmlElement.removeEventListener(evt.eventName, evt.function);
  104077. });
  104078. }
  104079. if (this._configuration.events) {
  104080. var _loop_1 = function (eventName) {
  104081. if (this_1._configuration.events && this_1._configuration.events[eventName]) {
  104082. var functionToFire_1 = function (selector, event) {
  104083. _this.onEventTriggered.notifyObservers({ event: event, template: _this, selector: selector });
  104084. };
  104085. if (typeof this_1._configuration.events[eventName] === 'boolean') {
  104086. this_1.parent.addEventListener(eventName, functionToFire_1.bind(this_1, '#' + this_1.parent.id), false);
  104087. }
  104088. else if (typeof this_1._configuration.events[eventName] === 'object') {
  104089. var selectorsArray = Object.keys(this_1._configuration.events[eventName] || {});
  104090. var event_1 = this_1._configuration.events[eventName] || {};
  104091. selectorsArray.filter(function (selector) { return event_1[selector]; }).forEach(function (selector) {
  104092. if (selector && selector.indexOf('#') !== 0) {
  104093. selector = '#' + selector;
  104094. }
  104095. var htmlElement = _this.parent.querySelector(selector);
  104096. if (htmlElement) {
  104097. var binding = functionToFire_1.bind(_this, selector);
  104098. htmlElement.addEventListener(eventName, binding, false);
  104099. _this.registeredEvents.push({
  104100. htmlElement: htmlElement,
  104101. eventName: eventName,
  104102. function: binding
  104103. });
  104104. }
  104105. });
  104106. }
  104107. }
  104108. };
  104109. var this_1 = this;
  104110. for (var eventName in this._configuration.events) {
  104111. _loop_1(eventName);
  104112. }
  104113. }
  104114. };
  104115. return Template;
  104116. }());
  104117. exports.Template = Template;
  104118. function getTemplateLocation(templateConfig) {
  104119. if (!templateConfig || typeof templateConfig === 'string') {
  104120. return templateConfig;
  104121. }
  104122. else {
  104123. return templateConfig.location;
  104124. }
  104125. }
  104126. exports.getTemplateLocation = getTemplateLocation;
  104127. /***/ }),
  104128. /* 20 */
  104129. /***/ (function(module, exports, __webpack_require__) {
  104130. /**!
  104131. @license
  104132. handlebars v4.0.11
  104133. Copyright (C) 2011-2017 by Yehuda Katz
  104134. Permission is hereby granted, free of charge, to any person obtaining a copy
  104135. of this software and associated documentation files (the "Software"), to deal
  104136. in the Software without restriction, including without limitation the rights
  104137. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  104138. copies of the Software, and to permit persons to whom the Software is
  104139. furnished to do so, subject to the following conditions:
  104140. The above copyright notice and this permission notice shall be included in
  104141. all copies or substantial portions of the Software.
  104142. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  104143. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  104144. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  104145. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  104146. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  104147. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  104148. THE SOFTWARE.
  104149. */
  104150. !function(a,b){ true?module.exports=b():"function"==typeof define&&define.amd?define([],b):"object"==typeof exports?exports.Handlebars=b():a.Handlebars=b()}(this,function(){return function(a){function b(d){if(c[d])return c[d].exports;var e=c[d]={exports:{},id:d,loaded:!1};return a[d].call(e.exports,e,e.exports,b),e.loaded=!0,e.exports}var c={};return b.m=a,b.c=c,b.p="",b(0)}([function(a,b,c){"use strict";function d(){var a=r();return a.compile=function(b,c){return k.compile(b,c,a)},a.precompile=function(b,c){return k.precompile(b,c,a)},a.AST=i["default"],a.Compiler=k.Compiler,a.JavaScriptCompiler=m["default"],a.Parser=j.parser,a.parse=j.parse,a}var e=c(1)["default"];b.__esModule=!0;var f=c(2),g=e(f),h=c(35),i=e(h),j=c(36),k=c(41),l=c(42),m=e(l),n=c(39),o=e(n),p=c(34),q=e(p),r=g["default"].create,s=d();s.create=d,q["default"](s),s.Visitor=o["default"],s["default"]=s,b["default"]=s,a.exports=b["default"]},function(a,b){"use strict";b["default"]=function(a){return a&&a.__esModule?a:{"default":a}},b.__esModule=!0},function(a,b,c){"use strict";function d(){var a=new h.HandlebarsEnvironment;return n.extend(a,h),a.SafeString=j["default"],a.Exception=l["default"],a.Utils=n,a.escapeExpression=n.escapeExpression,a.VM=p,a.template=function(b){return p.template(b,a)},a}var e=c(3)["default"],f=c(1)["default"];b.__esModule=!0;var g=c(4),h=e(g),i=c(21),j=f(i),k=c(6),l=f(k),m=c(5),n=e(m),o=c(22),p=e(o),q=c(34),r=f(q),s=d();s.create=d,r["default"](s),s["default"]=s,b["default"]=s,a.exports=b["default"]},function(a,b){"use strict";b["default"]=function(a){if(a&&a.__esModule)return a;var b={};if(null!=a)for(var c in a)Object.prototype.hasOwnProperty.call(a,c)&&(b[c]=a[c]);return b["default"]=a,b},b.__esModule=!0},function(a,b,c){"use strict";function d(a,b,c){this.helpers=a||{},this.partials=b||{},this.decorators=c||{},i.registerDefaultHelpers(this),j.registerDefaultDecorators(this)}var e=c(1)["default"];b.__esModule=!0,b.HandlebarsEnvironment=d;var f=c(5),g=c(6),h=e(g),i=c(10),j=c(18),k=c(20),l=e(k),m="4.0.11";b.VERSION=m;var n=7;b.COMPILER_REVISION=n;var o={1:"<= 1.0.rc.2",2:"== 1.0.0-rc.3",3:"== 1.0.0-rc.4",4:"== 1.x.x",5:"== 2.0.0-alpha.x",6:">= 2.0.0-beta.1",7:">= 4.0.0"};b.REVISION_CHANGES=o;var p="[object Object]";d.prototype={constructor:d,logger:l["default"],log:l["default"].log,registerHelper:function(a,b){if(f.toString.call(a)===p){if(b)throw new h["default"]("Arg not supported with multiple helpers");f.extend(this.helpers,a)}else this.helpers[a]=b},unregisterHelper:function(a){delete this.helpers[a]},registerPartial:function(a,b){if(f.toString.call(a)===p)f.extend(this.partials,a);else{if("undefined"==typeof b)throw new h["default"]('Attempting to register a partial called "'+a+'" as undefined');this.partials[a]=b}},unregisterPartial:function(a){delete this.partials[a]},registerDecorator:function(a,b){if(f.toString.call(a)===p){if(b)throw new h["default"]("Arg not supported with multiple decorators");f.extend(this.decorators,a)}else this.decorators[a]=b},unregisterDecorator:function(a){delete this.decorators[a]}};var q=l["default"].log;b.log=q,b.createFrame=f.createFrame,b.logger=l["default"]},function(a,b){"use strict";function c(a){return k[a]}function d(a){for(var b=1;b<arguments.length;b++)for(var c in arguments[b])Object.prototype.hasOwnProperty.call(arguments[b],c)&&(a[c]=arguments[b][c]);return a}function e(a,b){for(var c=0,d=a.length;c<d;c++)if(a[c]===b)return c;return-1}function f(a){if("string"!=typeof a){if(a&&a.toHTML)return a.toHTML();if(null==a)return"";if(!a)return a+"";a=""+a}return m.test(a)?a.replace(l,c):a}function g(a){return!a&&0!==a||!(!p(a)||0!==a.length)}function h(a){var b=d({},a);return b._parent=a,b}function i(a,b){return a.path=b,a}function j(a,b){return(a?a+".":"")+b}b.__esModule=!0,b.extend=d,b.indexOf=e,b.escapeExpression=f,b.isEmpty=g,b.createFrame=h,b.blockParams=i,b.appendContextPath=j;var k={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#x27;","`":"&#x60;","=":"&#x3D;"},l=/[&<>"'`=]/g,m=/[&<>"'`=]/,n=Object.prototype.toString;b.toString=n;var o=function(a){return"function"==typeof a};o(/x/)&&(b.isFunction=o=function(a){return"function"==typeof a&&"[object Function]"===n.call(a)}),b.isFunction=o;var p=Array.isArray||function(a){return!(!a||"object"!=typeof a)&&"[object Array]"===n.call(a)};b.isArray=p},function(a,b,c){"use strict";function d(a,b){var c=b&&b.loc,g=void 0,h=void 0;c&&(g=c.start.line,h=c.start.column,a+=" - "+g+":"+h);for(var i=Error.prototype.constructor.call(this,a),j=0;j<f.length;j++)this[f[j]]=i[f[j]];Error.captureStackTrace&&Error.captureStackTrace(this,d);try{c&&(this.lineNumber=g,e?Object.defineProperty(this,"column",{value:h,enumerable:!0}):this.column=h)}catch(k){}}var e=c(7)["default"];b.__esModule=!0;var f=["description","fileName","lineNumber","message","name","number","stack"];d.prototype=new Error,b["default"]=d,a.exports=b["default"]},function(a,b,c){a.exports={"default":c(8),__esModule:!0}},function(a,b,c){var d=c(9);a.exports=function(a,b,c){return d.setDesc(a,b,c)}},function(a,b){var c=Object;a.exports={create:c.create,getProto:c.getPrototypeOf,isEnum:{}.propertyIsEnumerable,getDesc:c.getOwnPropertyDescriptor,setDesc:c.defineProperty,setDescs:c.defineProperties,getKeys:c.keys,getNames:c.getOwnPropertyNames,getSymbols:c.getOwnPropertySymbols,each:[].forEach}},function(a,b,c){"use strict";function d(a){g["default"](a),i["default"](a),k["default"](a),m["default"](a),o["default"](a),q["default"](a),s["default"](a)}var e=c(1)["default"];b.__esModule=!0,b.registerDefaultHelpers=d;var f=c(11),g=e(f),h=c(12),i=e(h),j=c(13),k=e(j),l=c(14),m=e(l),n=c(15),o=e(n),p=c(16),q=e(p),r=c(17),s=e(r)},function(a,b,c){"use strict";b.__esModule=!0;var d=c(5);b["default"]=function(a){a.registerHelper("blockHelperMissing",function(b,c){var e=c.inverse,f=c.fn;if(b===!0)return f(this);if(b===!1||null==b)return e(this);if(d.isArray(b))return b.length>0?(c.ids&&(c.ids=[c.name]),a.helpers.each(b,c)):e(this);if(c.data&&c.ids){var g=d.createFrame(c.data);g.contextPath=d.appendContextPath(c.data.contextPath,c.name),c={data:g}}return f(b,c)})},a.exports=b["default"]},function(a,b,c){"use strict";var d=c(1)["default"];b.__esModule=!0;var e=c(5),f=c(6),g=d(f);b["default"]=function(a){a.registerHelper("each",function(a,b){function c(b,c,f){j&&(j.key=b,j.index=c,j.first=0===c,j.last=!!f,k&&(j.contextPath=k+b)),i+=d(a[b],{data:j,blockParams:e.blockParams([a[b],b],[k+b,null])})}if(!b)throw new g["default"]("Must pass iterator to #each");var d=b.fn,f=b.inverse,h=0,i="",j=void 0,k=void 0;if(b.data&&b.ids&&(k=e.appendContextPath(b.data.contextPath,b.ids[0])+"."),e.isFunction(a)&&(a=a.call(this)),b.data&&(j=e.createFrame(b.data)),a&&"object"==typeof a)if(e.isArray(a))for(var l=a.length;h<l;h++)h in a&&c(h,h,h===a.length-1);else{var m=void 0;for(var n in a)a.hasOwnProperty(n)&&(void 0!==m&&c(m,h-1),m=n,h++);void 0!==m&&c(m,h-1,!0)}return 0===h&&(i=f(this)),i})},a.exports=b["default"]},function(a,b,c){"use strict";var d=c(1)["default"];b.__esModule=!0;var e=c(6),f=d(e);b["default"]=function(a){a.registerHelper("helperMissing",function(){if(1!==arguments.length)throw new f["default"]('Missing helper: "'+arguments[arguments.length-1].name+'"')})},a.exports=b["default"]},function(a,b,c){"use strict";b.__esModule=!0;var d=c(5);b["default"]=function(a){a.registerHelper("if",function(a,b){return d.isFunction(a)&&(a=a.call(this)),!b.hash.includeZero&&!a||d.isEmpty(a)?b.inverse(this):b.fn(this)}),a.registerHelper("unless",function(b,c){return a.helpers["if"].call(this,b,{fn:c.inverse,inverse:c.fn,hash:c.hash})})},a.exports=b["default"]},function(a,b){"use strict";b.__esModule=!0,b["default"]=function(a){a.registerHelper("log",function(){for(var b=[void 0],c=arguments[arguments.length-1],d=0;d<arguments.length-1;d++)b.push(arguments[d]);var e=1;null!=c.hash.level?e=c.hash.level:c.data&&null!=c.data.level&&(e=c.data.level),b[0]=e,a.log.apply(a,b)})},a.exports=b["default"]},function(a,b){"use strict";b.__esModule=!0,b["default"]=function(a){a.registerHelper("lookup",function(a,b){return a&&a[b]})},a.exports=b["default"]},function(a,b,c){"use strict";b.__esModule=!0;var d=c(5);b["default"]=function(a){a.registerHelper("with",function(a,b){d.isFunction(a)&&(a=a.call(this));var c=b.fn;if(d.isEmpty(a))return b.inverse(this);var e=b.data;return b.data&&b.ids&&(e=d.createFrame(b.data),e.contextPath=d.appendContextPath(b.data.contextPath,b.ids[0])),c(a,{data:e,blockParams:d.blockParams([a],[e&&e.contextPath])})})},a.exports=b["default"]},function(a,b,c){"use strict";function d(a){g["default"](a)}var e=c(1)["default"];b.__esModule=!0,b.registerDefaultDecorators=d;var f=c(19),g=e(f)},function(a,b,c){"use strict";b.__esModule=!0;var d=c(5);b["default"]=function(a){a.registerDecorator("inline",function(a,b,c,e){var f=a;return b.partials||(b.partials={},f=function(e,f){var g=c.partials;c.partials=d.extend({},g,b.partials);var h=a(e,f);return c.partials=g,h}),b.partials[e.args[0]]=e.fn,f})},a.exports=b["default"]},function(a,b,c){"use strict";b.__esModule=!0;var d=c(5),e={methodMap:["debug","info","warn","error"],level:"info",lookupLevel:function(a){if("string"==typeof a){var b=d.indexOf(e.methodMap,a.toLowerCase());a=b>=0?b:parseInt(a,10)}return a},log:function(a){if(a=e.lookupLevel(a),"undefined"!=typeof console&&e.lookupLevel(e.level)<=a){var b=e.methodMap[a];console[b]||(b="log");for(var c=arguments.length,d=Array(c>1?c-1:0),f=1;f<c;f++)d[f-1]=arguments[f];console[b].apply(console,d)}}};b["default"]=e,a.exports=b["default"]},function(a,b){"use strict";function c(a){this.string=a}b.__esModule=!0,c.prototype.toString=c.prototype.toHTML=function(){return""+this.string},b["default"]=c,a.exports=b["default"]},function(a,b,c){"use strict";function d(a){var b=a&&a[0]||1,c=s.COMPILER_REVISION;if(b!==c){if(b<c){var d=s.REVISION_CHANGES[c],e=s.REVISION_CHANGES[b];throw new r["default"]("Template was precompiled with an older version of Handlebars than the current runtime. Please update your precompiler to a newer version ("+d+") or downgrade your runtime to an older version ("+e+").")}throw new r["default"]("Template was precompiled with a newer version of Handlebars than the current runtime. Please update your runtime to a newer version ("+a[1]+").")}}function e(a,b){function c(c,d,e){e.hash&&(d=p.extend({},d,e.hash),e.ids&&(e.ids[0]=!0)),c=b.VM.resolvePartial.call(this,c,d,e);var f=b.VM.invokePartial.call(this,c,d,e);if(null==f&&b.compile&&(e.partials[e.name]=b.compile(c,a.compilerOptions,b),f=e.partials[e.name](d,e)),null!=f){if(e.indent){for(var g=f.split("\n"),h=0,i=g.length;h<i&&(g[h]||h+1!==i);h++)g[h]=e.indent+g[h];f=g.join("\n")}return f}throw new r["default"]("The partial "+e.name+" could not be compiled when running in runtime-only mode")}function d(b){function c(b){return""+a.main(e,b,e.helpers,e.partials,g,i,h)}var f=arguments.length<=1||void 0===arguments[1]?{}:arguments[1],g=f.data;d._setup(f),!f.partial&&a.useData&&(g=j(b,g));var h=void 0,i=a.useBlockParams?[]:void 0;return a.useDepths&&(h=f.depths?b!=f.depths[0]?[b].concat(f.depths):f.depths:[b]),(c=k(a.main,c,e,f.depths||[],g,i))(b,f)}if(!b)throw new r["default"]("No environment passed to template");if(!a||!a.main)throw new r["default"]("Unknown template object: "+typeof a);a.main.decorator=a.main_d,b.VM.checkRevision(a.compiler);var e={strict:function(a,b){if(!(b in a))throw new r["default"]('"'+b+'" not defined in '+a);return a[b]},lookup:function(a,b){for(var c=a.length,d=0;d<c;d++)if(a[d]&&null!=a[d][b])return a[d][b]},lambda:function(a,b){return"function"==typeof a?a.call(b):a},escapeExpression:p.escapeExpression,invokePartial:c,fn:function(b){var c=a[b];return c.decorator=a[b+"_d"],c},programs:[],program:function(a,b,c,d,e){var g=this.programs[a],h=this.fn(a);return b||e||d||c?g=f(this,a,h,b,c,d,e):g||(g=this.programs[a]=f(this,a,h)),g},data:function(a,b){for(;a&&b--;)a=a._parent;return a},merge:function(a,b){var c=a||b;return a&&b&&a!==b&&(c=p.extend({},b,a)),c},nullContext:l({}),noop:b.VM.noop,compilerInfo:a.compiler};return d.isTop=!0,d._setup=function(c){c.partial?(e.helpers=c.helpers,e.partials=c.partials,e.decorators=c.decorators):(e.helpers=e.merge(c.helpers,b.helpers),a.usePartial&&(e.partials=e.merge(c.partials,b.partials)),(a.usePartial||a.useDecorators)&&(e.decorators=e.merge(c.decorators,b.decorators)))},d._child=function(b,c,d,g){if(a.useBlockParams&&!d)throw new r["default"]("must pass block params");if(a.useDepths&&!g)throw new r["default"]("must pass parent depths");return f(e,b,a[b],c,0,d,g)},d}function f(a,b,c,d,e,f,g){function h(b){var e=arguments.length<=1||void 0===arguments[1]?{}:arguments[1],h=g;return!g||b==g[0]||b===a.nullContext&&null===g[0]||(h=[b].concat(g)),c(a,b,a.helpers,a.partials,e.data||d,f&&[e.blockParams].concat(f),h)}return h=k(c,h,a,g,d,f),h.program=b,h.depth=g?g.length:0,h.blockParams=e||0,h}function g(a,b,c){return a?a.call||c.name||(c.name=a,a=c.partials[a]):a="@partial-block"===c.name?c.data["partial-block"]:c.partials[c.name],a}function h(a,b,c){var d=c.data&&c.data["partial-block"];c.partial=!0,c.ids&&(c.data.contextPath=c.ids[0]||c.data.contextPath);var e=void 0;if(c.fn&&c.fn!==i&&!function(){c.data=s.createFrame(c.data);var a=c.fn;e=c.data["partial-block"]=function(b){var c=arguments.length<=1||void 0===arguments[1]?{}:arguments[1];return c.data=s.createFrame(c.data),c.data["partial-block"]=d,a(b,c)},a.partials&&(c.partials=p.extend({},c.partials,a.partials))}(),void 0===a&&e&&(a=e),void 0===a)throw new r["default"]("The partial "+c.name+" could not be found");if(a instanceof Function)return a(b,c)}function i(){return""}function j(a,b){return b&&"root"in b||(b=b?s.createFrame(b):{},b.root=a),b}function k(a,b,c,d,e,f){if(a.decorator){var g={};b=a.decorator(b,g,c,d&&d[0],e,f,d),p.extend(b,g)}return b}var l=c(23)["default"],m=c(3)["default"],n=c(1)["default"];b.__esModule=!0,b.checkRevision=d,b.template=e,b.wrapProgram=f,b.resolvePartial=g,b.invokePartial=h,b.noop=i;var o=c(5),p=m(o),q=c(6),r=n(q),s=c(4)},function(a,b,c){a.exports={"default":c(24),__esModule:!0}},function(a,b,c){c(25),a.exports=c(30).Object.seal},function(a,b,c){var d=c(26);c(27)("seal",function(a){return function(b){return a&&d(b)?a(b):b}})},function(a,b){a.exports=function(a){return"object"==typeof a?null!==a:"function"==typeof a}},function(a,b,c){var d=c(28),e=c(30),f=c(33);a.exports=function(a,b){var c=(e.Object||{})[a]||Object[a],g={};g[a]=b(c),d(d.S+d.F*f(function(){c(1)}),"Object",g)}},function(a,b,c){var d=c(29),e=c(30),f=c(31),g="prototype",h=function(a,b,c){var i,j,k,l=a&h.F,m=a&h.G,n=a&h.S,o=a&h.P,p=a&h.B,q=a&h.W,r=m?e:e[b]||(e[b]={}),s=m?d:n?d[b]:(d[b]||{})[g];m&&(c=b);for(i in c)j=!l&&s&&i in s,j&&i in r||(k=j?s[i]:c[i],r[i]=m&&"function"!=typeof s[i]?c[i]:p&&j?f(k,d):q&&s[i]==k?function(a){var b=function(b){return this instanceof a?new a(b):a(b)};return b[g]=a[g],b}(k):o&&"function"==typeof k?f(Function.call,k):k,o&&((r[g]||(r[g]={}))[i]=k))};h.F=1,h.G=2,h.S=4,h.P=8,h.B=16,h.W=32,a.exports=h},function(a,b){var c=a.exports="undefined"!=typeof window&&window.Math==Math?window:"undefined"!=typeof self&&self.Math==Math?self:Function("return this")();"number"==typeof __g&&(__g=c)},function(a,b){var c=a.exports={version:"1.2.6"};"number"==typeof __e&&(__e=c)},function(a,b,c){var d=c(32);a.exports=function(a,b,c){if(d(a),void 0===b)return a;switch(c){case 1:return function(c){return a.call(b,c)};case 2:return function(c,d){return a.call(b,c,d)};case 3:return function(c,d,e){return a.call(b,c,d,e)}}return function(){return a.apply(b,arguments)}}},function(a,b){a.exports=function(a){if("function"!=typeof a)throw TypeError(a+" is not a function!");return a}},function(a,b){a.exports=function(a){try{return!!a()}catch(b){return!0}}},function(a,b){(function(c){"use strict";b.__esModule=!0,b["default"]=function(a){var b="undefined"!=typeof c?c:window,d=b.Handlebars;a.noConflict=function(){return b.Handlebars===a&&(b.Handlebars=d),a}},a.exports=b["default"]}).call(b,function(){return this}())},function(a,b){"use strict";b.__esModule=!0;var c={helpers:{helperExpression:function(a){return"SubExpression"===a.type||("MustacheStatement"===a.type||"BlockStatement"===a.type)&&!!(a.params&&a.params.length||a.hash)},scopedId:function(a){return/^\.|this\b/.test(a.original)},simpleId:function(a){return 1===a.parts.length&&!c.helpers.scopedId(a)&&!a.depth}}};b["default"]=c,a.exports=b["default"]},function(a,b,c){"use strict";function d(a,b){if("Program"===a.type)return a;h["default"].yy=n,n.locInfo=function(a){return new n.SourceLocation(b&&b.srcName,a)};var c=new j["default"](b);return c.accept(h["default"].parse(a))}var e=c(1)["default"],f=c(3)["default"];b.__esModule=!0,b.parse=d;var g=c(37),h=e(g),i=c(38),j=e(i),k=c(40),l=f(k),m=c(5);b.parser=h["default"];var n={};m.extend(n,l)},function(a,b){"use strict";b.__esModule=!0;var c=function(){function a(){this.yy={}}var b={trace:function(){},yy:{},symbols_:{error:2,root:3,program:4,EOF:5,program_repetition0:6,statement:7,mustache:8,block:9,rawBlock:10,partial:11,partialBlock:12,content:13,COMMENT:14,CONTENT:15,openRawBlock:16,rawBlock_repetition_plus0:17,END_RAW_BLOCK:18,OPEN_RAW_BLOCK:19,helperName:20,openRawBlock_repetition0:21,openRawBlock_option0:22,CLOSE_RAW_BLOCK:23,openBlock:24,block_option0:25,closeBlock:26,openInverse:27,block_option1:28,OPEN_BLOCK:29,openBlock_repetition0:30,openBlock_option0:31,openBlock_option1:32,CLOSE:33,OPEN_INVERSE:34,openInverse_repetition0:35,openInverse_option0:36,openInverse_option1:37,openInverseChain:38,OPEN_INVERSE_CHAIN:39,openInverseChain_repetition0:40,openInverseChain_option0:41,openInverseChain_option1:42,inverseAndProgram:43,INVERSE:44,inverseChain:45,inverseChain_option0:46,OPEN_ENDBLOCK:47,OPEN:48,mustache_repetition0:49,mustache_option0:50,OPEN_UNESCAPED:51,mustache_repetition1:52,mustache_option1:53,CLOSE_UNESCAPED:54,OPEN_PARTIAL:55,partialName:56,partial_repetition0:57,partial_option0:58,openPartialBlock:59,OPEN_PARTIAL_BLOCK:60,openPartialBlock_repetition0:61,openPartialBlock_option0:62,param:63,sexpr:64,OPEN_SEXPR:65,sexpr_repetition0:66,sexpr_option0:67,CLOSE_SEXPR:68,hash:69,hash_repetition_plus0:70,hashSegment:71,ID:72,EQUALS:73,blockParams:74,OPEN_BLOCK_PARAMS:75,blockParams_repetition_plus0:76,CLOSE_BLOCK_PARAMS:77,path:78,dataName:79,STRING:80,NUMBER:81,BOOLEAN:82,UNDEFINED:83,NULL:84,DATA:85,pathSegments:86,SEP:87,$accept:0,$end:1},terminals_:{2:"error",5:"EOF",14:"COMMENT",15:"CONTENT",18:"END_RAW_BLOCK",19:"OPEN_RAW_BLOCK",23:"CLOSE_RAW_BLOCK",29:"OPEN_BLOCK",33:"CLOSE",34:"OPEN_INVERSE",39:"OPEN_INVERSE_CHAIN",44:"INVERSE",47:"OPEN_ENDBLOCK",48:"OPEN",51:"OPEN_UNESCAPED",54:"CLOSE_UNESCAPED",55:"OPEN_PARTIAL",60:"OPEN_PARTIAL_BLOCK",65:"OPEN_SEXPR",68:"CLOSE_SEXPR",72:"ID",73:"EQUALS",75:"OPEN_BLOCK_PARAMS",77:"CLOSE_BLOCK_PARAMS",80:"STRING",81:"NUMBER",82:"BOOLEAN",83:"UNDEFINED",84:"NULL",85:"DATA",87:"SEP"},productions_:[0,[3,2],[4,1],[7,1],[7,1],[7,1],[7,1],[7,1],[7,1],[7,1],[13,1],[10,3],[16,5],[9,4],[9,4],[24,6],[27,6],[38,6],[43,2],[45,3],[45,1],[26,3],[8,5],[8,5],[11,5],[12,3],[59,5],[63,1],[63,1],[64,5],[69,1],[71,3],[74,3],[20,1],[20,1],[20,1],[20,1],[20,1],[20,1],[20,1],[56,1],[56,1],[79,2],[78,1],[86,3],[86,1],[6,0],[6,2],[17,1],[17,2],[21,0],[21,2],[22,0],[22,1],[25,0],[25,1],[28,0],[28,1],[30,0],[30,2],[31,0],[31,1],[32,0],[32,1],[35,0],[35,2],[36,0],[36,1],[37,0],[37,1],[40,0],[40,2],[41,0],[41,1],[42,0],[42,1],[46,0],[46,1],[49,0],[49,2],[50,0],[50,1],[52,0],[52,2],[53,0],[53,1],[57,0],[57,2],[58,0],[58,1],[61,0],[61,2],[62,0],[62,1],[66,0],[66,2],[67,0],[67,1],[70,1],[70,2],[76,1],[76,2]],performAction:function(a,b,c,d,e,f,g){var h=f.length-1;switch(e){case 1:return f[h-1];case 2:this.$=d.prepareProgram(f[h]);break;case 3:this.$=f[h];break;case 4:this.$=f[h];break;case 5:this.$=f[h];break;case 6:this.$=f[h];break;case 7:this.$=f[h];break;case 8:this.$=f[h];break;case 9:this.$={type:"CommentStatement",value:d.stripComment(f[h]),strip:d.stripFlags(f[h],f[h]),loc:d.locInfo(this._$)};break;case 10:this.$={type:"ContentStatement",original:f[h],value:f[h],loc:d.locInfo(this._$)};break;case 11:this.$=d.prepareRawBlock(f[h-2],f[h-1],f[h],this._$);break;case 12:this.$={path:f[h-3],params:f[h-2],hash:f[h-1]};break;case 13:this.$=d.prepareBlock(f[h-3],f[h-2],f[h-1],f[h],!1,this._$);break;case 14:this.$=d.prepareBlock(f[h-3],f[h-2],f[h-1],f[h],!0,this._$);break;case 15:this.$={open:f[h-5],path:f[h-4],params:f[h-3],hash:f[h-2],blockParams:f[h-1],strip:d.stripFlags(f[h-5],f[h])};break;case 16:this.$={path:f[h-4],params:f[h-3],hash:f[h-2],blockParams:f[h-1],strip:d.stripFlags(f[h-5],f[h])};break;case 17:this.$={path:f[h-4],params:f[h-3],hash:f[h-2],blockParams:f[h-1],strip:d.stripFlags(f[h-5],f[h])};break;case 18:this.$={strip:d.stripFlags(f[h-1],f[h-1]),program:f[h]};break;case 19:var i=d.prepareBlock(f[h-2],f[h-1],f[h],f[h],!1,this._$),j=d.prepareProgram([i],f[h-1].loc);j.chained=!0,this.$={strip:f[h-2].strip,program:j,chain:!0};break;case 20:this.$=f[h];break;case 21:this.$={path:f[h-1],strip:d.stripFlags(f[h-2],f[h])};break;case 22:this.$=d.prepareMustache(f[h-3],f[h-2],f[h-1],f[h-4],d.stripFlags(f[h-4],f[h]),this._$);break;case 23:this.$=d.prepareMustache(f[h-3],f[h-2],f[h-1],f[h-4],d.stripFlags(f[h-4],f[h]),this._$);break;case 24:this.$={type:"PartialStatement",name:f[h-3],params:f[h-2],hash:f[h-1],indent:"",strip:d.stripFlags(f[h-4],f[h]),loc:d.locInfo(this._$)};break;case 25:this.$=d.preparePartialBlock(f[h-2],f[h-1],f[h],this._$);break;case 26:this.$={path:f[h-3],params:f[h-2],hash:f[h-1],strip:d.stripFlags(f[h-4],f[h])};break;case 27:this.$=f[h];break;case 28:this.$=f[h];break;case 29:this.$={type:"SubExpression",path:f[h-3],params:f[h-2],hash:f[h-1],loc:d.locInfo(this._$)};break;case 30:this.$={type:"Hash",pairs:f[h],loc:d.locInfo(this._$)};break;case 31:this.$={type:"HashPair",key:d.id(f[h-2]),value:f[h],loc:d.locInfo(this._$)};break;case 32:this.$=d.id(f[h-1]);break;case 33:this.$=f[h];break;case 34:this.$=f[h];break;case 35:this.$={type:"StringLiteral",value:f[h],original:f[h],loc:d.locInfo(this._$)};break;case 36:this.$={type:"NumberLiteral",value:Number(f[h]),original:Number(f[h]),loc:d.locInfo(this._$)};break;case 37:this.$={type:"BooleanLiteral",value:"true"===f[h],original:"true"===f[h],loc:d.locInfo(this._$)};break;case 38:this.$={type:"UndefinedLiteral",original:void 0,value:void 0,loc:d.locInfo(this._$)};break;case 39:this.$={type:"NullLiteral",original:null,value:null,loc:d.locInfo(this._$)};break;case 40:this.$=f[h];break;case 41:this.$=f[h];break;case 42:this.$=d.preparePath(!0,f[h],this._$);break;case 43:this.$=d.preparePath(!1,f[h],this._$);break;case 44:f[h-2].push({part:d.id(f[h]),original:f[h],separator:f[h-1]}),this.$=f[h-2];break;case 45:this.$=[{part:d.id(f[h]),original:f[h]}];break;case 46:this.$=[];break;case 47:f[h-1].push(f[h]);break;case 48:this.$=[f[h]];break;case 49:f[h-1].push(f[h]);break;case 50:this.$=[];break;case 51:f[h-1].push(f[h]);break;case 58:this.$=[];break;case 59:f[h-1].push(f[h]);break;case 64:this.$=[];break;case 65:f[h-1].push(f[h]);break;case 70:this.$=[];break;case 71:f[h-1].push(f[h]);break;case 78:this.$=[];break;case 79:f[h-1].push(f[h]);break;case 82:this.$=[];break;case 83:f[h-1].push(f[h]);break;case 86:this.$=[];break;case 87:f[h-1].push(f[h]);break;case 90:this.$=[];break;case 91:f[h-1].push(f[h]);break;case 94:this.$=[];break;case 95:f[h-1].push(f[h]);break;case 98:this.$=[f[h]];break;case 99:f[h-1].push(f[h]);break;case 100:this.$=[f[h]];break;case 101:f[h-1].push(f[h])}},table:[{3:1,4:2,5:[2,46],6:3,14:[2,46],15:[2,46],19:[2,46],29:[2,46],34:[2,46],48:[2,46],51:[2,46],55:[2,46],60:[2,46]},{1:[3]},{5:[1,4]},{5:[2,2],7:5,8:6,9:7,10:8,11:9,12:10,13:11,14:[1,12],15:[1,20],16:17,19:[1,23],24:15,27:16,29:[1,21],34:[1,22],39:[2,2],44:[2,2],47:[2,2],48:[1,13],51:[1,14],55:[1,18],59:19,60:[1,24]},{1:[2,1]},{5:[2,47],14:[2,47],15:[2,47],19:[2,47],29:[2,47],34:[2,47],39:[2,47],44:[2,47],47:[2,47],48:[2,47],51:[2,47],55:[2,47],60:[2,47]},{5:[2,3],14:[2,3],15:[2,3],19:[2,3],29:[2,3],34:[2,3],39:[2,3],44:[2,3],47:[2,3],48:[2,3],51:[2,3],55:[2,3],60:[2,3]},{5:[2,4],14:[2,4],15:[2,4],19:[2,4],29:[2,4],34:[2,4],39:[2,4],44:[2,4],47:[2,4],48:[2,4],51:[2,4],55:[2,4],60:[2,4]},{5:[2,5],14:[2,5],15:[2,5],19:[2,5],29:[2,5],34:[2,5],39:[2,5],44:[2,5],47:[2,5],48:[2,5],51:[2,5],55:[2,5],60:[2,5]},{5:[2,6],14:[2,6],15:[2,6],19:[2,6],29:[2,6],34:[2,6],39:[2,6],44:[2,6],47:[2,6],48:[2,6],51:[2,6],55:[2,6],60:[2,6]},{5:[2,7],14:[2,7],15:[2,7],19:[2,7],29:[2,7],34:[2,7],39:[2,7],44:[2,7],47:[2,7],48:[2,7],51:[2,7],55:[2,7],60:[2,7]},{5:[2,8],14:[2,8],15:[2,8],19:[2,8],29:[2,8],34:[2,8],39:[2,8],44:[2,8],47:[2,8],48:[2,8],51:[2,8],55:[2,8],60:[2,8]},{5:[2,9],14:[2,9],15:[2,9],19:[2,9],29:[2,9],34:[2,9],39:[2,9],44:[2,9],47:[2,9],48:[2,9],51:[2,9],55:[2,9],60:[2,9]},{20:25,72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{20:36,72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{4:37,6:3,14:[2,46],15:[2,46],19:[2,46],29:[2,46],34:[2,46],39:[2,46],44:[2,46],47:[2,46],48:[2,46],51:[2,46],55:[2,46],60:[2,46]},{4:38,6:3,14:[2,46],15:[2,46],19:[2,46],29:[2,46],34:[2,46],44:[2,46],47:[2,46],48:[2,46],51:[2,46],55:[2,46],60:[2,46]},{13:40,15:[1,20],17:39},{20:42,56:41,64:43,65:[1,44],72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{4:45,6:3,14:[2,46],15:[2,46],19:[2,46],29:[2,46],34:[2,46],47:[2,46],48:[2,46],51:[2,46],55:[2,46],60:[2,46]},{5:[2,10],14:[2,10],15:[2,10],18:[2,10],19:[2,10],29:[2,10],34:[2,10],39:[2,10],44:[2,10],47:[2,10],48:[2,10],51:[2,10],55:[2,10],60:[2,10]},{20:46,72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{20:47,72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{20:48,72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{20:42,56:49,64:43,65:[1,44],72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{33:[2,78],49:50,65:[2,78],72:[2,78],80:[2,78],81:[2,78],82:[2,78],83:[2,78],84:[2,78],85:[2,78]},{23:[2,33],33:[2,33],54:[2,33],65:[2,33],68:[2,33],72:[2,33],75:[2,33],80:[2,33],81:[2,33],82:[2,33],83:[2,33],84:[2,33],85:[2,33]},{23:[2,34],33:[2,34],54:[2,34],65:[2,34],68:[2,34],72:[2,34],75:[2,34],80:[2,34],81:[2,34],82:[2,34],83:[2,34],84:[2,34],85:[2,34]},{23:[2,35],33:[2,35],54:[2,35],65:[2,35],68:[2,35],72:[2,35],75:[2,35],80:[2,35],81:[2,35],82:[2,35],83:[2,35],84:[2,35],85:[2,35]},{23:[2,36],33:[2,36],54:[2,36],65:[2,36],68:[2,36],72:[2,36],75:[2,36],80:[2,36],81:[2,36],82:[2,36],83:[2,36],84:[2,36],85:[2,36]},{23:[2,37],33:[2,37],54:[2,37],65:[2,37],68:[2,37],72:[2,37],75:[2,37],80:[2,37],81:[2,37],82:[2,37],83:[2,37],84:[2,37],85:[2,37]},{23:[2,38],33:[2,38],54:[2,38],65:[2,38],68:[2,38],72:[2,38],75:[2,38],80:[2,38],81:[2,38],82:[2,38],83:[2,38],84:[2,38],85:[2,38]},{23:[2,39],33:[2,39],54:[2,39],65:[2,39],68:[2,39],72:[2,39],75:[2,39],80:[2,39],81:[2,39],82:[2,39],83:[2,39],84:[2,39],85:[2,39]},{23:[2,43],33:[2,43],54:[2,43],65:[2,43],68:[2,43],72:[2,43],75:[2,43],80:[2,43],81:[2,43],82:[2,43],83:[2,43],84:[2,43],85:[2,43],87:[1,51]},{72:[1,35],86:52},{23:[2,45],33:[2,45],54:[2,45],65:[2,45],68:[2,45],72:[2,45],75:[2,45],80:[2,45],81:[2,45],82:[2,45],83:[2,45],84:[2,45],85:[2,45],87:[2,45]},{52:53,54:[2,82],65:[2,82],72:[2,82],80:[2,82],81:[2,82],82:[2,82],83:[2,82],84:[2,82],85:[2,82]},{25:54,38:56,39:[1,58],43:57,44:[1,59],45:55,47:[2,54]},{28:60,43:61,44:[1,59],47:[2,56]},{13:63,15:[1,20],18:[1,62]},{15:[2,48],18:[2,48]},{33:[2,86],57:64,65:[2,86],72:[2,86],80:[2,86],81:[2,86],82:[2,86],83:[2,86],84:[2,86],85:[2,86]},{33:[2,40],65:[2,40],72:[2,40],80:[2,40],81:[2,40],82:[2,40],83:[2,40],84:[2,40],85:[2,40]},{33:[2,41],65:[2,41],72:[2,41],80:[2,41],81:[2,41],82:[2,41],83:[2,41],84:[2,41],85:[2,41]},{20:65,72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{26:66,47:[1,67]},{30:68,33:[2,58],65:[2,58],72:[2,58],75:[2,58],80:[2,58],81:[2,58],82:[2,58],83:[2,58],84:[2,58],85:[2,58]},{33:[2,64],35:69,65:[2,64],72:[2,64],75:[2,64],80:[2,64],81:[2,64],82:[2,64],83:[2,64],84:[2,64],85:[2,64]},{21:70,23:[2,50],65:[2,50],72:[2,50],80:[2,50],81:[2,50],82:[2,50],83:[2,50],84:[2,50],85:[2,50]},{33:[2,90],61:71,65:[2,90],72:[2,90],80:[2,90],81:[2,90],82:[2,90],83:[2,90],84:[2,90],85:[2,90]},{20:75,33:[2,80],50:72,63:73,64:76,65:[1,44],69:74,70:77,71:78,72:[1,79],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{72:[1,80]},{23:[2,42],33:[2,42],54:[2,42],65:[2,42],68:[2,42],72:[2,42],75:[2,42],80:[2,42],81:[2,42],82:[2,42],83:[2,42],84:[2,42],85:[2,42],87:[1,51]},{20:75,53:81,54:[2,84],63:82,64:76,65:[1,44],69:83,70:77,71:78,72:[1,79],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{26:84,47:[1,67]},{47:[2,55]},{4:85,6:3,14:[2,46],15:[2,46],19:[2,46],29:[2,46],34:[2,46],39:[2,46],44:[2,46],47:[2,46],48:[2,46],51:[2,46],55:[2,46],60:[2,46]},{47:[2,20]},{20:86,72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{4:87,6:3,14:[2,46],15:[2,46],19:[2,46],29:[2,46],34:[2,46],47:[2,46],48:[2,46],51:[2,46],55:[2,46],60:[2,46]},{26:88,47:[1,67]},{47:[2,57]},{5:[2,11],14:[2,11],15:[2,11],19:[2,11],29:[2,11],34:[2,11],39:[2,11],44:[2,11],47:[2,11],48:[2,11],51:[2,11],55:[2,11],60:[2,11]},{15:[2,49],18:[2,49]},{20:75,33:[2,88],58:89,63:90,64:76,65:[1,44],69:91,70:77,71:78,72:[1,79],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{65:[2,94],66:92,68:[2,94],72:[2,94],80:[2,94],81:[2,94],82:[2,94],83:[2,94],84:[2,94],85:[2,94]},{5:[2,25],14:[2,25],15:[2,25],19:[2,25],29:[2,25],34:[2,25],39:[2,25],44:[2,25],47:[2,25],48:[2,25],51:[2,25],55:[2,25],60:[2,25]},{20:93,72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{20:75,31:94,33:[2,60],63:95,64:76,65:[1,44],69:96,70:77,71:78,72:[1,79],75:[2,60],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{20:75,33:[2,66],36:97,63:98,64:76,65:[1,44],69:99,70:77,71:78,72:[1,79],75:[2,66],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{20:75,22:100,23:[2,52],63:101,64:76,65:[1,44],69:102,70:77,71:78,72:[1,79],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{20:75,33:[2,92],62:103,63:104,64:76,65:[1,44],69:105,70:77,71:78,72:[1,79],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{33:[1,106]},{33:[2,79],65:[2,79],72:[2,79],80:[2,79],81:[2,79],82:[2,79],83:[2,79],84:[2,79],85:[2,79]},{33:[2,81]},{23:[2,27],33:[2,27],54:[2,27],65:[2,27],68:[2,27],72:[2,27],75:[2,27],80:[2,27],81:[2,27],82:[2,27],83:[2,27],84:[2,27],85:[2,27]},{23:[2,28],33:[2,28],54:[2,28],65:[2,28],68:[2,28],72:[2,28],75:[2,28],80:[2,28],81:[2,28],82:[2,28],83:[2,28],84:[2,28],85:[2,28]},{23:[2,30],33:[2,30],54:[2,30],68:[2,30],71:107,72:[1,108],75:[2,30]},{23:[2,98],33:[2,98],54:[2,98],68:[2,98],72:[2,98],75:[2,98]},{23:[2,45],33:[2,45],54:[2,45],65:[2,45],68:[2,45],72:[2,45],73:[1,109],75:[2,45],80:[2,45],81:[2,45],82:[2,45],83:[2,45],84:[2,45],85:[2,45],87:[2,45]},{23:[2,44],33:[2,44],54:[2,44],65:[2,44],68:[2,44],72:[2,44],75:[2,44],80:[2,44],81:[2,44],82:[2,44],83:[2,44],84:[2,44],85:[2,44],87:[2,44]},{54:[1,110]},{54:[2,83],65:[2,83],72:[2,83],80:[2,83],81:[2,83],82:[2,83],83:[2,83],84:[2,83],85:[2,83]},{54:[2,85]},{5:[2,13],14:[2,13],15:[2,13],19:[2,13],29:[2,13],34:[2,13],39:[2,13],44:[2,13],47:[2,13],48:[2,13],51:[2,13],55:[2,13],60:[2,13]},{38:56,39:[1,58],43:57,44:[1,59],45:112,46:111,47:[2,76]},{33:[2,70],40:113,65:[2,70],72:[2,70],75:[2,70],80:[2,70],81:[2,70],82:[2,70],83:[2,70],84:[2,70],85:[2,70]},{47:[2,18]},{5:[2,14],14:[2,14],15:[2,14],19:[2,14],29:[2,14],34:[2,14],39:[2,14],44:[2,14],47:[2,14],48:[2,14],51:[2,14],55:[2,14],60:[2,14]},{33:[1,114]},{33:[2,87],65:[2,87],72:[2,87],80:[2,87],81:[2,87],82:[2,87],83:[2,87],84:[2,87],
  104151. 85:[2,87]},{33:[2,89]},{20:75,63:116,64:76,65:[1,44],67:115,68:[2,96],69:117,70:77,71:78,72:[1,79],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{33:[1,118]},{32:119,33:[2,62],74:120,75:[1,121]},{33:[2,59],65:[2,59],72:[2,59],75:[2,59],80:[2,59],81:[2,59],82:[2,59],83:[2,59],84:[2,59],85:[2,59]},{33:[2,61],75:[2,61]},{33:[2,68],37:122,74:123,75:[1,121]},{33:[2,65],65:[2,65],72:[2,65],75:[2,65],80:[2,65],81:[2,65],82:[2,65],83:[2,65],84:[2,65],85:[2,65]},{33:[2,67],75:[2,67]},{23:[1,124]},{23:[2,51],65:[2,51],72:[2,51],80:[2,51],81:[2,51],82:[2,51],83:[2,51],84:[2,51],85:[2,51]},{23:[2,53]},{33:[1,125]},{33:[2,91],65:[2,91],72:[2,91],80:[2,91],81:[2,91],82:[2,91],83:[2,91],84:[2,91],85:[2,91]},{33:[2,93]},{5:[2,22],14:[2,22],15:[2,22],19:[2,22],29:[2,22],34:[2,22],39:[2,22],44:[2,22],47:[2,22],48:[2,22],51:[2,22],55:[2,22],60:[2,22]},{23:[2,99],33:[2,99],54:[2,99],68:[2,99],72:[2,99],75:[2,99]},{73:[1,109]},{20:75,63:126,64:76,65:[1,44],72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{5:[2,23],14:[2,23],15:[2,23],19:[2,23],29:[2,23],34:[2,23],39:[2,23],44:[2,23],47:[2,23],48:[2,23],51:[2,23],55:[2,23],60:[2,23]},{47:[2,19]},{47:[2,77]},{20:75,33:[2,72],41:127,63:128,64:76,65:[1,44],69:129,70:77,71:78,72:[1,79],75:[2,72],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{5:[2,24],14:[2,24],15:[2,24],19:[2,24],29:[2,24],34:[2,24],39:[2,24],44:[2,24],47:[2,24],48:[2,24],51:[2,24],55:[2,24],60:[2,24]},{68:[1,130]},{65:[2,95],68:[2,95],72:[2,95],80:[2,95],81:[2,95],82:[2,95],83:[2,95],84:[2,95],85:[2,95]},{68:[2,97]},{5:[2,21],14:[2,21],15:[2,21],19:[2,21],29:[2,21],34:[2,21],39:[2,21],44:[2,21],47:[2,21],48:[2,21],51:[2,21],55:[2,21],60:[2,21]},{33:[1,131]},{33:[2,63]},{72:[1,133],76:132},{33:[1,134]},{33:[2,69]},{15:[2,12]},{14:[2,26],15:[2,26],19:[2,26],29:[2,26],34:[2,26],47:[2,26],48:[2,26],51:[2,26],55:[2,26],60:[2,26]},{23:[2,31],33:[2,31],54:[2,31],68:[2,31],72:[2,31],75:[2,31]},{33:[2,74],42:135,74:136,75:[1,121]},{33:[2,71],65:[2,71],72:[2,71],75:[2,71],80:[2,71],81:[2,71],82:[2,71],83:[2,71],84:[2,71],85:[2,71]},{33:[2,73],75:[2,73]},{23:[2,29],33:[2,29],54:[2,29],65:[2,29],68:[2,29],72:[2,29],75:[2,29],80:[2,29],81:[2,29],82:[2,29],83:[2,29],84:[2,29],85:[2,29]},{14:[2,15],15:[2,15],19:[2,15],29:[2,15],34:[2,15],39:[2,15],44:[2,15],47:[2,15],48:[2,15],51:[2,15],55:[2,15],60:[2,15]},{72:[1,138],77:[1,137]},{72:[2,100],77:[2,100]},{14:[2,16],15:[2,16],19:[2,16],29:[2,16],34:[2,16],44:[2,16],47:[2,16],48:[2,16],51:[2,16],55:[2,16],60:[2,16]},{33:[1,139]},{33:[2,75]},{33:[2,32]},{72:[2,101],77:[2,101]},{14:[2,17],15:[2,17],19:[2,17],29:[2,17],34:[2,17],39:[2,17],44:[2,17],47:[2,17],48:[2,17],51:[2,17],55:[2,17],60:[2,17]}],defaultActions:{4:[2,1],55:[2,55],57:[2,20],61:[2,57],74:[2,81],83:[2,85],87:[2,18],91:[2,89],102:[2,53],105:[2,93],111:[2,19],112:[2,77],117:[2,97],120:[2,63],123:[2,69],124:[2,12],136:[2,75],137:[2,32]},parseError:function(a,b){throw new Error(a)},parse:function(a){function b(){var a;return a=c.lexer.lex()||1,"number"!=typeof a&&(a=c.symbols_[a]||a),a}var c=this,d=[0],e=[null],f=[],g=this.table,h="",i=0,j=0,k=0;this.lexer.setInput(a),this.lexer.yy=this.yy,this.yy.lexer=this.lexer,this.yy.parser=this,"undefined"==typeof this.lexer.yylloc&&(this.lexer.yylloc={});var l=this.lexer.yylloc;f.push(l);var m=this.lexer.options&&this.lexer.options.ranges;"function"==typeof this.yy.parseError&&(this.parseError=this.yy.parseError);for(var n,o,p,q,r,s,t,u,v,w={};;){if(p=d[d.length-1],this.defaultActions[p]?q=this.defaultActions[p]:(null!==n&&"undefined"!=typeof n||(n=b()),q=g[p]&&g[p][n]),"undefined"==typeof q||!q.length||!q[0]){var x="";if(!k){v=[];for(s in g[p])this.terminals_[s]&&s>2&&v.push("'"+this.terminals_[s]+"'");x=this.lexer.showPosition?"Parse error on line "+(i+1)+":\n"+this.lexer.showPosition()+"\nExpecting "+v.join(", ")+", got '"+(this.terminals_[n]||n)+"'":"Parse error on line "+(i+1)+": Unexpected "+(1==n?"end of input":"'"+(this.terminals_[n]||n)+"'"),this.parseError(x,{text:this.lexer.match,token:this.terminals_[n]||n,line:this.lexer.yylineno,loc:l,expected:v})}}if(q[0]instanceof Array&&q.length>1)throw new Error("Parse Error: multiple actions possible at state: "+p+", token: "+n);switch(q[0]){case 1:d.push(n),e.push(this.lexer.yytext),f.push(this.lexer.yylloc),d.push(q[1]),n=null,o?(n=o,o=null):(j=this.lexer.yyleng,h=this.lexer.yytext,i=this.lexer.yylineno,l=this.lexer.yylloc,k>0&&k--);break;case 2:if(t=this.productions_[q[1]][1],w.$=e[e.length-t],w._$={first_line:f[f.length-(t||1)].first_line,last_line:f[f.length-1].last_line,first_column:f[f.length-(t||1)].first_column,last_column:f[f.length-1].last_column},m&&(w._$.range=[f[f.length-(t||1)].range[0],f[f.length-1].range[1]]),r=this.performAction.call(w,h,j,i,this.yy,q[1],e,f),"undefined"!=typeof r)return r;t&&(d=d.slice(0,-1*t*2),e=e.slice(0,-1*t),f=f.slice(0,-1*t)),d.push(this.productions_[q[1]][0]),e.push(w.$),f.push(w._$),u=g[d[d.length-2]][d[d.length-1]],d.push(u);break;case 3:return!0}}return!0}},c=function(){var a={EOF:1,parseError:function(a,b){if(!this.yy.parser)throw new Error(a);this.yy.parser.parseError(a,b)},setInput:function(a){return this._input=a,this._more=this._less=this.done=!1,this.yylineno=this.yyleng=0,this.yytext=this.matched=this.match="",this.conditionStack=["INITIAL"],this.yylloc={first_line:1,first_column:0,last_line:1,last_column:0},this.options.ranges&&(this.yylloc.range=[0,0]),this.offset=0,this},input:function(){var a=this._input[0];this.yytext+=a,this.yyleng++,this.offset++,this.match+=a,this.matched+=a;var b=a.match(/(?:\r\n?|\n).*/g);return b?(this.yylineno++,this.yylloc.last_line++):this.yylloc.last_column++,this.options.ranges&&this.yylloc.range[1]++,this._input=this._input.slice(1),a},unput:function(a){var b=a.length,c=a.split(/(?:\r\n?|\n)/g);this._input=a+this._input,this.yytext=this.yytext.substr(0,this.yytext.length-b-1),this.offset-=b;var d=this.match.split(/(?:\r\n?|\n)/g);this.match=this.match.substr(0,this.match.length-1),this.matched=this.matched.substr(0,this.matched.length-1),c.length-1&&(this.yylineno-=c.length-1);var e=this.yylloc.range;return this.yylloc={first_line:this.yylloc.first_line,last_line:this.yylineno+1,first_column:this.yylloc.first_column,last_column:c?(c.length===d.length?this.yylloc.first_column:0)+d[d.length-c.length].length-c[0].length:this.yylloc.first_column-b},this.options.ranges&&(this.yylloc.range=[e[0],e[0]+this.yyleng-b]),this},more:function(){return this._more=!0,this},less:function(a){this.unput(this.match.slice(a))},pastInput:function(){var a=this.matched.substr(0,this.matched.length-this.match.length);return(a.length>20?"...":"")+a.substr(-20).replace(/\n/g,"")},upcomingInput:function(){var a=this.match;return a.length<20&&(a+=this._input.substr(0,20-a.length)),(a.substr(0,20)+(a.length>20?"...":"")).replace(/\n/g,"")},showPosition:function(){var a=this.pastInput(),b=new Array(a.length+1).join("-");return a+this.upcomingInput()+"\n"+b+"^"},next:function(){if(this.done)return this.EOF;this._input||(this.done=!0);var a,b,c,d,e;this._more||(this.yytext="",this.match="");for(var f=this._currentRules(),g=0;g<f.length&&(c=this._input.match(this.rules[f[g]]),!c||b&&!(c[0].length>b[0].length)||(b=c,d=g,this.options.flex));g++);return b?(e=b[0].match(/(?:\r\n?|\n).*/g),e&&(this.yylineno+=e.length),this.yylloc={first_line:this.yylloc.last_line,last_line:this.yylineno+1,first_column:this.yylloc.last_column,last_column:e?e[e.length-1].length-e[e.length-1].match(/\r?\n?/)[0].length:this.yylloc.last_column+b[0].length},this.yytext+=b[0],this.match+=b[0],this.matches=b,this.yyleng=this.yytext.length,this.options.ranges&&(this.yylloc.range=[this.offset,this.offset+=this.yyleng]),this._more=!1,this._input=this._input.slice(b[0].length),this.matched+=b[0],a=this.performAction.call(this,this.yy,this,f[d],this.conditionStack[this.conditionStack.length-1]),this.done&&this._input&&(this.done=!1),a?a:void 0):""===this._input?this.EOF:this.parseError("Lexical error on line "+(this.yylineno+1)+". Unrecognized text.\n"+this.showPosition(),{text:"",token:null,line:this.yylineno})},lex:function(){var a=this.next();return"undefined"!=typeof a?a:this.lex()},begin:function(a){this.conditionStack.push(a)},popState:function(){return this.conditionStack.pop()},_currentRules:function(){return this.conditions[this.conditionStack[this.conditionStack.length-1]].rules},topState:function(){return this.conditionStack[this.conditionStack.length-2]},pushState:function(a){this.begin(a)}};return a.options={},a.performAction=function(a,b,c,d){function e(a,c){return b.yytext=b.yytext.substr(a,b.yyleng-c)}switch(c){case 0:if("\\\\"===b.yytext.slice(-2)?(e(0,1),this.begin("mu")):"\\"===b.yytext.slice(-1)?(e(0,1),this.begin("emu")):this.begin("mu"),b.yytext)return 15;break;case 1:return 15;case 2:return this.popState(),15;case 3:return this.begin("raw"),15;case 4:return this.popState(),"raw"===this.conditionStack[this.conditionStack.length-1]?15:(b.yytext=b.yytext.substr(5,b.yyleng-9),"END_RAW_BLOCK");case 5:return 15;case 6:return this.popState(),14;case 7:return 65;case 8:return 68;case 9:return 19;case 10:return this.popState(),this.begin("raw"),23;case 11:return 55;case 12:return 60;case 13:return 29;case 14:return 47;case 15:return this.popState(),44;case 16:return this.popState(),44;case 17:return 34;case 18:return 39;case 19:return 51;case 20:return 48;case 21:this.unput(b.yytext),this.popState(),this.begin("com");break;case 22:return this.popState(),14;case 23:return 48;case 24:return 73;case 25:return 72;case 26:return 72;case 27:return 87;case 28:break;case 29:return this.popState(),54;case 30:return this.popState(),33;case 31:return b.yytext=e(1,2).replace(/\\"/g,'"'),80;case 32:return b.yytext=e(1,2).replace(/\\'/g,"'"),80;case 33:return 85;case 34:return 82;case 35:return 82;case 36:return 83;case 37:return 84;case 38:return 81;case 39:return 75;case 40:return 77;case 41:return 72;case 42:return b.yytext=b.yytext.replace(/\\([\\\]])/g,"$1"),72;case 43:return"INVALID";case 44:return 5}},a.rules=[/^(?:[^\x00]*?(?=(\{\{)))/,/^(?:[^\x00]+)/,/^(?:[^\x00]{2,}?(?=(\{\{|\\\{\{|\\\\\{\{|$)))/,/^(?:\{\{\{\{(?=[^\/]))/,/^(?:\{\{\{\{\/[^\s!"#%-,\.\/;->@\[-\^`\{-~]+(?=[=}\s\/.])\}\}\}\})/,/^(?:[^\x00]*?(?=(\{\{\{\{)))/,/^(?:[\s\S]*?--(~)?\}\})/,/^(?:\()/,/^(?:\))/,/^(?:\{\{\{\{)/,/^(?:\}\}\}\})/,/^(?:\{\{(~)?>)/,/^(?:\{\{(~)?#>)/,/^(?:\{\{(~)?#\*?)/,/^(?:\{\{(~)?\/)/,/^(?:\{\{(~)?\^\s*(~)?\}\})/,/^(?:\{\{(~)?\s*else\s*(~)?\}\})/,/^(?:\{\{(~)?\^)/,/^(?:\{\{(~)?\s*else\b)/,/^(?:\{\{(~)?\{)/,/^(?:\{\{(~)?&)/,/^(?:\{\{(~)?!--)/,/^(?:\{\{(~)?![\s\S]*?\}\})/,/^(?:\{\{(~)?\*?)/,/^(?:=)/,/^(?:\.\.)/,/^(?:\.(?=([=~}\s\/.)|])))/,/^(?:[\/.])/,/^(?:\s+)/,/^(?:\}(~)?\}\})/,/^(?:(~)?\}\})/,/^(?:"(\\["]|[^"])*")/,/^(?:'(\\[']|[^'])*')/,/^(?:@)/,/^(?:true(?=([~}\s)])))/,/^(?:false(?=([~}\s)])))/,/^(?:undefined(?=([~}\s)])))/,/^(?:null(?=([~}\s)])))/,/^(?:-?[0-9]+(?:\.[0-9]+)?(?=([~}\s)])))/,/^(?:as\s+\|)/,/^(?:\|)/,/^(?:([^\s!"#%-,\.\/;->@\[-\^`\{-~]+(?=([=~}\s\/.)|]))))/,/^(?:\[(\\\]|[^\]])*\])/,/^(?:.)/,/^(?:$)/],a.conditions={mu:{rules:[7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44],inclusive:!1},emu:{rules:[2],inclusive:!1},com:{rules:[6],inclusive:!1},raw:{rules:[3,4,5],inclusive:!1},INITIAL:{rules:[0,1,44],inclusive:!0}},a}();return b.lexer=c,a.prototype=b,b.Parser=a,new a}();b["default"]=c,a.exports=b["default"]},function(a,b,c){"use strict";function d(){var a=arguments.length<=0||void 0===arguments[0]?{}:arguments[0];this.options=a}function e(a,b,c){void 0===b&&(b=a.length);var d=a[b-1],e=a[b-2];return d?"ContentStatement"===d.type?(e||!c?/\r?\n\s*?$/:/(^|\r?\n)\s*?$/).test(d.original):void 0:c}function f(a,b,c){void 0===b&&(b=-1);var d=a[b+1],e=a[b+2];return d?"ContentStatement"===d.type?(e||!c?/^\s*?\r?\n/:/^\s*?(\r?\n|$)/).test(d.original):void 0:c}function g(a,b,c){var d=a[null==b?0:b+1];if(d&&"ContentStatement"===d.type&&(c||!d.rightStripped)){var e=d.value;d.value=d.value.replace(c?/^\s+/:/^[ \t]*\r?\n?/,""),d.rightStripped=d.value!==e}}function h(a,b,c){var d=a[null==b?a.length-1:b-1];if(d&&"ContentStatement"===d.type&&(c||!d.leftStripped)){var e=d.value;return d.value=d.value.replace(c?/\s+$/:/[ \t]+$/,""),d.leftStripped=d.value!==e,d.leftStripped}}var i=c(1)["default"];b.__esModule=!0;var j=c(39),k=i(j);d.prototype=new k["default"],d.prototype.Program=function(a){var b=!this.options.ignoreStandalone,c=!this.isRootSeen;this.isRootSeen=!0;for(var d=a.body,i=0,j=d.length;i<j;i++){var k=d[i],l=this.accept(k);if(l){var m=e(d,i,c),n=f(d,i,c),o=l.openStandalone&&m,p=l.closeStandalone&&n,q=l.inlineStandalone&&m&&n;l.close&&g(d,i,!0),l.open&&h(d,i,!0),b&&q&&(g(d,i),h(d,i)&&"PartialStatement"===k.type&&(k.indent=/([ \t]+$)/.exec(d[i-1].original)[1])),b&&o&&(g((k.program||k.inverse).body),h(d,i)),b&&p&&(g(d,i),h((k.inverse||k.program).body))}}return a},d.prototype.BlockStatement=d.prototype.DecoratorBlock=d.prototype.PartialBlockStatement=function(a){this.accept(a.program),this.accept(a.inverse);var b=a.program||a.inverse,c=a.program&&a.inverse,d=c,i=c;if(c&&c.chained)for(d=c.body[0].program;i.chained;)i=i.body[i.body.length-1].program;var j={open:a.openStrip.open,close:a.closeStrip.close,openStandalone:f(b.body),closeStandalone:e((d||b).body)};if(a.openStrip.close&&g(b.body,null,!0),c){var k=a.inverseStrip;k.open&&h(b.body,null,!0),k.close&&g(d.body,null,!0),a.closeStrip.open&&h(i.body,null,!0),!this.options.ignoreStandalone&&e(b.body)&&f(d.body)&&(h(b.body),g(d.body))}else a.closeStrip.open&&h(b.body,null,!0);return j},d.prototype.Decorator=d.prototype.MustacheStatement=function(a){return a.strip},d.prototype.PartialStatement=d.prototype.CommentStatement=function(a){var b=a.strip||{};return{inlineStandalone:!0,open:b.open,close:b.close}},b["default"]=d,a.exports=b["default"]},function(a,b,c){"use strict";function d(){this.parents=[]}function e(a){this.acceptRequired(a,"path"),this.acceptArray(a.params),this.acceptKey(a,"hash")}function f(a){e.call(this,a),this.acceptKey(a,"program"),this.acceptKey(a,"inverse")}function g(a){this.acceptRequired(a,"name"),this.acceptArray(a.params),this.acceptKey(a,"hash")}var h=c(1)["default"];b.__esModule=!0;var i=c(6),j=h(i);d.prototype={constructor:d,mutating:!1,acceptKey:function(a,b){var c=this.accept(a[b]);if(this.mutating){if(c&&!d.prototype[c.type])throw new j["default"]('Unexpected node type "'+c.type+'" found when accepting '+b+" on "+a.type);a[b]=c}},acceptRequired:function(a,b){if(this.acceptKey(a,b),!a[b])throw new j["default"](a.type+" requires "+b)},acceptArray:function(a){for(var b=0,c=a.length;b<c;b++)this.acceptKey(a,b),a[b]||(a.splice(b,1),b--,c--)},accept:function(a){if(a){if(!this[a.type])throw new j["default"]("Unknown type: "+a.type,a);this.current&&this.parents.unshift(this.current),this.current=a;var b=this[a.type](a);return this.current=this.parents.shift(),!this.mutating||b?b:b!==!1?a:void 0}},Program:function(a){this.acceptArray(a.body)},MustacheStatement:e,Decorator:e,BlockStatement:f,DecoratorBlock:f,PartialStatement:g,PartialBlockStatement:function(a){g.call(this,a),this.acceptKey(a,"program")},ContentStatement:function(){},CommentStatement:function(){},SubExpression:e,PathExpression:function(){},StringLiteral:function(){},NumberLiteral:function(){},BooleanLiteral:function(){},UndefinedLiteral:function(){},NullLiteral:function(){},Hash:function(a){this.acceptArray(a.pairs)},HashPair:function(a){this.acceptRequired(a,"value")}},b["default"]=d,a.exports=b["default"]},function(a,b,c){"use strict";function d(a,b){if(b=b.path?b.path.original:b,a.path.original!==b){var c={loc:a.path.loc};throw new q["default"](a.path.original+" doesn't match "+b,c)}}function e(a,b){this.source=a,this.start={line:b.first_line,column:b.first_column},this.end={line:b.last_line,column:b.last_column}}function f(a){return/^\[.*\]$/.test(a)?a.substr(1,a.length-2):a}function g(a,b){return{open:"~"===a.charAt(2),close:"~"===b.charAt(b.length-3)}}function h(a){return a.replace(/^\{\{~?\!-?-?/,"").replace(/-?-?~?\}\}$/,"")}function i(a,b,c){c=this.locInfo(c);for(var d=a?"@":"",e=[],f=0,g="",h=0,i=b.length;h<i;h++){var j=b[h].part,k=b[h].original!==j;if(d+=(b[h].separator||"")+j,k||".."!==j&&"."!==j&&"this"!==j)e.push(j);else{if(e.length>0)throw new q["default"]("Invalid path: "+d,{loc:c});".."===j&&(f++,g+="../")}}return{type:"PathExpression",data:a,depth:f,parts:e,original:d,loc:c}}function j(a,b,c,d,e,f){var g=d.charAt(3)||d.charAt(2),h="{"!==g&&"&"!==g,i=/\*/.test(d);return{type:i?"Decorator":"MustacheStatement",path:a,params:b,hash:c,escaped:h,strip:e,loc:this.locInfo(f)}}function k(a,b,c,e){d(a,c),e=this.locInfo(e);var f={type:"Program",body:b,strip:{},loc:e};return{type:"BlockStatement",path:a.path,params:a.params,hash:a.hash,program:f,openStrip:{},inverseStrip:{},closeStrip:{},loc:e}}function l(a,b,c,e,f,g){e&&e.path&&d(a,e);var h=/\*/.test(a.open);b.blockParams=a.blockParams;var i=void 0,j=void 0;if(c){if(h)throw new q["default"]("Unexpected inverse block on decorator",c);c.chain&&(c.program.body[0].closeStrip=e.strip),j=c.strip,i=c.program}return f&&(f=i,i=b,b=f),{type:h?"DecoratorBlock":"BlockStatement",path:a.path,params:a.params,hash:a.hash,program:b,inverse:i,openStrip:a.strip,inverseStrip:j,closeStrip:e&&e.strip,loc:this.locInfo(g)}}function m(a,b){if(!b&&a.length){var c=a[0].loc,d=a[a.length-1].loc;c&&d&&(b={source:c.source,start:{line:c.start.line,column:c.start.column},end:{line:d.end.line,column:d.end.column}})}return{type:"Program",body:a,strip:{},loc:b}}function n(a,b,c,e){return d(a,c),{type:"PartialBlockStatement",name:a.path,params:a.params,hash:a.hash,program:b,openStrip:a.strip,closeStrip:c&&c.strip,loc:this.locInfo(e)}}var o=c(1)["default"];b.__esModule=!0,b.SourceLocation=e,b.id=f,b.stripFlags=g,b.stripComment=h,b.preparePath=i,b.prepareMustache=j,b.prepareRawBlock=k,b.prepareBlock=l,b.prepareProgram=m,b.preparePartialBlock=n;var p=c(6),q=o(p)},function(a,b,c){"use strict";function d(){}function e(a,b,c){if(null==a||"string"!=typeof a&&"Program"!==a.type)throw new k["default"]("You must pass a string or Handlebars AST to Handlebars.precompile. You passed "+a);b=b||{},"data"in b||(b.data=!0),b.compat&&(b.useDepths=!0);var d=c.parse(a,b),e=(new c.Compiler).compile(d,b);return(new c.JavaScriptCompiler).compile(e,b)}function f(a,b,c){function d(){var d=c.parse(a,b),e=(new c.Compiler).compile(d,b),f=(new c.JavaScriptCompiler).compile(e,b,void 0,!0);return c.template(f)}function e(a,b){return f||(f=d()),f.call(this,a,b)}if(void 0===b&&(b={}),null==a||"string"!=typeof a&&"Program"!==a.type)throw new k["default"]("You must pass a string or Handlebars AST to Handlebars.compile. You passed "+a);b=l.extend({},b),"data"in b||(b.data=!0),b.compat&&(b.useDepths=!0);var f=void 0;return e._setup=function(a){return f||(f=d()),f._setup(a)},e._child=function(a,b,c,e){return f||(f=d()),f._child(a,b,c,e)},e}function g(a,b){if(a===b)return!0;if(l.isArray(a)&&l.isArray(b)&&a.length===b.length){for(var c=0;c<a.length;c++)if(!g(a[c],b[c]))return!1;return!0}}function h(a){if(!a.path.parts){var b=a.path;a.path={type:"PathExpression",data:!1,depth:0,parts:[b.original+""],original:b.original+"",loc:b.loc}}}var i=c(1)["default"];b.__esModule=!0,b.Compiler=d,b.precompile=e,b.compile=f;var j=c(6),k=i(j),l=c(5),m=c(35),n=i(m),o=[].slice;d.prototype={compiler:d,equals:function(a){var b=this.opcodes.length;if(a.opcodes.length!==b)return!1;for(var c=0;c<b;c++){var d=this.opcodes[c],e=a.opcodes[c];if(d.opcode!==e.opcode||!g(d.args,e.args))return!1}b=this.children.length;for(var c=0;c<b;c++)if(!this.children[c].equals(a.children[c]))return!1;return!0},guid:0,compile:function(a,b){this.sourceNode=[],this.opcodes=[],this.children=[],this.options=b,this.stringParams=b.stringParams,this.trackIds=b.trackIds,b.blockParams=b.blockParams||[];var c=b.knownHelpers;if(b.knownHelpers={helperMissing:!0,blockHelperMissing:!0,each:!0,"if":!0,unless:!0,"with":!0,log:!0,lookup:!0},c)for(var d in c)d in c&&(this.options.knownHelpers[d]=c[d]);return this.accept(a)},compileProgram:function(a){var b=new this.compiler,c=b.compile(a,this.options),d=this.guid++;return this.usePartial=this.usePartial||c.usePartial,this.children[d]=c,this.useDepths=this.useDepths||c.useDepths,d},accept:function(a){if(!this[a.type])throw new k["default"]("Unknown type: "+a.type,a);this.sourceNode.unshift(a);var b=this[a.type](a);return this.sourceNode.shift(),b},Program:function(a){this.options.blockParams.unshift(a.blockParams);for(var b=a.body,c=b.length,d=0;d<c;d++)this.accept(b[d]);return this.options.blockParams.shift(),this.isSimple=1===c,this.blockParams=a.blockParams?a.blockParams.length:0,this},BlockStatement:function(a){h(a);var b=a.program,c=a.inverse;b=b&&this.compileProgram(b),c=c&&this.compileProgram(c);var d=this.classifySexpr(a);"helper"===d?this.helperSexpr(a,b,c):"simple"===d?(this.simpleSexpr(a),this.opcode("pushProgram",b),this.opcode("pushProgram",c),this.opcode("emptyHash"),this.opcode("blockValue",a.path.original)):(this.ambiguousSexpr(a,b,c),this.opcode("pushProgram",b),this.opcode("pushProgram",c),this.opcode("emptyHash"),this.opcode("ambiguousBlockValue")),this.opcode("append")},DecoratorBlock:function(a){var b=a.program&&this.compileProgram(a.program),c=this.setupFullMustacheParams(a,b,void 0),d=a.path;this.useDecorators=!0,this.opcode("registerDecorator",c.length,d.original)},PartialStatement:function(a){this.usePartial=!0;var b=a.program;b&&(b=this.compileProgram(a.program));var c=a.params;if(c.length>1)throw new k["default"]("Unsupported number of partial arguments: "+c.length,a);c.length||(this.options.explicitPartialContext?this.opcode("pushLiteral","undefined"):c.push({type:"PathExpression",parts:[],depth:0}));var d=a.name.original,e="SubExpression"===a.name.type;e&&this.accept(a.name),this.setupFullMustacheParams(a,b,void 0,!0);var f=a.indent||"";this.options.preventIndent&&f&&(this.opcode("appendContent",f),f=""),this.opcode("invokePartial",e,d,f),this.opcode("append")},PartialBlockStatement:function(a){this.PartialStatement(a)},MustacheStatement:function(a){this.SubExpression(a),a.escaped&&!this.options.noEscape?this.opcode("appendEscaped"):this.opcode("append")},Decorator:function(a){this.DecoratorBlock(a)},ContentStatement:function(a){a.value&&this.opcode("appendContent",a.value)},CommentStatement:function(){},SubExpression:function(a){h(a);var b=this.classifySexpr(a);"simple"===b?this.simpleSexpr(a):"helper"===b?this.helperSexpr(a):this.ambiguousSexpr(a)},ambiguousSexpr:function(a,b,c){var d=a.path,e=d.parts[0],f=null!=b||null!=c;this.opcode("getContext",d.depth),this.opcode("pushProgram",b),this.opcode("pushProgram",c),d.strict=!0,this.accept(d),this.opcode("invokeAmbiguous",e,f)},simpleSexpr:function(a){var b=a.path;b.strict=!0,this.accept(b),this.opcode("resolvePossibleLambda")},helperSexpr:function(a,b,c){var d=this.setupFullMustacheParams(a,b,c),e=a.path,f=e.parts[0];if(this.options.knownHelpers[f])this.opcode("invokeKnownHelper",d.length,f);else{if(this.options.knownHelpersOnly)throw new k["default"]("You specified knownHelpersOnly, but used the unknown helper "+f,a);e.strict=!0,e.falsy=!0,this.accept(e),this.opcode("invokeHelper",d.length,e.original,n["default"].helpers.simpleId(e))}},PathExpression:function(a){this.addDepth(a.depth),this.opcode("getContext",a.depth);var b=a.parts[0],c=n["default"].helpers.scopedId(a),d=!a.depth&&!c&&this.blockParamIndex(b);d?this.opcode("lookupBlockParam",d,a.parts):b?a.data?(this.options.data=!0,this.opcode("lookupData",a.depth,a.parts,a.strict)):this.opcode("lookupOnContext",a.parts,a.falsy,a.strict,c):this.opcode("pushContext")},StringLiteral:function(a){this.opcode("pushString",a.value)},NumberLiteral:function(a){this.opcode("pushLiteral",a.value)},BooleanLiteral:function(a){this.opcode("pushLiteral",a.value)},UndefinedLiteral:function(){this.opcode("pushLiteral","undefined")},NullLiteral:function(){this.opcode("pushLiteral","null")},Hash:function(a){var b=a.pairs,c=0,d=b.length;for(this.opcode("pushHash");c<d;c++)this.pushParam(b[c].value);for(;c--;)this.opcode("assignToHash",b[c].key);this.opcode("popHash")},opcode:function(a){this.opcodes.push({opcode:a,args:o.call(arguments,1),loc:this.sourceNode[0].loc})},addDepth:function(a){a&&(this.useDepths=!0)},classifySexpr:function(a){var b=n["default"].helpers.simpleId(a.path),c=b&&!!this.blockParamIndex(a.path.parts[0]),d=!c&&n["default"].helpers.helperExpression(a),e=!c&&(d||b);if(e&&!d){var f=a.path.parts[0],g=this.options;g.knownHelpers[f]?d=!0:g.knownHelpersOnly&&(e=!1)}return d?"helper":e?"ambiguous":"simple"},pushParams:function(a){for(var b=0,c=a.length;b<c;b++)this.pushParam(a[b])},pushParam:function(a){var b=null!=a.value?a.value:a.original||"";if(this.stringParams)b.replace&&(b=b.replace(/^(\.?\.\/)*/g,"").replace(/\//g,".")),a.depth&&this.addDepth(a.depth),this.opcode("getContext",a.depth||0),this.opcode("pushStringParam",b,a.type),"SubExpression"===a.type&&this.accept(a);else{if(this.trackIds){var c=void 0;if(!a.parts||n["default"].helpers.scopedId(a)||a.depth||(c=this.blockParamIndex(a.parts[0])),c){var d=a.parts.slice(1).join(".");this.opcode("pushId","BlockParam",c,d)}else b=a.original||b,b.replace&&(b=b.replace(/^this(?:\.|$)/,"").replace(/^\.\//,"").replace(/^\.$/,"")),this.opcode("pushId",a.type,b)}this.accept(a)}},setupFullMustacheParams:function(a,b,c,d){var e=a.params;return this.pushParams(e),this.opcode("pushProgram",b),this.opcode("pushProgram",c),a.hash?this.accept(a.hash):this.opcode("emptyHash",d),e},blockParamIndex:function(a){for(var b=0,c=this.options.blockParams.length;b<c;b++){var d=this.options.blockParams[b],e=d&&l.indexOf(d,a);if(d&&e>=0)return[b,e]}}}},function(a,b,c){"use strict";function d(a){this.value=a}function e(){}function f(a,b,c,d){var e=b.popStack(),f=0,g=c.length;for(a&&g--;f<g;f++)e=b.nameLookup(e,c[f],d);return a?[b.aliasable("container.strict"),"(",e,", ",b.quotedString(c[f]),")"]:e}var g=c(1)["default"];b.__esModule=!0;var h=c(4),i=c(6),j=g(i),k=c(5),l=c(43),m=g(l);e.prototype={nameLookup:function(a,b){return e.isValidJavaScriptVariableName(b)?[a,".",b]:[a,"[",JSON.stringify(b),"]"]},depthedLookup:function(a){return[this.aliasable("container.lookup"),'(depths, "',a,'")']},compilerInfo:function(){var a=h.COMPILER_REVISION,b=h.REVISION_CHANGES[a];return[a,b]},appendToBuffer:function(a,b,c){return k.isArray(a)||(a=[a]),a=this.source.wrap(a,b),this.environment.isSimple?["return ",a,";"]:c?["buffer += ",a,";"]:(a.appendToBuffer=!0,a)},initializeBuffer:function(){return this.quotedString("")},compile:function(a,b,c,d){this.environment=a,this.options=b,this.stringParams=this.options.stringParams,this.trackIds=this.options.trackIds,this.precompile=!d,this.name=this.environment.name,this.isChild=!!c,this.context=c||{decorators:[],programs:[],environments:[]},this.preamble(),this.stackSlot=0,this.stackVars=[],this.aliases={},this.registers={list:[]},this.hashes=[],this.compileStack=[],this.inlineStack=[],this.blockParams=[],this.compileChildren(a,b),this.useDepths=this.useDepths||a.useDepths||a.useDecorators||this.options.compat,this.useBlockParams=this.useBlockParams||a.useBlockParams;var e=a.opcodes,f=void 0,g=void 0,h=void 0,i=void 0;for(h=0,i=e.length;h<i;h++)f=e[h],this.source.currentLocation=f.loc,g=g||f.loc,this[f.opcode].apply(this,f.args);if(this.source.currentLocation=g,this.pushSource(""),this.stackSlot||this.inlineStack.length||this.compileStack.length)throw new j["default"]("Compile completed with content left on stack");this.decorators.isEmpty()?this.decorators=void 0:(this.useDecorators=!0,this.decorators.prepend("var decorators = container.decorators;\n"),this.decorators.push("return fn;"),d?this.decorators=Function.apply(this,["fn","props","container","depth0","data","blockParams","depths",this.decorators.merge()]):(this.decorators.prepend("function(fn, props, container, depth0, data, blockParams, depths) {\n"),this.decorators.push("}\n"),this.decorators=this.decorators.merge()));var k=this.createFunctionContext(d);if(this.isChild)return k;var l={compiler:this.compilerInfo(),main:k};this.decorators&&(l.main_d=this.decorators,l.useDecorators=!0);var m=this.context,n=m.programs,o=m.decorators;for(h=0,i=n.length;h<i;h++)n[h]&&(l[h]=n[h],o[h]&&(l[h+"_d"]=o[h],l.useDecorators=!0));return this.environment.usePartial&&(l.usePartial=!0),this.options.data&&(l.useData=!0),this.useDepths&&(l.useDepths=!0),this.useBlockParams&&(l.useBlockParams=!0),this.options.compat&&(l.compat=!0),d?l.compilerOptions=this.options:(l.compiler=JSON.stringify(l.compiler),this.source.currentLocation={start:{line:1,column:0}},l=this.objectLiteral(l),b.srcName?(l=l.toStringWithSourceMap({file:b.destName}),l.map=l.map&&l.map.toString()):l=l.toString()),l},preamble:function(){this.lastContext=0,this.source=new m["default"](this.options.srcName),this.decorators=new m["default"](this.options.srcName)},createFunctionContext:function(a){var b="",c=this.stackVars.concat(this.registers.list);c.length>0&&(b+=", "+c.join(", "));var d=0;for(var e in this.aliases){var f=this.aliases[e];this.aliases.hasOwnProperty(e)&&f.children&&f.referenceCount>1&&(b+=", alias"+ ++d+"="+e,f.children[0]="alias"+d)}var g=["container","depth0","helpers","partials","data"];(this.useBlockParams||this.useDepths)&&g.push("blockParams"),this.useDepths&&g.push("depths");var h=this.mergeSource(b);return a?(g.push(h),Function.apply(this,g)):this.source.wrap(["function(",g.join(","),") {\n ",h,"}"])},mergeSource:function(a){var b=this.environment.isSimple,c=!this.forceBuffer,d=void 0,e=void 0,f=void 0,g=void 0;return this.source.each(function(a){a.appendToBuffer?(f?a.prepend(" + "):f=a,g=a):(f&&(e?f.prepend("buffer += "):d=!0,g.add(";"),f=g=void 0),e=!0,b||(c=!1))}),c?f?(f.prepend("return "),g.add(";")):e||this.source.push('return "";'):(a+=", buffer = "+(d?"":this.initializeBuffer()),f?(f.prepend("return buffer + "),g.add(";")):this.source.push("return buffer;")),a&&this.source.prepend("var "+a.substring(2)+(d?"":";\n")),this.source.merge()},blockValue:function(a){var b=this.aliasable("helpers.blockHelperMissing"),c=[this.contextName(0)];this.setupHelperArgs(a,0,c);var d=this.popStack();c.splice(1,0,d),this.push(this.source.functionCall(b,"call",c))},ambiguousBlockValue:function(){var a=this.aliasable("helpers.blockHelperMissing"),b=[this.contextName(0)];this.setupHelperArgs("",0,b,!0),this.flushInline();var c=this.topStack();b.splice(1,0,c),this.pushSource(["if (!",this.lastHelper,") { ",c," = ",this.source.functionCall(a,"call",b),"}"])},appendContent:function(a){this.pendingContent?a=this.pendingContent+a:this.pendingLocation=this.source.currentLocation,this.pendingContent=a},append:function(){if(this.isInline())this.replaceStack(function(a){return[" != null ? ",a,' : ""']}),this.pushSource(this.appendToBuffer(this.popStack()));else{var a=this.popStack();this.pushSource(["if (",a," != null) { ",this.appendToBuffer(a,void 0,!0)," }"]),this.environment.isSimple&&this.pushSource(["else { ",this.appendToBuffer("''",void 0,!0)," }"])}},appendEscaped:function(){this.pushSource(this.appendToBuffer([this.aliasable("container.escapeExpression"),"(",this.popStack(),")"]))},getContext:function(a){this.lastContext=a},pushContext:function(){this.pushStackLiteral(this.contextName(this.lastContext))},lookupOnContext:function(a,b,c,d){var e=0;d||!this.options.compat||this.lastContext?this.pushContext():this.push(this.depthedLookup(a[e++])),this.resolvePath("context",a,e,b,c)},lookupBlockParam:function(a,b){this.useBlockParams=!0,this.push(["blockParams[",a[0],"][",a[1],"]"]),this.resolvePath("context",b,1)},lookupData:function(a,b,c){a?this.pushStackLiteral("container.data(data, "+a+")"):this.pushStackLiteral("data"),this.resolvePath("data",b,0,!0,c)},resolvePath:function(a,b,c,d,e){var g=this;if(this.options.strict||this.options.assumeObjects)return void this.push(f(this.options.strict&&e,this,b,a));for(var h=b.length;c<h;c++)this.replaceStack(function(e){
  104152. var f=g.nameLookup(e,b[c],a);return d?[" && ",f]:[" != null ? ",f," : ",e]})},resolvePossibleLambda:function(){this.push([this.aliasable("container.lambda"),"(",this.popStack(),", ",this.contextName(0),")"])},pushStringParam:function(a,b){this.pushContext(),this.pushString(b),"SubExpression"!==b&&("string"==typeof a?this.pushString(a):this.pushStackLiteral(a))},emptyHash:function(a){this.trackIds&&this.push("{}"),this.stringParams&&(this.push("{}"),this.push("{}")),this.pushStackLiteral(a?"undefined":"{}")},pushHash:function(){this.hash&&this.hashes.push(this.hash),this.hash={values:[],types:[],contexts:[],ids:[]}},popHash:function(){var a=this.hash;this.hash=this.hashes.pop(),this.trackIds&&this.push(this.objectLiteral(a.ids)),this.stringParams&&(this.push(this.objectLiteral(a.contexts)),this.push(this.objectLiteral(a.types))),this.push(this.objectLiteral(a.values))},pushString:function(a){this.pushStackLiteral(this.quotedString(a))},pushLiteral:function(a){this.pushStackLiteral(a)},pushProgram:function(a){null!=a?this.pushStackLiteral(this.programExpression(a)):this.pushStackLiteral(null)},registerDecorator:function(a,b){var c=this.nameLookup("decorators",b,"decorator"),d=this.setupHelperArgs(b,a);this.decorators.push(["fn = ",this.decorators.functionCall(c,"",["fn","props","container",d])," || fn;"])},invokeHelper:function(a,b,c){var d=this.popStack(),e=this.setupHelper(a,b),f=c?[e.name," || "]:"",g=["("].concat(f,d);this.options.strict||g.push(" || ",this.aliasable("helpers.helperMissing")),g.push(")"),this.push(this.source.functionCall(g,"call",e.callParams))},invokeKnownHelper:function(a,b){var c=this.setupHelper(a,b);this.push(this.source.functionCall(c.name,"call",c.callParams))},invokeAmbiguous:function(a,b){this.useRegister("helper");var c=this.popStack();this.emptyHash();var d=this.setupHelper(0,a,b),e=this.lastHelper=this.nameLookup("helpers",a,"helper"),f=["(","(helper = ",e," || ",c,")"];this.options.strict||(f[0]="(helper = ",f.push(" != null ? helper : ",this.aliasable("helpers.helperMissing"))),this.push(["(",f,d.paramsInit?["),(",d.paramsInit]:[],"),","(typeof helper === ",this.aliasable('"function"')," ? ",this.source.functionCall("helper","call",d.callParams)," : helper))"])},invokePartial:function(a,b,c){var d=[],e=this.setupParams(b,1,d);a&&(b=this.popStack(),delete e.name),c&&(e.indent=JSON.stringify(c)),e.helpers="helpers",e.partials="partials",e.decorators="container.decorators",a?d.unshift(b):d.unshift(this.nameLookup("partials",b,"partial")),this.options.compat&&(e.depths="depths"),e=this.objectLiteral(e),d.push(e),this.push(this.source.functionCall("container.invokePartial","",d))},assignToHash:function(a){var b=this.popStack(),c=void 0,d=void 0,e=void 0;this.trackIds&&(e=this.popStack()),this.stringParams&&(d=this.popStack(),c=this.popStack());var f=this.hash;c&&(f.contexts[a]=c),d&&(f.types[a]=d),e&&(f.ids[a]=e),f.values[a]=b},pushId:function(a,b,c){"BlockParam"===a?this.pushStackLiteral("blockParams["+b[0]+"].path["+b[1]+"]"+(c?" + "+JSON.stringify("."+c):"")):"PathExpression"===a?this.pushString(b):"SubExpression"===a?this.pushStackLiteral("true"):this.pushStackLiteral("null")},compiler:e,compileChildren:function(a,b){for(var c=a.children,d=void 0,e=void 0,f=0,g=c.length;f<g;f++){d=c[f],e=new this.compiler;var h=this.matchExistingProgram(d);if(null==h){this.context.programs.push("");var i=this.context.programs.length;d.index=i,d.name="program"+i,this.context.programs[i]=e.compile(d,b,this.context,!this.precompile),this.context.decorators[i]=e.decorators,this.context.environments[i]=d,this.useDepths=this.useDepths||e.useDepths,this.useBlockParams=this.useBlockParams||e.useBlockParams,d.useDepths=this.useDepths,d.useBlockParams=this.useBlockParams}else d.index=h.index,d.name="program"+h.index,this.useDepths=this.useDepths||h.useDepths,this.useBlockParams=this.useBlockParams||h.useBlockParams}},matchExistingProgram:function(a){for(var b=0,c=this.context.environments.length;b<c;b++){var d=this.context.environments[b];if(d&&d.equals(a))return d}},programExpression:function(a){var b=this.environment.children[a],c=[b.index,"data",b.blockParams];return(this.useBlockParams||this.useDepths)&&c.push("blockParams"),this.useDepths&&c.push("depths"),"container.program("+c.join(", ")+")"},useRegister:function(a){this.registers[a]||(this.registers[a]=!0,this.registers.list.push(a))},push:function(a){return a instanceof d||(a=this.source.wrap(a)),this.inlineStack.push(a),a},pushStackLiteral:function(a){this.push(new d(a))},pushSource:function(a){this.pendingContent&&(this.source.push(this.appendToBuffer(this.source.quotedString(this.pendingContent),this.pendingLocation)),this.pendingContent=void 0),a&&this.source.push(a)},replaceStack:function(a){var b=["("],c=void 0,e=void 0,f=void 0;if(!this.isInline())throw new j["default"]("replaceStack on non-inline");var g=this.popStack(!0);if(g instanceof d)c=[g.value],b=["(",c],f=!0;else{e=!0;var h=this.incrStack();b=["((",this.push(h)," = ",g,")"],c=this.topStack()}var i=a.call(this,c);f||this.popStack(),e&&this.stackSlot--,this.push(b.concat(i,")"))},incrStack:function(){return this.stackSlot++,this.stackSlot>this.stackVars.length&&this.stackVars.push("stack"+this.stackSlot),this.topStackName()},topStackName:function(){return"stack"+this.stackSlot},flushInline:function(){var a=this.inlineStack;this.inlineStack=[];for(var b=0,c=a.length;b<c;b++){var e=a[b];if(e instanceof d)this.compileStack.push(e);else{var f=this.incrStack();this.pushSource([f," = ",e,";"]),this.compileStack.push(f)}}},isInline:function(){return this.inlineStack.length},popStack:function(a){var b=this.isInline(),c=(b?this.inlineStack:this.compileStack).pop();if(!a&&c instanceof d)return c.value;if(!b){if(!this.stackSlot)throw new j["default"]("Invalid stack pop");this.stackSlot--}return c},topStack:function(){var a=this.isInline()?this.inlineStack:this.compileStack,b=a[a.length-1];return b instanceof d?b.value:b},contextName:function(a){return this.useDepths&&a?"depths["+a+"]":"depth"+a},quotedString:function(a){return this.source.quotedString(a)},objectLiteral:function(a){return this.source.objectLiteral(a)},aliasable:function(a){var b=this.aliases[a];return b?(b.referenceCount++,b):(b=this.aliases[a]=this.source.wrap(a),b.aliasable=!0,b.referenceCount=1,b)},setupHelper:function(a,b,c){var d=[],e=this.setupHelperArgs(b,a,d,c),f=this.nameLookup("helpers",b,"helper"),g=this.aliasable(this.contextName(0)+" != null ? "+this.contextName(0)+" : (container.nullContext || {})");return{params:d,paramsInit:e,name:f,callParams:[g].concat(d)}},setupParams:function(a,b,c){var d={},e=[],f=[],g=[],h=!c,i=void 0;h&&(c=[]),d.name=this.quotedString(a),d.hash=this.popStack(),this.trackIds&&(d.hashIds=this.popStack()),this.stringParams&&(d.hashTypes=this.popStack(),d.hashContexts=this.popStack());var j=this.popStack(),k=this.popStack();(k||j)&&(d.fn=k||"container.noop",d.inverse=j||"container.noop");for(var l=b;l--;)i=this.popStack(),c[l]=i,this.trackIds&&(g[l]=this.popStack()),this.stringParams&&(f[l]=this.popStack(),e[l]=this.popStack());return h&&(d.args=this.source.generateArray(c)),this.trackIds&&(d.ids=this.source.generateArray(g)),this.stringParams&&(d.types=this.source.generateArray(f),d.contexts=this.source.generateArray(e)),this.options.data&&(d.data="data"),this.useBlockParams&&(d.blockParams="blockParams"),d},setupHelperArgs:function(a,b,c,d){var e=this.setupParams(a,b,c);return e=this.objectLiteral(e),d?(this.useRegister("options"),c.push("options"),["options=",e]):c?(c.push(e),""):e}},function(){for(var a="break else new var case finally return void catch for switch while continue function this with default if throw delete in try do instanceof typeof abstract enum int short boolean export interface static byte extends long super char final native synchronized class float package throws const goto private transient debugger implements protected volatile double import public let yield await null true false".split(" "),b=e.RESERVED_WORDS={},c=0,d=a.length;c<d;c++)b[a[c]]=!0}(),e.isValidJavaScriptVariableName=function(a){return!e.RESERVED_WORDS[a]&&/^[a-zA-Z_$][0-9a-zA-Z_$]*$/.test(a)},b["default"]=e,a.exports=b["default"]},function(a,b,c){"use strict";function d(a,b,c){if(f.isArray(a)){for(var d=[],e=0,g=a.length;e<g;e++)d.push(b.wrap(a[e],c));return d}return"boolean"==typeof a||"number"==typeof a?a+"":a}function e(a){this.srcFile=a,this.source=[]}b.__esModule=!0;var f=c(5),g=void 0;try{}catch(h){}g||(g=function(a,b,c,d){this.src="",d&&this.add(d)},g.prototype={add:function(a){f.isArray(a)&&(a=a.join("")),this.src+=a},prepend:function(a){f.isArray(a)&&(a=a.join("")),this.src=a+this.src},toStringWithSourceMap:function(){return{code:this.toString()}},toString:function(){return this.src}}),e.prototype={isEmpty:function(){return!this.source.length},prepend:function(a,b){this.source.unshift(this.wrap(a,b))},push:function(a,b){this.source.push(this.wrap(a,b))},merge:function(){var a=this.empty();return this.each(function(b){a.add([" ",b,"\n"])}),a},each:function(a){for(var b=0,c=this.source.length;b<c;b++)a(this.source[b])},empty:function(){var a=this.currentLocation||{start:{}};return new g(a.start.line,a.start.column,this.srcFile)},wrap:function(a){var b=arguments.length<=1||void 0===arguments[1]?this.currentLocation||{start:{}}:arguments[1];return a instanceof g?a:(a=d(a,this,b),new g(b.start.line,b.start.column,this.srcFile,a))},functionCall:function(a,b,c){return c=this.generateList(c),this.wrap([a,b?"."+b+"(":"(",c,")"])},quotedString:function(a){return'"'+(a+"").replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")+'"'},objectLiteral:function(a){var b=[];for(var c in a)if(a.hasOwnProperty(c)){var e=d(a[c],this);"undefined"!==e&&b.push([this.quotedString(c),":",e])}var f=this.generateList(b);return f.prepend("{"),f.add("}"),f},generateList:function(a){for(var b=this.empty(),c=0,e=a.length;c<e;c++)c&&b.add(","),b.add(d(a[c],this));return b},generateArray:function(a){var b=this.generateList(a);return b.prepend("["),b.add("]"),b}},b["default"]=e,a.exports=b["default"]}])});
  104153. /***/ }),
  104154. /* 21 */
  104155. /***/ (function(module, exports, __webpack_require__) {
  104156. "use strict";
  104157. Object.defineProperty(exports, "__esModule", { value: true });
  104158. var EventManager = (function () {
  104159. function EventManager(templateManager) {
  104160. var _this = this;
  104161. this.templateManager = templateManager;
  104162. this.callbacksContainer = {};
  104163. this.templateManager.onEventTriggered.add(function (eventData) {
  104164. _this.eventTriggered(eventData);
  104165. });
  104166. }
  104167. EventManager.prototype.registerCallback = function (templateName, callback, eventType, selector) {
  104168. if (!this.callbacksContainer[templateName]) {
  104169. this.callbacksContainer[templateName] = [];
  104170. }
  104171. this.callbacksContainer[templateName].push({
  104172. eventType: eventType,
  104173. callback: callback
  104174. });
  104175. };
  104176. EventManager.prototype.unregisterCallback = function (templateName, callback, eventType, selector) {
  104177. var callbackDefs = this.callbacksContainer[templateName] || [];
  104178. this.callbacksContainer[templateName] = callbackDefs.filter(function (callbackDef) { return (!callbackDef.eventType || callbackDef.eventType === eventType) && (!callbackDef.selector || callbackDef.selector === selector); });
  104179. };
  104180. EventManager.prototype.eventTriggered = function (data) {
  104181. var templateName = data.template.name;
  104182. var eventType = data.event.type;
  104183. var selector = data.selector;
  104184. var callbackDefs = this.callbacksContainer[templateName] || [];
  104185. callbackDefs.filter(function (callbackDef) { return (!callbackDef.eventType || callbackDef.eventType === eventType) && (!callbackDef.selector || callbackDef.selector === selector); }).forEach(function (callbackDef) {
  104186. callbackDef.callback(data);
  104187. });
  104188. };
  104189. return EventManager;
  104190. }());
  104191. exports.EventManager = EventManager;
  104192. /***/ }),
  104193. /* 22 */
  104194. /***/ (function(module, exports, __webpack_require__) {
  104195. "use strict";
  104196. Object.defineProperty(exports, "__esModule", { value: true });
  104197. var mappers_1 = __webpack_require__(1);
  104198. var types_1 = __webpack_require__(23);
  104199. var deepmerge = __webpack_require__(13);
  104200. var babylonjs_1 = __webpack_require__(0);
  104201. var ConfigurationLoader = (function () {
  104202. function ConfigurationLoader() {
  104203. this.configurationCache = {};
  104204. this.loadRequests = [];
  104205. }
  104206. ConfigurationLoader.prototype.loadConfiguration = function (initConfig, callback) {
  104207. var _this = this;
  104208. if (initConfig === void 0) { initConfig = {}; }
  104209. var loadedConfig = deepmerge({}, initConfig);
  104210. var extendedConfiguration = types_1.getConfigurationType(loadedConfig.extends || "");
  104211. loadedConfig = deepmerge(extendedConfiguration, loadedConfig);
  104212. if (loadedConfig.configuration) {
  104213. var mapperType_1 = "json";
  104214. return Promise.resolve().then(function () {
  104215. if (typeof loadedConfig.configuration === "string" || (loadedConfig.configuration && loadedConfig.configuration.url)) {
  104216. var url = '';
  104217. if (typeof loadedConfig.configuration === "string") {
  104218. url = loadedConfig.configuration;
  104219. }
  104220. if (typeof loadedConfig.configuration === "object" && loadedConfig.configuration.url) {
  104221. url = loadedConfig.configuration.url;
  104222. var type = loadedConfig.configuration.mapper;
  104223. if (!type) {
  104224. type = loadedConfig.configuration.url.split('.').pop();
  104225. }
  104226. mapperType_1 = type || mapperType_1;
  104227. }
  104228. return _this.loadFile(url);
  104229. }
  104230. else {
  104231. if (typeof loadedConfig.configuration === "object") {
  104232. mapperType_1 = loadedConfig.configuration.mapper || mapperType_1;
  104233. return loadedConfig.configuration.payload || {};
  104234. }
  104235. return {};
  104236. }
  104237. }).then(function (data) {
  104238. var mapper = mappers_1.mapperManager.getMapper(mapperType_1);
  104239. var parsed = mapper.map(data);
  104240. var merged = deepmerge(loadedConfig, parsed);
  104241. if (callback)
  104242. callback(merged);
  104243. return merged;
  104244. });
  104245. }
  104246. else {
  104247. if (callback)
  104248. callback(loadedConfig);
  104249. return Promise.resolve(loadedConfig);
  104250. }
  104251. };
  104252. ConfigurationLoader.prototype.dispose = function () {
  104253. this.loadRequests.forEach(function (request) {
  104254. request.abort();
  104255. });
  104256. };
  104257. ConfigurationLoader.prototype.loadFile = function (url) {
  104258. var _this = this;
  104259. var cacheReference = this.configurationCache;
  104260. if (cacheReference[url]) {
  104261. return Promise.resolve(cacheReference[url]);
  104262. }
  104263. return new Promise(function (resolve, reject) {
  104264. var fileRequest = babylonjs_1.Tools.LoadFile(url, resolve, undefined, undefined, false, function (request, error) {
  104265. reject(error);
  104266. });
  104267. _this.loadRequests.push(fileRequest);
  104268. });
  104269. };
  104270. return ConfigurationLoader;
  104271. }());
  104272. exports.ConfigurationLoader = ConfigurationLoader;
  104273. exports.configurationLoader = new ConfigurationLoader();
  104274. exports.default = exports.configurationLoader;
  104275. /***/ }),
  104276. /* 23 */
  104277. /***/ (function(module, exports, __webpack_require__) {
  104278. "use strict";
  104279. Object.defineProperty(exports, "__esModule", { value: true });
  104280. var minimal_1 = __webpack_require__(24);
  104281. exports.minimalConfiguration = minimal_1.minimalConfiguration;
  104282. var default_1 = __webpack_require__(25);
  104283. exports.defaultConfiguration = default_1.defaultConfiguration;
  104284. var getConfigurationType = function (type) {
  104285. switch (type) {
  104286. case 'default':
  104287. return default_1.defaultConfiguration;
  104288. case 'minimal':
  104289. return minimal_1.minimalConfiguration;
  104290. case 'none':
  104291. return {};
  104292. default:
  104293. return default_1.defaultConfiguration;
  104294. }
  104295. };
  104296. exports.getConfigurationType = getConfigurationType;
  104297. /***/ }),
  104298. /* 24 */
  104299. /***/ (function(module, exports, __webpack_require__) {
  104300. "use strict";
  104301. Object.defineProperty(exports, "__esModule", { value: true });
  104302. exports.minimalConfiguration = {
  104303. version: "0.1",
  104304. templates: {
  104305. main: {
  104306. html: __webpack_require__(6)
  104307. },
  104308. loadingScreen: {
  104309. html: __webpack_require__(7),
  104310. params: {
  104311. backgroundColor: "#000000",
  104312. loadingImage: __webpack_require__(8)
  104313. }
  104314. },
  104315. viewer: {
  104316. html: __webpack_require__(9),
  104317. },
  104318. overlay: {
  104319. html: __webpack_require__(10),
  104320. params: {
  104321. closeImage: __webpack_require__(11),
  104322. closeText: 'Close'
  104323. }
  104324. },
  104325. error: {
  104326. html: __webpack_require__(12)
  104327. }
  104328. },
  104329. engine: {
  104330. antialiasing: true
  104331. }
  104332. };
  104333. /***/ }),
  104334. /* 25 */
  104335. /***/ (function(module, exports, __webpack_require__) {
  104336. "use strict";
  104337. Object.defineProperty(exports, "__esModule", { value: true });
  104338. exports.defaultConfiguration = {
  104339. version: "3.2.0-alpha4",
  104340. templates: {
  104341. main: {
  104342. html: __webpack_require__(6)
  104343. },
  104344. loadingScreen: {
  104345. html: __webpack_require__(7),
  104346. params: {
  104347. backgroundColor: "#000000",
  104348. loadingImage: __webpack_require__(8)
  104349. }
  104350. },
  104351. viewer: {
  104352. html: __webpack_require__(9),
  104353. events: {
  104354. pointerout: true,
  104355. pointerdown: true,
  104356. pointerup: true
  104357. }
  104358. },
  104359. navBar: {
  104360. html: __webpack_require__(26),
  104361. params: {
  104362. buttons: {
  104363. "fullscreen-button": {
  104364. altText: "Fullscreen",
  104365. image: __webpack_require__(27)
  104366. }
  104367. },
  104368. visibilityTimeout: 2000
  104369. },
  104370. events: {
  104371. pointerdown: { 'fullscreen-button': true },
  104372. pointerover: true
  104373. }
  104374. },
  104375. overlay: {
  104376. html: __webpack_require__(10),
  104377. params: {
  104378. closeImage: __webpack_require__(11),
  104379. closeText: 'Close'
  104380. }
  104381. },
  104382. help: {
  104383. html: __webpack_require__(28)
  104384. },
  104385. share: {
  104386. html: __webpack_require__(29)
  104387. },
  104388. error: {
  104389. html: __webpack_require__(12)
  104390. }
  104391. },
  104392. camera: {
  104393. behaviors: {
  104394. autoRotate: 0,
  104395. framing: {
  104396. type: 2,
  104397. zoomOnBoundingInfo: true,
  104398. zoomStopsAnimation: false
  104399. }
  104400. }
  104401. },
  104402. skybox: {
  104403. pbr: true,
  104404. blur: 0.7,
  104405. infiniteDIstance: false,
  104406. },
  104407. ground: true,
  104408. engine: {
  104409. antialiasing: true
  104410. },
  104411. scene: {
  104412. imageProcessingConfiguration: {
  104413. exposure: 1.4,
  104414. contrast: 1.66,
  104415. toneMappingEnabled: true
  104416. }
  104417. }
  104418. };
  104419. /***/ }),
  104420. /* 26 */
  104421. /***/ (function(module, exports) {
  104422. module.exports = "<style>nav-bar{position:absolute;height:160px;width:100%;bottom:0;background-color:rgba(0,0,0,.3);color:#fff;transition:1s;align-items:flex-start;justify-content:space-around;display:flex;flex-direction:column}@media screen and (min-width:768px){nav-bar{align-items:center;flex-direction:row;justify-content:space-between;height:80px}}div.flex-container{display:flex;width:100%}div.thumbnail{position:relative;overflow:hidden;display:block;width:40px;height:40px;background-size:cover;background-position:center;border-radius:20px;margin:0 10px}div.title-container{flex-direction:column;display:flex;justify-content:space-between}span.model-title{font-size:125%}span.model-subtitle{font-size:90%}div.button-container{align-items:center;justify-content:flex-end}div.button{cursor:pointer;height:30px;margin:0 10px}div.button img{height:100%}</style> {{#if disableOnFullscreen}} <style>viewer:fullscreen nav-bar{display:none}viewer:-moz-full-screen nav-bar{display:none}viewer:-webkit-full-screen nav-bar{display:none}</style> {{/if}} <div class=flex-container id=model-metadata> <div class=thumbnail> </div> <div class=title-container> <span class=model-title>{{#if title}}{{title}}{{/if}}</span> <span class=model-subtitle> {{#if subtitle}}{{subtitle}} {{/if}}</span> </div> </div> <div class=\"button-container flex-container\"> {{#eachInMap buttons}} <div id={{id}} class=button> {{#if text}} <span>{{text}}</span>> {{/if}} {{#if image}} <img src={{image}} alt={{altText}}> {{/if}} </div> {{/eachInMap}} </div>";
  104423. /***/ }),
  104424. /* 27 */
  104425. /***/ (function(module, exports) {
  104426. module.exports = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwAQAAAAB/ecQqAAAAAnRSTlMAAHaTzTgAAAAeSURBVHgBY6ASsP/A/wcXZQNGhCkyAfE24HUndQAAXlkXcQ24P7gAAAAASUVORK5CYII="
  104427. /***/ }),
  104428. /* 28 */
  104429. /***/ (function(module, exports) {
  104430. module.exports = "HELP";
  104431. /***/ }),
  104432. /* 29 */
  104433. /***/ (function(module, exports) {
  104434. module.exports = "SHARE";
  104435. /***/ }),
  104436. /* 30 */
  104437. /***/ (function(module, exports, __webpack_require__) {
  104438. "use strict";
  104439. Object.defineProperty(exports, "__esModule", { value: true });
  104440. var babylonjs_1 = __webpack_require__(0);
  104441. var modelAnimation_1 = __webpack_require__(31);
  104442. var ViewerModel = (function () {
  104443. function ViewerModel(_modelConfiguration, _scene, disableAutoLoad) {
  104444. if (disableAutoLoad === void 0) { disableAutoLoad = false; }
  104445. this._modelConfiguration = _modelConfiguration;
  104446. this._scene = _scene;
  104447. this.onLoadedObservable = new babylonjs_1.Observable();
  104448. this.onLoadErrorObservable = new babylonjs_1.Observable();
  104449. this.onLoadProgressObservable = new babylonjs_1.Observable();
  104450. this._animations = [];
  104451. if (!disableAutoLoad) {
  104452. this._initLoad();
  104453. }
  104454. }
  104455. ViewerModel.prototype.load = function () {
  104456. if (this.loader) {
  104457. babylonjs_1.Tools.Error("Model was already loaded or in the process of loading.");
  104458. }
  104459. else {
  104460. this._initLoad();
  104461. }
  104462. };
  104463. ViewerModel.prototype.getAnimationNames = function () {
  104464. return this._animations.map(function (a) { return a.name; });
  104465. };
  104466. ViewerModel.prototype._getAnimationByName = function (name) {
  104467. var filtered = this._animations.filter(function (a) { return a.name === name; });
  104468. if (filtered.length === 1) {
  104469. return filtered[0];
  104470. }
  104471. else {
  104472. return null;
  104473. }
  104474. };
  104475. ViewerModel.prototype.playAnimation = function (name) {
  104476. var animation = this._getAnimationByName(name);
  104477. if (animation) {
  104478. if (this.currentAnimation) {
  104479. this.currentAnimation.stop();
  104480. }
  104481. this.currentAnimation = animation;
  104482. animation.start();
  104483. return animation;
  104484. }
  104485. else {
  104486. throw new Error("animation not found - " + name);
  104487. }
  104488. };
  104489. ViewerModel.prototype._initLoad = function () {
  104490. var _this = this;
  104491. if (!this._modelConfiguration || !this._modelConfiguration.url) {
  104492. return babylonjs_1.Tools.Error("No model URL to load.");
  104493. }
  104494. var parts = this._modelConfiguration.url.split('/');
  104495. var filename = parts.pop() || this._modelConfiguration.url;
  104496. var base = parts.length ? parts.join('/') + '/' : './';
  104497. var plugin = this._modelConfiguration.loader;
  104498. var animationsArray = this._scene.animationGroups.slice();
  104499. this.loader = babylonjs_1.SceneLoader.ImportMesh(undefined, base, filename, this._scene, function (meshes, particleSystems, skeletons) {
  104500. meshes.forEach(function (mesh) {
  104501. babylonjs_1.Tags.AddTagsTo(mesh, "viewerMesh");
  104502. });
  104503. _this.meshes = meshes;
  104504. _this.particleSystems = particleSystems;
  104505. _this.skeletons = skeletons;
  104506. if (_this.loader.name === 'gltf') {
  104507. _this._scene.animationGroups.forEach(function (ag) {
  104508. if (animationsArray.indexOf(ag) === -1) {
  104509. _this._animations.push(new modelAnimation_1.GroupModelAnimation(ag));
  104510. }
  104511. });
  104512. }
  104513. else {
  104514. skeletons.forEach(function (skeleton, idx) {
  104515. var ag = new BABYLON.AnimationGroup("animation-" + idx, _this._scene);
  104516. skeleton.getAnimatables().forEach(function (a) {
  104517. if (a.animations[0]) {
  104518. ag.addTargetedAnimation(a.animations[0], a);
  104519. }
  104520. });
  104521. _this._animations.push(new modelAnimation_1.GroupModelAnimation(ag));
  104522. });
  104523. }
  104524. if (_this._modelConfiguration.animation) {
  104525. if (_this._modelConfiguration.animation.playOnce) {
  104526. _this._animations.forEach(function (a) {
  104527. a.playMode = modelAnimation_1.AnimationPlayMode.ONCE;
  104528. });
  104529. }
  104530. if (_this._modelConfiguration.animation.autoStart && _this._animations.length) {
  104531. var animationName = _this._modelConfiguration.animation.autoStart === true ?
  104532. _this._animations[0].name : _this._modelConfiguration.animation.autoStart;
  104533. _this.playAnimation(animationName);
  104534. }
  104535. }
  104536. _this.onLoadedObservable.notifyObserversWithPromise(_this);
  104537. }, function (progressEvent) {
  104538. _this.onLoadProgressObservable.notifyObserversWithPromise(progressEvent);
  104539. }, function (e, m, exception) {
  104540. _this.onLoadErrorObservable.notifyObserversWithPromise({ message: m, exception: exception });
  104541. }, plugin);
  104542. this.loader['animationStartMode'] = 0;
  104543. };
  104544. ViewerModel.prototype.dispose = function () {
  104545. this.particleSystems.forEach(function (ps) { return ps.dispose(); });
  104546. this.skeletons.forEach(function (s) { return s.dispose(); });
  104547. this._animations.forEach(function (ag) { return ag.dispose(); });
  104548. this.meshes.forEach(function (m) { return m.dispose(); });
  104549. };
  104550. return ViewerModel;
  104551. }());
  104552. exports.ViewerModel = ViewerModel;
  104553. /***/ }),
  104554. /* 31 */
  104555. /***/ (function(module, exports, __webpack_require__) {
  104556. "use strict";
  104557. Object.defineProperty(exports, "__esModule", { value: true });
  104558. var AnimationPlayMode;
  104559. (function (AnimationPlayMode) {
  104560. AnimationPlayMode[AnimationPlayMode["ONCE"] = 0] = "ONCE";
  104561. AnimationPlayMode[AnimationPlayMode["LOOP"] = 1] = "LOOP";
  104562. })(AnimationPlayMode = exports.AnimationPlayMode || (exports.AnimationPlayMode = {}));
  104563. var AnimationState;
  104564. (function (AnimationState) {
  104565. AnimationState[AnimationState["INIT"] = 0] = "INIT";
  104566. AnimationState[AnimationState["PLAYING"] = 1] = "PLAYING";
  104567. AnimationState[AnimationState["PAUSED"] = 2] = "PAUSED";
  104568. AnimationState[AnimationState["STOPPED"] = 3] = "STOPPED";
  104569. AnimationState[AnimationState["ENDED"] = 4] = "ENDED";
  104570. })(AnimationState = exports.AnimationState || (exports.AnimationState = {}));
  104571. var GroupModelAnimation = (function () {
  104572. function GroupModelAnimation(_animationGroup) {
  104573. var _this = this;
  104574. this._animationGroup = _animationGroup;
  104575. this._state = AnimationState.INIT;
  104576. this._playMode = AnimationPlayMode.LOOP;
  104577. this._animationGroup.onAnimationEndObservable.add(function () {
  104578. _this.stop();
  104579. _this._state = AnimationState.ENDED;
  104580. });
  104581. }
  104582. Object.defineProperty(GroupModelAnimation.prototype, "name", {
  104583. get: function () {
  104584. return this._animationGroup.name;
  104585. },
  104586. enumerable: true,
  104587. configurable: true
  104588. });
  104589. Object.defineProperty(GroupModelAnimation.prototype, "state", {
  104590. get: function () {
  104591. return this._state;
  104592. },
  104593. enumerable: true,
  104594. configurable: true
  104595. });
  104596. Object.defineProperty(GroupModelAnimation.prototype, "speedRatio", {
  104597. get: function () {
  104598. return this._animationGroup.speedRatio;
  104599. },
  104600. set: function (value) {
  104601. this._animationGroup.speedRatio = value;
  104602. },
  104603. enumerable: true,
  104604. configurable: true
  104605. });
  104606. Object.defineProperty(GroupModelAnimation.prototype, "frames", {
  104607. get: function () {
  104608. var animationFrames = this._animationGroup.targetedAnimations.map(function (ta) {
  104609. var keys = ta.animation.getKeys();
  104610. return keys[keys.length - 1].frame;
  104611. });
  104612. return Math.max.apply(null, animationFrames);
  104613. },
  104614. enumerable: true,
  104615. configurable: true
  104616. });
  104617. Object.defineProperty(GroupModelAnimation.prototype, "currentFrame", {
  104618. get: function () {
  104619. for (var i = 0; i < this._animationGroup.animatables.length; ++i) {
  104620. var animatable = this._animationGroup.animatables[i];
  104621. var animations = animatable.getAnimations();
  104622. if (!animations || !animations.length) {
  104623. continue;
  104624. }
  104625. for (var idx = 0; idx < animations.length; ++idx) {
  104626. if (animations[idx].currentFrame) {
  104627. return animations[idx].currentFrame;
  104628. }
  104629. }
  104630. }
  104631. return 0;
  104632. },
  104633. enumerable: true,
  104634. configurable: true
  104635. });
  104636. Object.defineProperty(GroupModelAnimation.prototype, "fps", {
  104637. get: function () {
  104638. for (var i = 0; i < this._animationGroup.animatables.length; ++i) {
  104639. var animatable = this._animationGroup.animatables[i];
  104640. var animations = animatable.getAnimations();
  104641. if (!animations || !animations.length) {
  104642. continue;
  104643. }
  104644. for (var idx = 0; idx < animations.length; ++idx) {
  104645. if (animations[idx].animation && animations[idx].animation.framePerSecond) {
  104646. return animations[idx].animation.framePerSecond;
  104647. }
  104648. }
  104649. }
  104650. return 0;
  104651. },
  104652. enumerable: true,
  104653. configurable: true
  104654. });
  104655. Object.defineProperty(GroupModelAnimation.prototype, "playMode", {
  104656. get: function () {
  104657. return this._playMode;
  104658. },
  104659. set: function (value) {
  104660. if (value === this._playMode) {
  104661. return;
  104662. }
  104663. this._playMode = value;
  104664. if (this.state === AnimationState.PLAYING) {
  104665. this._animationGroup.play(this._playMode === AnimationPlayMode.LOOP);
  104666. }
  104667. else {
  104668. this._animationGroup.reset();
  104669. this._state = AnimationState.INIT;
  104670. }
  104671. },
  104672. enumerable: true,
  104673. configurable: true
  104674. });
  104675. GroupModelAnimation.prototype.reset = function () {
  104676. this._animationGroup.reset();
  104677. };
  104678. GroupModelAnimation.prototype.restart = function () {
  104679. this._animationGroup.restart();
  104680. };
  104681. GroupModelAnimation.prototype.goToFrame = function (frameNumber) {
  104682. this._animationGroup['_animatables'].forEach(function (a) {
  104683. a.goToFrame(frameNumber);
  104684. });
  104685. };
  104686. GroupModelAnimation.prototype.start = function () {
  104687. this._animationGroup.start(this.playMode === AnimationPlayMode.LOOP, this.speedRatio);
  104688. if (this._animationGroup.isStarted) {
  104689. this._state = AnimationState.PLAYING;
  104690. }
  104691. };
  104692. GroupModelAnimation.prototype.pause = function () {
  104693. this._animationGroup.pause();
  104694. this._state = AnimationState.PAUSED;
  104695. };
  104696. GroupModelAnimation.prototype.stop = function () {
  104697. this._animationGroup.stop();
  104698. if (!this._animationGroup.isStarted) {
  104699. this._state = AnimationState.STOPPED;
  104700. }
  104701. };
  104702. GroupModelAnimation.prototype.dispose = function () {
  104703. this._animationGroup.dispose();
  104704. };
  104705. return GroupModelAnimation;
  104706. }());
  104707. exports.GroupModelAnimation = GroupModelAnimation;
  104708. /***/ }),
  104709. /* 32 */
  104710. /***/ (function(module, exports, __webpack_require__) {
  104711. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  104712. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  104713. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  104714. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  104715. return c > 3 && r && Object.defineProperty(target, key, r), r;
  104716. };
  104717. var __extends = (this && this.__extends) || (function () {
  104718. var extendStatics = Object.setPrototypeOf ||
  104719. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  104720. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  104721. return function (d, b) {
  104722. extendStatics(d, b);
  104723. function __() { this.constructor = d; }
  104724. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  104725. };
  104726. })();
  104727. (function universalModuleDefinition(root, factory) {
  104728. if(true)
  104729. module.exports = factory(__webpack_require__(0));
  104730. else if(typeof define === 'function' && define.amd)
  104731. define("babylonjs-loaders", ["babylonjs"], factory);
  104732. else if(typeof exports === 'object')
  104733. exports["babylonjs-loaders"] = factory(require("babylonjs"));
  104734. else {
  104735. root["BABYLON"] = factory(root["BABYLON"]);
  104736. }
  104737. })(this, function(BABYLON) {
  104738. var BABYLON;
  104739. (function (BABYLON) {
  104740. var STLFileLoader = /** @class */ (function () {
  104741. function STLFileLoader() {
  104742. this.solidPattern = /solid (\S*)([\S\s]*)endsolid[ ]*(\S*)/g;
  104743. this.facetsPattern = /facet([\s\S]*?)endfacet/g;
  104744. this.normalPattern = /normal[\s]+([\-+]?[0-9]+\.?[0-9]*([eE][\-+]?[0-9]+)?)+[\s]+([\-+]?[0-9]*\.?[0-9]+([eE][\-+]?[0-9]+)?)+[\s]+([\-+]?[0-9]*\.?[0-9]+([eE][\-+]?[0-9]+)?)+/g;
  104745. this.vertexPattern = /vertex[\s]+([\-+]?[0-9]+\.?[0-9]*([eE][\-+]?[0-9]+)?)+[\s]+([\-+]?[0-9]*\.?[0-9]+([eE][\-+]?[0-9]+)?)+[\s]+([\-+]?[0-9]*\.?[0-9]+([eE][\-+]?[0-9]+)?)+/g;
  104746. this.name = "stl";
  104747. // force data to come in as an ArrayBuffer
  104748. // we'll convert to string if it looks like it's an ASCII .stl
  104749. this.extensions = {
  104750. ".stl": { isBinary: true },
  104751. };
  104752. }
  104753. STLFileLoader.prototype.importMesh = function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  104754. var matches;
  104755. if (this.isBinary(data)) {
  104756. // binary .stl
  104757. var babylonMesh = new BABYLON.Mesh("stlmesh", scene);
  104758. this.parseBinary(babylonMesh, data);
  104759. if (meshes) {
  104760. meshes.push(babylonMesh);
  104761. }
  104762. return true;
  104763. }
  104764. // ASCII .stl
  104765. // convert to string
  104766. var array_buffer = new Uint8Array(data);
  104767. var str = '';
  104768. for (var i = 0; i < data.byteLength; i++) {
  104769. str += String.fromCharCode(array_buffer[i]); // implicitly assumes little-endian
  104770. }
  104771. data = str;
  104772. while (matches = this.solidPattern.exec(data)) {
  104773. var meshName = matches[1];
  104774. var meshNameFromEnd = matches[3];
  104775. if (meshName != meshNameFromEnd) {
  104776. BABYLON.Tools.Error("Error in STL, solid name != endsolid name");
  104777. return false;
  104778. }
  104779. // check meshesNames
  104780. if (meshesNames && meshName) {
  104781. if (meshesNames instanceof Array) {
  104782. if (!meshesNames.indexOf(meshName)) {
  104783. continue;
  104784. }
  104785. }
  104786. else {
  104787. if (meshName !== meshesNames) {
  104788. continue;
  104789. }
  104790. }
  104791. }
  104792. // stl mesh name can be empty as well
  104793. meshName = meshName || "stlmesh";
  104794. var babylonMesh = new BABYLON.Mesh(meshName, scene);
  104795. this.parseASCII(babylonMesh, matches[2]);
  104796. if (meshes) {
  104797. meshes.push(babylonMesh);
  104798. }
  104799. }
  104800. return true;
  104801. };
  104802. STLFileLoader.prototype.load = function (scene, data, rootUrl) {
  104803. var result = this.importMesh(null, scene, data, rootUrl, null, null, null);
  104804. if (result) {
  104805. scene.createDefaultCameraOrLight();
  104806. }
  104807. return result;
  104808. };
  104809. STLFileLoader.prototype.loadAssetContainer = function (scene, data, rootUrl, onError) {
  104810. var container = new BABYLON.AssetContainer(scene);
  104811. this.importMesh(null, scene, data, rootUrl, container.meshes, null, null);
  104812. container.removeAllFromScene();
  104813. return container;
  104814. };
  104815. STLFileLoader.prototype.isBinary = function (data) {
  104816. // check if file size is correct for binary stl
  104817. var faceSize, nFaces, reader;
  104818. reader = new DataView(data);
  104819. faceSize = (32 / 8 * 3) + ((32 / 8 * 3) * 3) + (16 / 8);
  104820. nFaces = reader.getUint32(80, true);
  104821. if (80 + (32 / 8) + (nFaces * faceSize) === reader.byteLength) {
  104822. return true;
  104823. }
  104824. // check characters higher than ASCII to confirm binary
  104825. var fileLength = reader.byteLength;
  104826. for (var index = 0; index < fileLength; index++) {
  104827. if (reader.getUint8(index) > 127) {
  104828. return true;
  104829. }
  104830. }
  104831. return false;
  104832. };
  104833. STLFileLoader.prototype.parseBinary = function (mesh, data) {
  104834. var reader = new DataView(data);
  104835. var faces = reader.getUint32(80, true);
  104836. var dataOffset = 84;
  104837. var faceLength = 12 * 4 + 2;
  104838. var offset = 0;
  104839. var positions = new Float32Array(faces * 3 * 3);
  104840. var normals = new Float32Array(faces * 3 * 3);
  104841. var indices = new Uint32Array(faces * 3);
  104842. var indicesCount = 0;
  104843. for (var face = 0; face < faces; face++) {
  104844. var start = dataOffset + face * faceLength;
  104845. var normalX = reader.getFloat32(start, true);
  104846. var normalY = reader.getFloat32(start + 4, true);
  104847. var normalZ = reader.getFloat32(start + 8, true);
  104848. for (var i = 1; i <= 3; i++) {
  104849. var vertexstart = start + i * 12;
  104850. // ordering is intentional to match ascii import
  104851. positions[offset] = reader.getFloat32(vertexstart, true);
  104852. positions[offset + 2] = reader.getFloat32(vertexstart + 4, true);
  104853. positions[offset + 1] = reader.getFloat32(vertexstart + 8, true);
  104854. normals[offset] = normalX;
  104855. normals[offset + 2] = normalY;
  104856. normals[offset + 1] = normalZ;
  104857. offset += 3;
  104858. }
  104859. indices[indicesCount] = indicesCount++;
  104860. indices[indicesCount] = indicesCount++;
  104861. indices[indicesCount] = indicesCount++;
  104862. }
  104863. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  104864. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  104865. mesh.setIndices(indices);
  104866. mesh.computeWorldMatrix(true);
  104867. };
  104868. STLFileLoader.prototype.parseASCII = function (mesh, solidData) {
  104869. var positions = [];
  104870. var normals = [];
  104871. var indices = [];
  104872. var indicesCount = 0;
  104873. //load facets, ignoring loop as the standard doesn't define it can contain more than vertices
  104874. var matches;
  104875. while (matches = this.facetsPattern.exec(solidData)) {
  104876. var facet = matches[1];
  104877. //one normal per face
  104878. var normalMatches = this.normalPattern.exec(facet);
  104879. this.normalPattern.lastIndex = 0;
  104880. if (!normalMatches) {
  104881. continue;
  104882. }
  104883. var normal = [Number(normalMatches[1]), Number(normalMatches[5]), Number(normalMatches[3])];
  104884. var vertexMatch;
  104885. while (vertexMatch = this.vertexPattern.exec(facet)) {
  104886. positions.push(Number(vertexMatch[1]), Number(vertexMatch[5]), Number(vertexMatch[3]));
  104887. normals.push(normal[0], normal[1], normal[2]);
  104888. }
  104889. indices.push(indicesCount++, indicesCount++, indicesCount++);
  104890. this.vertexPattern.lastIndex = 0;
  104891. }
  104892. this.facetsPattern.lastIndex = 0;
  104893. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  104894. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  104895. mesh.setIndices(indices);
  104896. mesh.computeWorldMatrix(true);
  104897. };
  104898. return STLFileLoader;
  104899. }());
  104900. BABYLON.STLFileLoader = STLFileLoader;
  104901. if (BABYLON.SceneLoader) {
  104902. BABYLON.SceneLoader.RegisterPlugin(new STLFileLoader());
  104903. }
  104904. })(BABYLON || (BABYLON = {}));
  104905. //# sourceMappingURL=babylon.stlFileLoader.js.map
  104906. var BABYLON;
  104907. (function (BABYLON) {
  104908. /**
  104909. * Class reading and parsing the MTL file bundled with the obj file.
  104910. */
  104911. var MTLFileLoader = /** @class */ (function () {
  104912. function MTLFileLoader() {
  104913. // All material loaded from the mtl will be set here
  104914. this.materials = [];
  104915. }
  104916. /**
  104917. * This function will read the mtl file and create each material described inside
  104918. * This function could be improve by adding :
  104919. * -some component missing (Ni, Tf...)
  104920. * -including the specific options available
  104921. *
  104922. * @param scene
  104923. * @param data
  104924. * @param rootUrl
  104925. */
  104926. MTLFileLoader.prototype.parseMTL = function (scene, data, rootUrl) {
  104927. //Split the lines from the file
  104928. var lines = data.split('\n');
  104929. //Space char
  104930. var delimiter_pattern = /\s+/;
  104931. //Array with RGB colors
  104932. var color;
  104933. //New material
  104934. var material = null;
  104935. //Look at each line
  104936. for (var i = 0; i < lines.length; i++) {
  104937. var line = lines[i].trim();
  104938. // Blank line or comment
  104939. if (line.length === 0 || line.charAt(0) === '#') {
  104940. continue;
  104941. }
  104942. //Get the first parameter (keyword)
  104943. var pos = line.indexOf(' ');
  104944. var key = (pos >= 0) ? line.substring(0, pos) : line;
  104945. key = key.toLowerCase();
  104946. //Get the data following the key
  104947. var value = (pos >= 0) ? line.substring(pos + 1).trim() : "";
  104948. //This mtl keyword will create the new material
  104949. if (key === "newmtl") {
  104950. //Check if it is the first material.
  104951. // Materials specifications are described after this keyword.
  104952. if (material) {
  104953. //Add the previous material in the material array.
  104954. this.materials.push(material);
  104955. }
  104956. //Create a new material.
  104957. // value is the name of the material read in the mtl file
  104958. material = new BABYLON.StandardMaterial(value, scene);
  104959. }
  104960. else if (key === "kd" && material) {
  104961. // Diffuse color (color under white light) using RGB values
  104962. //value = "r g b"
  104963. color = value.split(delimiter_pattern, 3).map(parseFloat);
  104964. //color = [r,g,b]
  104965. //Set tghe color into the material
  104966. material.diffuseColor = BABYLON.Color3.FromArray(color);
  104967. }
  104968. else if (key === "ka" && material) {
  104969. // Ambient color (color under shadow) using RGB values
  104970. //value = "r g b"
  104971. color = value.split(delimiter_pattern, 3).map(parseFloat);
  104972. //color = [r,g,b]
  104973. //Set tghe color into the material
  104974. material.ambientColor = BABYLON.Color3.FromArray(color);
  104975. }
  104976. else if (key === "ks" && material) {
  104977. // Specular color (color when light is reflected from shiny surface) using RGB values
  104978. //value = "r g b"
  104979. color = value.split(delimiter_pattern, 3).map(parseFloat);
  104980. //color = [r,g,b]
  104981. //Set the color into the material
  104982. material.specularColor = BABYLON.Color3.FromArray(color);
  104983. }
  104984. else if (key === "ke" && material) {
  104985. // Emissive color using RGB values
  104986. color = value.split(delimiter_pattern, 3).map(parseFloat);
  104987. material.emissiveColor = BABYLON.Color3.FromArray(color);
  104988. }
  104989. else if (key === "ns" && material) {
  104990. //value = "Integer"
  104991. material.specularPower = parseFloat(value);
  104992. }
  104993. else if (key === "d" && material) {
  104994. //d is dissolve for current material. It mean alpha for BABYLON
  104995. material.alpha = parseFloat(value);
  104996. //Texture
  104997. //This part can be improved by adding the possible options of texture
  104998. }
  104999. else if (key === "map_ka" && material) {
  105000. // ambient texture map with a loaded image
  105001. //We must first get the folder of the image
  105002. material.ambientTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  105003. }
  105004. else if (key === "map_kd" && material) {
  105005. // Diffuse texture map with a loaded image
  105006. material.diffuseTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  105007. }
  105008. else if (key === "map_ks" && material) {
  105009. // Specular texture map with a loaded image
  105010. //We must first get the folder of the image
  105011. material.specularTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  105012. }
  105013. else if (key === "map_ns") {
  105014. //Specular
  105015. //Specular highlight component
  105016. //We must first get the folder of the image
  105017. //
  105018. //Not supported by BABYLON
  105019. //
  105020. // continue;
  105021. }
  105022. else if (key === "map_bump" && material) {
  105023. //The bump texture
  105024. material.bumpTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  105025. }
  105026. else if (key === "map_d" && material) {
  105027. // The dissolve of the material
  105028. material.opacityTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  105029. //Options for illumination
  105030. }
  105031. else if (key === "illum") {
  105032. //Illumination
  105033. if (value === "0") {
  105034. //That mean Kd == Kd
  105035. }
  105036. else if (value === "1") {
  105037. //Color on and Ambient on
  105038. }
  105039. else if (value === "2") {
  105040. //Highlight on
  105041. }
  105042. else if (value === "3") {
  105043. //Reflection on and Ray trace on
  105044. }
  105045. else if (value === "4") {
  105046. //Transparency: Glass on, Reflection: Ray trace on
  105047. }
  105048. else if (value === "5") {
  105049. //Reflection: Fresnel on and Ray trace on
  105050. }
  105051. else if (value === "6") {
  105052. //Transparency: Refraction on, Reflection: Fresnel off and Ray trace on
  105053. }
  105054. else if (value === "7") {
  105055. //Transparency: Refraction on, Reflection: Fresnel on and Ray trace on
  105056. }
  105057. else if (value === "8") {
  105058. //Reflection on and Ray trace off
  105059. }
  105060. else if (value === "9") {
  105061. //Transparency: Glass on, Reflection: Ray trace off
  105062. }
  105063. else if (value === "10") {
  105064. //Casts shadows onto invisible surfaces
  105065. }
  105066. }
  105067. else {
  105068. // console.log("Unhandled expression at line : " + i +'\n' + "with value : " + line);
  105069. }
  105070. }
  105071. //At the end of the file, add the last material
  105072. if (material) {
  105073. this.materials.push(material);
  105074. }
  105075. };
  105076. /**
  105077. * Gets the texture for the material.
  105078. *
  105079. * If the material is imported from input file,
  105080. * We sanitize the url to ensure it takes the textre from aside the material.
  105081. *
  105082. * @param rootUrl The root url to load from
  105083. * @param value The value stored in the mtl
  105084. * @return The Texture
  105085. */
  105086. MTLFileLoader._getTexture = function (rootUrl, value, scene) {
  105087. if (!value) {
  105088. return null;
  105089. }
  105090. var url = rootUrl;
  105091. // Load from input file.
  105092. if (rootUrl === "file:") {
  105093. var lastDelimiter = value.lastIndexOf("\\");
  105094. if (lastDelimiter === -1) {
  105095. lastDelimiter = value.lastIndexOf("/");
  105096. }
  105097. if (lastDelimiter > -1) {
  105098. url += value.substr(lastDelimiter + 1);
  105099. }
  105100. else {
  105101. url += value;
  105102. }
  105103. }
  105104. else {
  105105. url += value;
  105106. }
  105107. return new BABYLON.Texture(url, scene);
  105108. };
  105109. return MTLFileLoader;
  105110. }());
  105111. BABYLON.MTLFileLoader = MTLFileLoader;
  105112. var OBJFileLoader = /** @class */ (function () {
  105113. function OBJFileLoader() {
  105114. this.name = "obj";
  105115. this.extensions = ".obj";
  105116. this.obj = /^o/;
  105117. this.group = /^g/;
  105118. this.mtllib = /^mtllib /;
  105119. this.usemtl = /^usemtl /;
  105120. this.smooth = /^s /;
  105121. this.vertexPattern = /v( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)/;
  105122. // vn float float float
  105123. this.normalPattern = /vn( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)/;
  105124. // vt float float
  105125. this.uvPattern = /vt( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)/;
  105126. // f vertex vertex vertex ...
  105127. this.facePattern1 = /f\s+(([\d]{1,}[\s]?){3,})+/;
  105128. // f vertex/uvs vertex/uvs vertex/uvs ...
  105129. this.facePattern2 = /f\s+((([\d]{1,}\/[\d]{1,}[\s]?){3,})+)/;
  105130. // f vertex/uvs/normal vertex/uvs/normal vertex/uvs/normal ...
  105131. this.facePattern3 = /f\s+((([\d]{1,}\/[\d]{1,}\/[\d]{1,}[\s]?){3,})+)/;
  105132. // f vertex//normal vertex//normal vertex//normal ...
  105133. this.facePattern4 = /f\s+((([\d]{1,}\/\/[\d]{1,}[\s]?){3,})+)/;
  105134. }
  105135. /**
  105136. * Calls synchronously the MTL file attached to this obj.
  105137. * Load function or importMesh function don't enable to load 2 files in the same time asynchronously.
  105138. * Without this function materials are not displayed in the first frame (but displayed after).
  105139. * In consequence it is impossible to get material information in your HTML file
  105140. *
  105141. * @param url The URL of the MTL file
  105142. * @param rootUrl
  105143. * @param onSuccess Callback function to be called when the MTL file is loaded
  105144. * @private
  105145. */
  105146. OBJFileLoader.prototype._loadMTL = function (url, rootUrl, onSuccess) {
  105147. //The complete path to the mtl file
  105148. var pathOfFile = BABYLON.Tools.BaseUrl + rootUrl + url;
  105149. // Loads through the babylon tools to allow fileInput search.
  105150. BABYLON.Tools.LoadFile(pathOfFile, onSuccess, undefined, undefined, false, function () { console.warn("Error - Unable to load " + pathOfFile); });
  105151. };
  105152. OBJFileLoader.prototype.importMesh = function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  105153. //get the meshes from OBJ file
  105154. var loadedMeshes = this._parseSolid(meshesNames, scene, data, rootUrl);
  105155. //Push meshes from OBJ file into the variable mesh of this function
  105156. if (meshes) {
  105157. loadedMeshes.forEach(function (mesh) {
  105158. meshes.push(mesh);
  105159. });
  105160. }
  105161. return true;
  105162. };
  105163. OBJFileLoader.prototype.load = function (scene, data, rootUrl) {
  105164. //Get the 3D model
  105165. return this.importMesh(null, scene, data, rootUrl, null, null, null);
  105166. };
  105167. OBJFileLoader.prototype.loadAssetContainer = function (scene, data, rootUrl, onError) {
  105168. var container = new BABYLON.AssetContainer(scene);
  105169. this.importMesh(null, scene, data, rootUrl, container.meshes, null, null);
  105170. container.removeAllFromScene();
  105171. return container;
  105172. };
  105173. /**
  105174. * Read the OBJ file and create an Array of meshes.
  105175. * Each mesh contains all information given by the OBJ and the MTL file.
  105176. * i.e. vertices positions and indices, optional normals values, optional UV values, optional material
  105177. *
  105178. * @param meshesNames
  105179. * @param scene BABYLON.Scene The scene where are displayed the data
  105180. * @param data String The content of the obj file
  105181. * @param rootUrl String The path to the folder
  105182. * @returns Array<AbstractMesh>
  105183. * @private
  105184. */
  105185. OBJFileLoader.prototype._parseSolid = function (meshesNames, scene, data, rootUrl) {
  105186. var positions = []; //values for the positions of vertices
  105187. var normals = []; //Values for the normals
  105188. var uvs = []; //Values for the textures
  105189. var meshesFromObj = []; //[mesh] Contains all the obj meshes
  105190. var handledMesh; //The current mesh of meshes array
  105191. var indicesForBabylon = []; //The list of indices for VertexData
  105192. var wrappedPositionForBabylon = []; //The list of position in vectors
  105193. var wrappedUvsForBabylon = []; //Array with all value of uvs to match with the indices
  105194. var wrappedNormalsForBabylon = []; //Array with all value of normals to match with the indices
  105195. var tuplePosNorm = []; //Create a tuple with indice of Position, Normal, UV [pos, norm, uvs]
  105196. var curPositionInIndices = 0;
  105197. var hasMeshes = false; //Meshes are defined in the file
  105198. var unwrappedPositionsForBabylon = []; //Value of positionForBabylon w/o Vector3() [x,y,z]
  105199. var unwrappedNormalsForBabylon = []; //Value of normalsForBabylon w/o Vector3() [x,y,z]
  105200. var unwrappedUVForBabylon = []; //Value of uvsForBabylon w/o Vector3() [x,y,z]
  105201. var triangles = []; //Indices from new triangles coming from polygons
  105202. var materialNameFromObj = ""; //The name of the current material
  105203. var fileToLoad = ""; //The name of the mtlFile to load
  105204. var materialsFromMTLFile = new MTLFileLoader();
  105205. var objMeshName = ""; //The name of the current obj mesh
  105206. var increment = 1; //Id for meshes created by the multimaterial
  105207. var isFirstMaterial = true;
  105208. /**
  105209. * Search for obj in the given array.
  105210. * This function is called to check if a couple of data already exists in an array.
  105211. *
  105212. * If found, returns the index of the founded tuple index. Returns -1 if not found
  105213. * @param arr Array<{ normals: Array<number>, idx: Array<number> }>
  105214. * @param obj Array<number>
  105215. * @returns {boolean}
  105216. */
  105217. var isInArray = function (arr, obj) {
  105218. if (!arr[obj[0]])
  105219. arr[obj[0]] = { normals: [], idx: [] };
  105220. var idx = arr[obj[0]].normals.indexOf(obj[1]);
  105221. return idx === -1 ? -1 : arr[obj[0]].idx[idx];
  105222. };
  105223. var isInArrayUV = function (arr, obj) {
  105224. if (!arr[obj[0]])
  105225. arr[obj[0]] = { normals: [], idx: [], uv: [] };
  105226. var idx = arr[obj[0]].normals.indexOf(obj[1]);
  105227. if (idx != 1 && (obj[2] == arr[obj[0]].uv[idx])) {
  105228. return arr[obj[0]].idx[idx];
  105229. }
  105230. return -1;
  105231. };
  105232. /**
  105233. * This function set the data for each triangle.
  105234. * Data are position, normals and uvs
  105235. * If a tuple of (position, normal) is not set, add the data into the corresponding array
  105236. * If the tuple already exist, add only their indice
  105237. *
  105238. * @param indicePositionFromObj Integer The index in positions array
  105239. * @param indiceUvsFromObj Integer The index in uvs array
  105240. * @param indiceNormalFromObj Integer The index in normals array
  105241. * @param positionVectorFromOBJ Vector3 The value of position at index objIndice
  105242. * @param textureVectorFromOBJ Vector3 The value of uvs
  105243. * @param normalsVectorFromOBJ Vector3 The value of normals at index objNormale
  105244. */
  105245. var setData = function (indicePositionFromObj, indiceUvsFromObj, indiceNormalFromObj, positionVectorFromOBJ, textureVectorFromOBJ, normalsVectorFromOBJ) {
  105246. //Check if this tuple already exists in the list of tuples
  105247. var _index;
  105248. if (OBJFileLoader.OPTIMIZE_WITH_UV) {
  105249. _index = isInArrayUV(tuplePosNorm, [
  105250. indicePositionFromObj,
  105251. indiceNormalFromObj,
  105252. indiceUvsFromObj
  105253. ]);
  105254. }
  105255. else {
  105256. _index = isInArray(tuplePosNorm, [
  105257. indicePositionFromObj,
  105258. indiceNormalFromObj
  105259. ]);
  105260. }
  105261. //If it not exists
  105262. if (_index == -1) {
  105263. //Add an new indice.
  105264. //The array of indices is only an array with his length equal to the number of triangles - 1.
  105265. //We add vertices data in this order
  105266. indicesForBabylon.push(wrappedPositionForBabylon.length);
  105267. //Push the position of vertice for Babylon
  105268. //Each element is a BABYLON.Vector3(x,y,z)
  105269. wrappedPositionForBabylon.push(positionVectorFromOBJ);
  105270. //Push the uvs for Babylon
  105271. //Each element is a BABYLON.Vector3(u,v)
  105272. wrappedUvsForBabylon.push(textureVectorFromOBJ);
  105273. //Push the normals for Babylon
  105274. //Each element is a BABYLON.Vector3(x,y,z)
  105275. wrappedNormalsForBabylon.push(normalsVectorFromOBJ);
  105276. //Add the tuple in the comparison list
  105277. tuplePosNorm[indicePositionFromObj].normals.push(indiceNormalFromObj);
  105278. tuplePosNorm[indicePositionFromObj].idx.push(curPositionInIndices++);
  105279. if (OBJFileLoader.OPTIMIZE_WITH_UV)
  105280. tuplePosNorm[indicePositionFromObj].uv.push(indiceUvsFromObj);
  105281. }
  105282. else {
  105283. //The tuple already exists
  105284. //Add the index of the already existing tuple
  105285. //At this index we can get the value of position, normal and uvs of vertex
  105286. indicesForBabylon.push(_index);
  105287. }
  105288. };
  105289. /**
  105290. * Transform BABYLON.Vector() object onto 3 digits in an array
  105291. */
  105292. var unwrapData = function () {
  105293. //Every array has the same length
  105294. for (var l = 0; l < wrappedPositionForBabylon.length; l++) {
  105295. //Push the x, y, z values of each element in the unwrapped array
  105296. unwrappedPositionsForBabylon.push(wrappedPositionForBabylon[l].x, wrappedPositionForBabylon[l].y, wrappedPositionForBabylon[l].z);
  105297. unwrappedNormalsForBabylon.push(wrappedNormalsForBabylon[l].x, wrappedNormalsForBabylon[l].y, wrappedNormalsForBabylon[l].z);
  105298. unwrappedUVForBabylon.push(wrappedUvsForBabylon[l].x, wrappedUvsForBabylon[l].y); //z is an optional value not supported by BABYLON
  105299. }
  105300. // Reset arrays for the next new meshes
  105301. wrappedPositionForBabylon = [];
  105302. wrappedNormalsForBabylon = [];
  105303. wrappedUvsForBabylon = [];
  105304. tuplePosNorm = [];
  105305. curPositionInIndices = 0;
  105306. };
  105307. /**
  105308. * Create triangles from polygons by recursion
  105309. * The best to understand how it works is to draw it in the same time you get the recursion.
  105310. * It is important to notice that a triangle is a polygon
  105311. * We get 4 patterns of face defined in OBJ File :
  105312. * facePattern1 = ["1","2","3","4","5","6"]
  105313. * facePattern2 = ["1/1","2/2","3/3","4/4","5/5","6/6"]
  105314. * facePattern3 = ["1/1/1","2/2/2","3/3/3","4/4/4","5/5/5","6/6/6"]
  105315. * facePattern4 = ["1//1","2//2","3//3","4//4","5//5","6//6"]
  105316. * Each pattern is divided by the same method
  105317. * @param face Array[String] The indices of elements
  105318. * @param v Integer The variable to increment
  105319. */
  105320. var getTriangles = function (face, v) {
  105321. //Work for each element of the array
  105322. if (v + 1 < face.length) {
  105323. //Add on the triangle variable the indexes to obtain triangles
  105324. triangles.push(face[0], face[v], face[v + 1]);
  105325. //Incrementation for recursion
  105326. v += 1;
  105327. //Recursion
  105328. getTriangles(face, v);
  105329. }
  105330. //Result obtained after 2 iterations:
  105331. //Pattern1 => triangle = ["1","2","3","1","3","4"];
  105332. //Pattern2 => triangle = ["1/1","2/2","3/3","1/1","3/3","4/4"];
  105333. //Pattern3 => triangle = ["1/1/1","2/2/2","3/3/3","1/1/1","3/3/3","4/4/4"];
  105334. //Pattern4 => triangle = ["1//1","2//2","3//3","1//1","3//3","4//4"];
  105335. };
  105336. /**
  105337. * Create triangles and push the data for each polygon for the pattern 1
  105338. * In this pattern we get vertice positions
  105339. * @param face
  105340. * @param v
  105341. */
  105342. var setDataForCurrentFaceWithPattern1 = function (face, v) {
  105343. //Get the indices of triangles for each polygon
  105344. getTriangles(face, v);
  105345. //For each element in the triangles array.
  105346. //This var could contains 1 to an infinity of triangles
  105347. for (var k = 0; k < triangles.length; k++) {
  105348. // Set position indice
  105349. var indicePositionFromObj = parseInt(triangles[k]) - 1;
  105350. setData(indicePositionFromObj, 0, 0, //In the pattern 1, normals and uvs are not defined
  105351. positions[indicePositionFromObj], //Get the vectors data
  105352. BABYLON.Vector2.Zero(), BABYLON.Vector3.Up() //Create default vectors
  105353. );
  105354. }
  105355. //Reset variable for the next line
  105356. triangles = [];
  105357. };
  105358. /**
  105359. * Create triangles and push the data for each polygon for the pattern 2
  105360. * In this pattern we get vertice positions and uvsu
  105361. * @param face
  105362. * @param v
  105363. */
  105364. var setDataForCurrentFaceWithPattern2 = function (face, v) {
  105365. //Get the indices of triangles for each polygon
  105366. getTriangles(face, v);
  105367. for (var k = 0; k < triangles.length; k++) {
  105368. //triangle[k] = "1/1"
  105369. //Split the data for getting position and uv
  105370. var point = triangles[k].split("/"); // ["1", "1"]
  105371. //Set position indice
  105372. var indicePositionFromObj = parseInt(point[0]) - 1;
  105373. //Set uv indice
  105374. var indiceUvsFromObj = parseInt(point[1]) - 1;
  105375. setData(indicePositionFromObj, indiceUvsFromObj, 0, //Default value for normals
  105376. positions[indicePositionFromObj], //Get the values for each element
  105377. uvs[indiceUvsFromObj], BABYLON.Vector3.Up() //Default value for normals
  105378. );
  105379. }
  105380. //Reset variable for the next line
  105381. triangles = [];
  105382. };
  105383. /**
  105384. * Create triangles and push the data for each polygon for the pattern 3
  105385. * In this pattern we get vertice positions, uvs and normals
  105386. * @param face
  105387. * @param v
  105388. */
  105389. var setDataForCurrentFaceWithPattern3 = function (face, v) {
  105390. //Get the indices of triangles for each polygon
  105391. getTriangles(face, v);
  105392. for (var k = 0; k < triangles.length; k++) {
  105393. //triangle[k] = "1/1/1"
  105394. //Split the data for getting position, uv, and normals
  105395. var point = triangles[k].split("/"); // ["1", "1", "1"]
  105396. // Set position indice
  105397. var indicePositionFromObj = parseInt(point[0]) - 1;
  105398. // Set uv indice
  105399. var indiceUvsFromObj = parseInt(point[1]) - 1;
  105400. // Set normal indice
  105401. var indiceNormalFromObj = parseInt(point[2]) - 1;
  105402. setData(indicePositionFromObj, indiceUvsFromObj, indiceNormalFromObj, positions[indicePositionFromObj], uvs[indiceUvsFromObj], normals[indiceNormalFromObj] //Set the vector for each component
  105403. );
  105404. }
  105405. //Reset variable for the next line
  105406. triangles = [];
  105407. };
  105408. /**
  105409. * Create triangles and push the data for each polygon for the pattern 4
  105410. * In this pattern we get vertice positions and normals
  105411. * @param face
  105412. * @param v
  105413. */
  105414. var setDataForCurrentFaceWithPattern4 = function (face, v) {
  105415. getTriangles(face, v);
  105416. for (var k = 0; k < triangles.length; k++) {
  105417. //triangle[k] = "1//1"
  105418. //Split the data for getting position and normals
  105419. var point = triangles[k].split("//"); // ["1", "1"]
  105420. // We check indices, and normals
  105421. var indicePositionFromObj = parseInt(point[0]) - 1;
  105422. var indiceNormalFromObj = parseInt(point[1]) - 1;
  105423. setData(indicePositionFromObj, 1, //Default value for uv
  105424. indiceNormalFromObj, positions[indicePositionFromObj], //Get each vector of data
  105425. BABYLON.Vector2.Zero(), normals[indiceNormalFromObj]);
  105426. }
  105427. //Reset variable for the next line
  105428. triangles = [];
  105429. };
  105430. var addPreviousObjMesh = function () {
  105431. //Check if it is not the first mesh. Otherwise we don't have data.
  105432. if (meshesFromObj.length > 0) {
  105433. //Get the previous mesh for applying the data about the faces
  105434. //=> in obj file, faces definition append after the name of the mesh
  105435. handledMesh = meshesFromObj[meshesFromObj.length - 1];
  105436. //Set the data into Array for the mesh
  105437. unwrapData();
  105438. // Reverse tab. Otherwise face are displayed in the wrong sens
  105439. indicesForBabylon.reverse();
  105440. //Set the information for the mesh
  105441. //Slice the array to avoid rewriting because of the fact this is the same var which be rewrited
  105442. handledMesh.indices = indicesForBabylon.slice();
  105443. handledMesh.positions = unwrappedPositionsForBabylon.slice();
  105444. handledMesh.normals = unwrappedNormalsForBabylon.slice();
  105445. handledMesh.uvs = unwrappedUVForBabylon.slice();
  105446. //Reset the array for the next mesh
  105447. indicesForBabylon = [];
  105448. unwrappedPositionsForBabylon = [];
  105449. unwrappedNormalsForBabylon = [];
  105450. unwrappedUVForBabylon = [];
  105451. }
  105452. };
  105453. //Main function
  105454. //Split the file into lines
  105455. var lines = data.split('\n');
  105456. //Look at each line
  105457. for (var i = 0; i < lines.length; i++) {
  105458. var line = lines[i].trim();
  105459. var result;
  105460. //Comment or newLine
  105461. if (line.length === 0 || line.charAt(0) === '#') {
  105462. continue;
  105463. //Get information about one position possible for the vertices
  105464. }
  105465. else if ((result = this.vertexPattern.exec(line)) !== null) {
  105466. //Create a Vector3 with the position x, y, z
  105467. //Value of result:
  105468. // ["v 1.0 2.0 3.0", "1.0", "2.0", "3.0"]
  105469. //Add the Vector in the list of positions
  105470. positions.push(new BABYLON.Vector3(parseFloat(result[1]), parseFloat(result[2]), parseFloat(result[3])));
  105471. }
  105472. else if ((result = this.normalPattern.exec(line)) !== null) {
  105473. //Create a Vector3 with the normals x, y, z
  105474. //Value of result
  105475. // ["vn 1.0 2.0 3.0", "1.0", "2.0", "3.0"]
  105476. //Add the Vector in the list of normals
  105477. normals.push(new BABYLON.Vector3(parseFloat(result[1]), parseFloat(result[2]), parseFloat(result[3])));
  105478. }
  105479. else if ((result = this.uvPattern.exec(line)) !== null) {
  105480. //Create a Vector2 with the normals u, v
  105481. //Value of result
  105482. // ["vt 0.1 0.2 0.3", "0.1", "0.2"]
  105483. //Add the Vector in the list of uvs
  105484. uvs.push(new BABYLON.Vector2(parseFloat(result[1]), parseFloat(result[2])));
  105485. //Identify patterns of faces
  105486. //Face could be defined in different type of pattern
  105487. }
  105488. else if ((result = this.facePattern3.exec(line)) !== null) {
  105489. //Value of result:
  105490. //["f 1/1/1 2/2/2 3/3/3", "1/1/1 2/2/2 3/3/3"...]
  105491. //Set the data for this face
  105492. setDataForCurrentFaceWithPattern3(result[1].trim().split(" "), // ["1/1/1", "2/2/2", "3/3/3"]
  105493. 1);
  105494. }
  105495. else if ((result = this.facePattern4.exec(line)) !== null) {
  105496. //Value of result:
  105497. //["f 1//1 2//2 3//3", "1//1 2//2 3//3"...]
  105498. //Set the data for this face
  105499. setDataForCurrentFaceWithPattern4(result[1].trim().split(" "), // ["1//1", "2//2", "3//3"]
  105500. 1);
  105501. }
  105502. else if ((result = this.facePattern2.exec(line)) !== null) {
  105503. //Value of result:
  105504. //["f 1/1 2/2 3/3", "1/1 2/2 3/3"...]
  105505. //Set the data for this face
  105506. setDataForCurrentFaceWithPattern2(result[1].trim().split(" "), // ["1/1", "2/2", "3/3"]
  105507. 1);
  105508. }
  105509. else if ((result = this.facePattern1.exec(line)) !== null) {
  105510. //Value of result
  105511. //["f 1 2 3", "1 2 3"...]
  105512. //Set the data for this face
  105513. setDataForCurrentFaceWithPattern1(result[1].trim().split(" "), // ["1", "2", "3"]
  105514. 1);
  105515. //Define a mesh or an object
  105516. //Each time this keyword is analysed, create a new Object with all data for creating a babylonMesh
  105517. }
  105518. else if (this.group.test(line) || this.obj.test(line)) {
  105519. //Create a new mesh corresponding to the name of the group.
  105520. //Definition of the mesh
  105521. var objMesh =
  105522. //Set the name of the current obj mesh
  105523. {
  105524. name: line.substring(2).trim(),
  105525. indices: undefined,
  105526. positions: undefined,
  105527. normals: undefined,
  105528. uvs: undefined,
  105529. materialName: ""
  105530. };
  105531. addPreviousObjMesh();
  105532. //Push the last mesh created with only the name
  105533. meshesFromObj.push(objMesh);
  105534. //Set this variable to indicate that now meshesFromObj has objects defined inside
  105535. hasMeshes = true;
  105536. isFirstMaterial = true;
  105537. increment = 1;
  105538. //Keyword for applying a material
  105539. }
  105540. else if (this.usemtl.test(line)) {
  105541. //Get the name of the material
  105542. materialNameFromObj = line.substring(7).trim();
  105543. //If this new material is in the same mesh
  105544. if (!isFirstMaterial) {
  105545. //Set the data for the previous mesh
  105546. addPreviousObjMesh();
  105547. //Create a new mesh
  105548. var objMesh =
  105549. //Set the name of the current obj mesh
  105550. {
  105551. name: objMeshName + "_mm" + increment.toString(),
  105552. indices: undefined,
  105553. positions: undefined,
  105554. normals: undefined,
  105555. uvs: undefined,
  105556. materialName: materialNameFromObj
  105557. };
  105558. increment++;
  105559. //If meshes are already defined
  105560. meshesFromObj.push(objMesh);
  105561. }
  105562. //Set the material name if the previous line define a mesh
  105563. if (hasMeshes && isFirstMaterial) {
  105564. //Set the material name to the previous mesh (1 material per mesh)
  105565. meshesFromObj[meshesFromObj.length - 1].materialName = materialNameFromObj;
  105566. isFirstMaterial = false;
  105567. }
  105568. //Keyword for loading the mtl file
  105569. }
  105570. else if (this.mtllib.test(line)) {
  105571. //Get the name of mtl file
  105572. fileToLoad = line.substring(7).trim();
  105573. //Apply smoothing
  105574. }
  105575. else if (this.smooth.test(line)) {
  105576. // smooth shading => apply smoothing
  105577. //Toda y I don't know it work with babylon and with obj.
  105578. //With the obj file an integer is set
  105579. }
  105580. else {
  105581. //If there is another possibility
  105582. console.log("Unhandled expression at line : " + line);
  105583. }
  105584. }
  105585. //At the end of the file, add the last mesh into the meshesFromObj array
  105586. if (hasMeshes) {
  105587. //Set the data for the last mesh
  105588. handledMesh = meshesFromObj[meshesFromObj.length - 1];
  105589. //Reverse indices for displaying faces in the good sens
  105590. indicesForBabylon.reverse();
  105591. //Get the good array
  105592. unwrapData();
  105593. //Set array
  105594. handledMesh.indices = indicesForBabylon;
  105595. handledMesh.positions = unwrappedPositionsForBabylon;
  105596. handledMesh.normals = unwrappedNormalsForBabylon;
  105597. handledMesh.uvs = unwrappedUVForBabylon;
  105598. }
  105599. //If any o or g keyword found, create a mesj with a random id
  105600. if (!hasMeshes) {
  105601. // reverse tab of indices
  105602. indicesForBabylon.reverse();
  105603. //Get positions normals uvs
  105604. unwrapData();
  105605. //Set data for one mesh
  105606. meshesFromObj.push({
  105607. name: BABYLON.Geometry.RandomId(),
  105608. indices: indicesForBabylon,
  105609. positions: unwrappedPositionsForBabylon,
  105610. normals: unwrappedNormalsForBabylon,
  105611. uvs: unwrappedUVForBabylon,
  105612. materialName: materialNameFromObj
  105613. });
  105614. }
  105615. //Create a BABYLON.Mesh list
  105616. var babylonMeshesArray = []; //The mesh for babylon
  105617. var materialToUse = new Array();
  105618. //Set data for each mesh
  105619. for (var j = 0; j < meshesFromObj.length; j++) {
  105620. //check meshesNames (stlFileLoader)
  105621. if (meshesNames && meshesFromObj[j].name) {
  105622. if (meshesNames instanceof Array) {
  105623. if (meshesNames.indexOf(meshesFromObj[j].name) == -1) {
  105624. continue;
  105625. }
  105626. }
  105627. else {
  105628. if (meshesFromObj[j].name !== meshesNames) {
  105629. continue;
  105630. }
  105631. }
  105632. }
  105633. //Get the current mesh
  105634. //Set the data with VertexBuffer for each mesh
  105635. handledMesh = meshesFromObj[j];
  105636. //Create a BABYLON.Mesh with the name of the obj mesh
  105637. var babylonMesh = new BABYLON.Mesh(meshesFromObj[j].name, scene);
  105638. //Push the name of the material to an array
  105639. //This is indispensable for the importMesh function
  105640. materialToUse.push(meshesFromObj[j].materialName);
  105641. var vertexData = new BABYLON.VertexData(); //The container for the values
  105642. //Set the data for the babylonMesh
  105643. vertexData.positions = handledMesh.positions;
  105644. vertexData.normals = handledMesh.normals;
  105645. vertexData.uvs = handledMesh.uvs;
  105646. vertexData.indices = handledMesh.indices;
  105647. //Set the data from the VertexBuffer to the current BABYLON.Mesh
  105648. vertexData.applyToMesh(babylonMesh);
  105649. //Push the mesh into an array
  105650. babylonMeshesArray.push(babylonMesh);
  105651. }
  105652. //load the materials
  105653. //Check if we have a file to load
  105654. if (fileToLoad !== "") {
  105655. //Load the file synchronously
  105656. this._loadMTL(fileToLoad, rootUrl, function (dataLoaded) {
  105657. //Create materials thanks MTLLoader function
  105658. materialsFromMTLFile.parseMTL(scene, dataLoaded, rootUrl);
  105659. //Look at each material loaded in the mtl file
  105660. for (var n = 0; n < materialsFromMTLFile.materials.length; n++) {
  105661. //Three variables to get all meshes with the same material
  105662. var startIndex = 0;
  105663. var _indices = [];
  105664. var _index;
  105665. //The material from MTL file is used in the meshes loaded
  105666. //Push the indice in an array
  105667. //Check if the material is not used for another mesh
  105668. while ((_index = materialToUse.indexOf(materialsFromMTLFile.materials[n].name, startIndex)) > -1) {
  105669. _indices.push(_index);
  105670. startIndex = _index + 1;
  105671. }
  105672. //If the material is not used dispose it
  105673. if (_index == -1 && _indices.length == 0) {
  105674. //If the material is not needed, remove it
  105675. materialsFromMTLFile.materials[n].dispose();
  105676. }
  105677. else {
  105678. for (var o = 0; o < _indices.length; o++) {
  105679. //Apply the material to the BABYLON.Mesh for each mesh with the material
  105680. babylonMeshesArray[_indices[o]].material = materialsFromMTLFile.materials[n];
  105681. }
  105682. }
  105683. }
  105684. });
  105685. }
  105686. //Return an array with all BABYLON.Mesh
  105687. return babylonMeshesArray;
  105688. };
  105689. OBJFileLoader.OPTIMIZE_WITH_UV = false;
  105690. return OBJFileLoader;
  105691. }());
  105692. BABYLON.OBJFileLoader = OBJFileLoader;
  105693. if (BABYLON.SceneLoader) {
  105694. //Add this loader into the register plugin
  105695. BABYLON.SceneLoader.RegisterPlugin(new OBJFileLoader());
  105696. }
  105697. })(BABYLON || (BABYLON = {}));
  105698. //# sourceMappingURL=babylon.objFileLoader.js.map
  105699. var BABYLON;
  105700. (function (BABYLON) {
  105701. var GLTFLoaderCoordinateSystemMode;
  105702. (function (GLTFLoaderCoordinateSystemMode) {
  105703. /**
  105704. * Automatically convert the glTF right-handed data to the appropriate system based on the current coordinate system mode of the scene.
  105705. */
  105706. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["AUTO"] = 0] = "AUTO";
  105707. /**
  105708. * Sets the useRightHandedSystem flag on the scene.
  105709. */
  105710. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["FORCE_RIGHT_HANDED"] = 1] = "FORCE_RIGHT_HANDED";
  105711. })(GLTFLoaderCoordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode || (BABYLON.GLTFLoaderCoordinateSystemMode = {}));
  105712. var GLTFLoaderAnimationStartMode;
  105713. (function (GLTFLoaderAnimationStartMode) {
  105714. /**
  105715. * No animation will start.
  105716. */
  105717. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["NONE"] = 0] = "NONE";
  105718. /**
  105719. * The first animation will start.
  105720. */
  105721. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["FIRST"] = 1] = "FIRST";
  105722. /**
  105723. * All animations will start.
  105724. */
  105725. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["ALL"] = 2] = "ALL";
  105726. })(GLTFLoaderAnimationStartMode = BABYLON.GLTFLoaderAnimationStartMode || (BABYLON.GLTFLoaderAnimationStartMode = {}));
  105727. var GLTFLoaderState;
  105728. (function (GLTFLoaderState) {
  105729. GLTFLoaderState[GLTFLoaderState["Loading"] = 0] = "Loading";
  105730. GLTFLoaderState[GLTFLoaderState["Ready"] = 1] = "Ready";
  105731. GLTFLoaderState[GLTFLoaderState["Complete"] = 2] = "Complete";
  105732. })(GLTFLoaderState = BABYLON.GLTFLoaderState || (BABYLON.GLTFLoaderState = {}));
  105733. var GLTFFileLoader = /** @class */ (function () {
  105734. function GLTFFileLoader() {
  105735. // #region Common options
  105736. /**
  105737. * Raised when the asset has been parsed.
  105738. * The data.json property stores the glTF JSON.
  105739. * The data.bin property stores the BIN chunk from a glTF binary or null if the input is not a glTF binary.
  105740. */
  105741. this.onParsedObservable = new BABYLON.Observable();
  105742. // #endregion
  105743. // #region V2 options
  105744. /**
  105745. * The coordinate system mode (AUTO, FORCE_RIGHT_HANDED).
  105746. */
  105747. this.coordinateSystemMode = GLTFLoaderCoordinateSystemMode.AUTO;
  105748. /**
  105749. * The animation start mode (NONE, FIRST, ALL).
  105750. */
  105751. this.animationStartMode = GLTFLoaderAnimationStartMode.FIRST;
  105752. /**
  105753. * Set to true to compile materials before raising the success callback.
  105754. */
  105755. this.compileMaterials = false;
  105756. /**
  105757. * Set to true to also compile materials with clip planes.
  105758. */
  105759. this.useClipPlane = false;
  105760. /**
  105761. * Set to true to compile shadow generators before raising the success callback.
  105762. */
  105763. this.compileShadowGenerators = false;
  105764. /**
  105765. * Raised when the loader creates a mesh after parsing the glTF properties of the mesh.
  105766. */
  105767. this.onMeshLoadedObservable = new BABYLON.Observable();
  105768. /**
  105769. * Raised when the loader creates a texture after parsing the glTF properties of the texture.
  105770. */
  105771. this.onTextureLoadedObservable = new BABYLON.Observable();
  105772. /**
  105773. * Raised when the loader creates a material after parsing the glTF properties of the material.
  105774. */
  105775. this.onMaterialLoadedObservable = new BABYLON.Observable();
  105776. /**
  105777. * Raised when the loader creates an animation group after parsing the glTF properties of the animation.
  105778. */
  105779. this.onAnimationGroupLoadedObservable = new BABYLON.Observable();
  105780. /**
  105781. * Raised when the asset is completely loaded, immediately before the loader is disposed.
  105782. * For assets with LODs, raised when all of the LODs are complete.
  105783. * For assets without LODs, raised when the model is complete, immediately after onSuccess.
  105784. */
  105785. this.onCompleteObservable = new BABYLON.Observable();
  105786. /**
  105787. * Raised when the loader is disposed.
  105788. */
  105789. this.onDisposeObservable = new BABYLON.Observable();
  105790. /**
  105791. * Raised after a loader extension is created.
  105792. * Set additional options for a loader extension in this event.
  105793. */
  105794. this.onExtensionLoadedObservable = new BABYLON.Observable();
  105795. // #endregion
  105796. this._loader = null;
  105797. this.name = "gltf";
  105798. this.extensions = {
  105799. ".gltf": { isBinary: false },
  105800. ".glb": { isBinary: true }
  105801. };
  105802. }
  105803. Object.defineProperty(GLTFFileLoader.prototype, "onParsed", {
  105804. set: function (callback) {
  105805. if (this._onParsedObserver) {
  105806. this.onParsedObservable.remove(this._onParsedObserver);
  105807. }
  105808. this._onParsedObserver = this.onParsedObservable.add(callback);
  105809. },
  105810. enumerable: true,
  105811. configurable: true
  105812. });
  105813. Object.defineProperty(GLTFFileLoader.prototype, "onMeshLoaded", {
  105814. set: function (callback) {
  105815. if (this._onMeshLoadedObserver) {
  105816. this.onMeshLoadedObservable.remove(this._onMeshLoadedObserver);
  105817. }
  105818. this._onMeshLoadedObserver = this.onMeshLoadedObservable.add(callback);
  105819. },
  105820. enumerable: true,
  105821. configurable: true
  105822. });
  105823. Object.defineProperty(GLTFFileLoader.prototype, "onTextureLoaded", {
  105824. set: function (callback) {
  105825. if (this._onTextureLoadedObserver) {
  105826. this.onTextureLoadedObservable.remove(this._onTextureLoadedObserver);
  105827. }
  105828. this._onTextureLoadedObserver = this.onTextureLoadedObservable.add(callback);
  105829. },
  105830. enumerable: true,
  105831. configurable: true
  105832. });
  105833. Object.defineProperty(GLTFFileLoader.prototype, "onMaterialLoaded", {
  105834. set: function (callback) {
  105835. if (this._onMaterialLoadedObserver) {
  105836. this.onMaterialLoadedObservable.remove(this._onMaterialLoadedObserver);
  105837. }
  105838. this._onMaterialLoadedObserver = this.onMaterialLoadedObservable.add(callback);
  105839. },
  105840. enumerable: true,
  105841. configurable: true
  105842. });
  105843. Object.defineProperty(GLTFFileLoader.prototype, "onAnimationGroupLoaded", {
  105844. set: function (callback) {
  105845. if (this._onAnimationGroupLoadedObserver) {
  105846. this.onAnimationGroupLoadedObservable.remove(this._onAnimationGroupLoadedObserver);
  105847. }
  105848. this._onAnimationGroupLoadedObserver = this.onAnimationGroupLoadedObservable.add(callback);
  105849. },
  105850. enumerable: true,
  105851. configurable: true
  105852. });
  105853. Object.defineProperty(GLTFFileLoader.prototype, "onComplete", {
  105854. set: function (callback) {
  105855. if (this._onCompleteObserver) {
  105856. this.onCompleteObservable.remove(this._onCompleteObserver);
  105857. }
  105858. this._onCompleteObserver = this.onCompleteObservable.add(callback);
  105859. },
  105860. enumerable: true,
  105861. configurable: true
  105862. });
  105863. Object.defineProperty(GLTFFileLoader.prototype, "onDispose", {
  105864. set: function (callback) {
  105865. if (this._onDisposeObserver) {
  105866. this.onDisposeObservable.remove(this._onDisposeObserver);
  105867. }
  105868. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  105869. },
  105870. enumerable: true,
  105871. configurable: true
  105872. });
  105873. Object.defineProperty(GLTFFileLoader.prototype, "onExtensionLoaded", {
  105874. set: function (callback) {
  105875. if (this._onExtensionLoadedObserver) {
  105876. this.onExtensionLoadedObservable.remove(this._onExtensionLoadedObserver);
  105877. }
  105878. this._onExtensionLoadedObserver = this.onExtensionLoadedObservable.add(callback);
  105879. },
  105880. enumerable: true,
  105881. configurable: true
  105882. });
  105883. /**
  105884. * Gets a promise that resolves when the asset is completely loaded.
  105885. * @returns A promise that resolves when the asset is completely loaded.
  105886. */
  105887. GLTFFileLoader.prototype.whenCompleteAsync = function () {
  105888. var _this = this;
  105889. return new Promise(function (resolve) {
  105890. _this.onCompleteObservable.add(function () {
  105891. resolve();
  105892. }, undefined, undefined, undefined, true);
  105893. });
  105894. };
  105895. Object.defineProperty(GLTFFileLoader.prototype, "loaderState", {
  105896. /**
  105897. * The loader state or null if not active.
  105898. */
  105899. get: function () {
  105900. return this._loader ? this._loader.state : null;
  105901. },
  105902. enumerable: true,
  105903. configurable: true
  105904. });
  105905. /**
  105906. * Disposes the loader, releases resources during load, and cancels any outstanding requests.
  105907. */
  105908. GLTFFileLoader.prototype.dispose = function () {
  105909. if (this._loader) {
  105910. this._loader.dispose();
  105911. this._loader = null;
  105912. }
  105913. this.onMeshLoadedObservable.clear();
  105914. this.onTextureLoadedObservable.clear();
  105915. this.onMaterialLoadedObservable.clear();
  105916. this.onDisposeObservable.notifyObservers(this);
  105917. this.onDisposeObservable.clear();
  105918. };
  105919. GLTFFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  105920. var _this = this;
  105921. return Promise.resolve().then(function () {
  105922. var loaderData = _this._parse(data);
  105923. _this._loader = _this._getLoader(loaderData);
  105924. return _this._loader.importMeshAsync(meshesNames, scene, loaderData, rootUrl, onProgress);
  105925. });
  105926. };
  105927. GLTFFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  105928. var _this = this;
  105929. return Promise.resolve().then(function () {
  105930. var loaderData = _this._parse(data);
  105931. _this._loader = _this._getLoader(loaderData);
  105932. return _this._loader.loadAsync(scene, loaderData, rootUrl, onProgress);
  105933. });
  105934. };
  105935. GLTFFileLoader.prototype.loadAssetContainerAsync = function (scene, data, rootUrl, onProgress) {
  105936. var _this = this;
  105937. return Promise.resolve().then(function () {
  105938. var loaderData = _this._parse(data);
  105939. _this._loader = _this._getLoader(loaderData);
  105940. return _this._loader.importMeshAsync(null, scene, loaderData, rootUrl, onProgress).then(function (result) {
  105941. var container = new BABYLON.AssetContainer(scene);
  105942. Array.prototype.push.apply(container.meshes, result.meshes);
  105943. Array.prototype.push.apply(container.particleSystems, result.particleSystems);
  105944. Array.prototype.push.apply(container.skeletons, result.skeletons);
  105945. container.removeAllFromScene();
  105946. return container;
  105947. });
  105948. });
  105949. };
  105950. GLTFFileLoader.prototype.canDirectLoad = function (data) {
  105951. return ((data.indexOf("scene") !== -1) && (data.indexOf("node") !== -1));
  105952. };
  105953. GLTFFileLoader.prototype.createPlugin = function () {
  105954. return new GLTFFileLoader();
  105955. };
  105956. GLTFFileLoader.prototype._parse = function (data) {
  105957. var parsedData;
  105958. if (data instanceof ArrayBuffer) {
  105959. parsedData = GLTFFileLoader._parseBinary(data);
  105960. }
  105961. else {
  105962. parsedData = {
  105963. json: JSON.parse(data),
  105964. bin: null
  105965. };
  105966. }
  105967. this.onParsedObservable.notifyObservers(parsedData);
  105968. this.onParsedObservable.clear();
  105969. return parsedData;
  105970. };
  105971. GLTFFileLoader.prototype._getLoader = function (loaderData) {
  105972. var _this = this;
  105973. var loaderVersion = { major: 2, minor: 0 };
  105974. var asset = loaderData.json.asset || {};
  105975. var version = GLTFFileLoader._parseVersion(asset.version);
  105976. if (!version) {
  105977. throw new Error("Invalid version: " + asset.version);
  105978. }
  105979. if (asset.minVersion !== undefined) {
  105980. var minVersion = GLTFFileLoader._parseVersion(asset.minVersion);
  105981. if (!minVersion) {
  105982. throw new Error("Invalid minimum version: " + asset.minVersion);
  105983. }
  105984. if (GLTFFileLoader._compareVersion(minVersion, loaderVersion) > 0) {
  105985. throw new Error("Incompatible minimum version: " + asset.minVersion);
  105986. }
  105987. }
  105988. var createLoaders = {
  105989. 1: GLTFFileLoader.CreateGLTFLoaderV1,
  105990. 2: GLTFFileLoader.CreateGLTFLoaderV2
  105991. };
  105992. var createLoader = createLoaders[version.major];
  105993. if (!createLoader) {
  105994. throw new Error("Unsupported version: " + asset.version);
  105995. }
  105996. var loader = createLoader();
  105997. loader.coordinateSystemMode = this.coordinateSystemMode;
  105998. loader.animationStartMode = this.animationStartMode;
  105999. loader.compileMaterials = this.compileMaterials;
  106000. loader.useClipPlane = this.useClipPlane;
  106001. loader.compileShadowGenerators = this.compileShadowGenerators;
  106002. loader.onMeshLoadedObservable.add(function (mesh) { return _this.onMeshLoadedObservable.notifyObservers(mesh); });
  106003. loader.onTextureLoadedObservable.add(function (texture) { return _this.onTextureLoadedObservable.notifyObservers(texture); });
  106004. loader.onMaterialLoadedObservable.add(function (material) { return _this.onMaterialLoadedObservable.notifyObservers(material); });
  106005. loader.onExtensionLoadedObservable.add(function (extension) { return _this.onExtensionLoadedObservable.notifyObservers(extension); });
  106006. loader.onCompleteObservable.add(function () {
  106007. _this.onMeshLoadedObservable.clear();
  106008. _this.onTextureLoadedObservable.clear();
  106009. _this.onMaterialLoadedObservable.clear();
  106010. _this.onCompleteObservable.notifyObservers(_this);
  106011. _this.onCompleteObservable.clear();
  106012. });
  106013. return loader;
  106014. };
  106015. GLTFFileLoader._parseBinary = function (data) {
  106016. var Binary = {
  106017. Magic: 0x46546C67
  106018. };
  106019. var binaryReader = new BinaryReader(data);
  106020. var magic = binaryReader.readUint32();
  106021. if (magic !== Binary.Magic) {
  106022. throw new Error("Unexpected magic: " + magic);
  106023. }
  106024. var version = binaryReader.readUint32();
  106025. switch (version) {
  106026. case 1: return GLTFFileLoader._parseV1(binaryReader);
  106027. case 2: return GLTFFileLoader._parseV2(binaryReader);
  106028. }
  106029. throw new Error("Unsupported version: " + version);
  106030. };
  106031. GLTFFileLoader._parseV1 = function (binaryReader) {
  106032. var ContentFormat = {
  106033. JSON: 0
  106034. };
  106035. var length = binaryReader.readUint32();
  106036. if (length != binaryReader.getLength()) {
  106037. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  106038. }
  106039. var contentLength = binaryReader.readUint32();
  106040. var contentFormat = binaryReader.readUint32();
  106041. var content;
  106042. switch (contentFormat) {
  106043. case ContentFormat.JSON: {
  106044. content = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(contentLength)));
  106045. break;
  106046. }
  106047. default: {
  106048. throw new Error("Unexpected content format: " + contentFormat);
  106049. }
  106050. }
  106051. var bytesRemaining = binaryReader.getLength() - binaryReader.getPosition();
  106052. var body = binaryReader.readUint8Array(bytesRemaining);
  106053. return {
  106054. json: content,
  106055. bin: body
  106056. };
  106057. };
  106058. GLTFFileLoader._parseV2 = function (binaryReader) {
  106059. var ChunkFormat = {
  106060. JSON: 0x4E4F534A,
  106061. BIN: 0x004E4942
  106062. };
  106063. var length = binaryReader.readUint32();
  106064. if (length !== binaryReader.getLength()) {
  106065. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  106066. }
  106067. // JSON chunk
  106068. var chunkLength = binaryReader.readUint32();
  106069. var chunkFormat = binaryReader.readUint32();
  106070. if (chunkFormat !== ChunkFormat.JSON) {
  106071. throw new Error("First chunk format is not JSON");
  106072. }
  106073. var json = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(chunkLength)));
  106074. // Look for BIN chunk
  106075. var bin = null;
  106076. while (binaryReader.getPosition() < binaryReader.getLength()) {
  106077. var chunkLength_1 = binaryReader.readUint32();
  106078. var chunkFormat_1 = binaryReader.readUint32();
  106079. switch (chunkFormat_1) {
  106080. case ChunkFormat.JSON: {
  106081. throw new Error("Unexpected JSON chunk");
  106082. }
  106083. case ChunkFormat.BIN: {
  106084. bin = binaryReader.readUint8Array(chunkLength_1);
  106085. break;
  106086. }
  106087. default: {
  106088. // ignore unrecognized chunkFormat
  106089. binaryReader.skipBytes(chunkLength_1);
  106090. break;
  106091. }
  106092. }
  106093. }
  106094. return {
  106095. json: json,
  106096. bin: bin
  106097. };
  106098. };
  106099. GLTFFileLoader._parseVersion = function (version) {
  106100. if (version === "1.0" || version === "1.0.1") {
  106101. return {
  106102. major: 1,
  106103. minor: 0
  106104. };
  106105. }
  106106. var match = (version + "").match(/^(\d+)\.(\d+)/);
  106107. if (!match) {
  106108. return null;
  106109. }
  106110. return {
  106111. major: parseInt(match[1]),
  106112. minor: parseInt(match[2])
  106113. };
  106114. };
  106115. GLTFFileLoader._compareVersion = function (a, b) {
  106116. if (a.major > b.major)
  106117. return 1;
  106118. if (a.major < b.major)
  106119. return -1;
  106120. if (a.minor > b.minor)
  106121. return 1;
  106122. if (a.minor < b.minor)
  106123. return -1;
  106124. return 0;
  106125. };
  106126. GLTFFileLoader._decodeBufferToText = function (buffer) {
  106127. var result = "";
  106128. var length = buffer.byteLength;
  106129. for (var i = 0; i < length; i++) {
  106130. result += String.fromCharCode(buffer[i]);
  106131. }
  106132. return result;
  106133. };
  106134. // #endregion
  106135. // #region V1 options
  106136. GLTFFileLoader.IncrementalLoading = true;
  106137. GLTFFileLoader.HomogeneousCoordinates = false;
  106138. return GLTFFileLoader;
  106139. }());
  106140. BABYLON.GLTFFileLoader = GLTFFileLoader;
  106141. var BinaryReader = /** @class */ (function () {
  106142. function BinaryReader(arrayBuffer) {
  106143. this._arrayBuffer = arrayBuffer;
  106144. this._dataView = new DataView(arrayBuffer);
  106145. this._byteOffset = 0;
  106146. }
  106147. BinaryReader.prototype.getPosition = function () {
  106148. return this._byteOffset;
  106149. };
  106150. BinaryReader.prototype.getLength = function () {
  106151. return this._arrayBuffer.byteLength;
  106152. };
  106153. BinaryReader.prototype.readUint32 = function () {
  106154. var value = this._dataView.getUint32(this._byteOffset, true);
  106155. this._byteOffset += 4;
  106156. return value;
  106157. };
  106158. BinaryReader.prototype.readUint8Array = function (length) {
  106159. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  106160. this._byteOffset += length;
  106161. return value;
  106162. };
  106163. BinaryReader.prototype.skipBytes = function (length) {
  106164. this._byteOffset += length;
  106165. };
  106166. return BinaryReader;
  106167. }());
  106168. if (BABYLON.SceneLoader) {
  106169. BABYLON.SceneLoader.RegisterPlugin(new GLTFFileLoader());
  106170. }
  106171. })(BABYLON || (BABYLON = {}));
  106172. //# sourceMappingURL=babylon.glTFFileLoader.js.map
  106173. var BABYLON;
  106174. (function (BABYLON) {
  106175. var GLTF1;
  106176. (function (GLTF1) {
  106177. /**
  106178. * Enums
  106179. */
  106180. var EComponentType;
  106181. (function (EComponentType) {
  106182. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  106183. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  106184. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  106185. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  106186. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  106187. })(EComponentType = GLTF1.EComponentType || (GLTF1.EComponentType = {}));
  106188. var EShaderType;
  106189. (function (EShaderType) {
  106190. EShaderType[EShaderType["FRAGMENT"] = 35632] = "FRAGMENT";
  106191. EShaderType[EShaderType["VERTEX"] = 35633] = "VERTEX";
  106192. })(EShaderType = GLTF1.EShaderType || (GLTF1.EShaderType = {}));
  106193. var EParameterType;
  106194. (function (EParameterType) {
  106195. EParameterType[EParameterType["BYTE"] = 5120] = "BYTE";
  106196. EParameterType[EParameterType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  106197. EParameterType[EParameterType["SHORT"] = 5122] = "SHORT";
  106198. EParameterType[EParameterType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  106199. EParameterType[EParameterType["INT"] = 5124] = "INT";
  106200. EParameterType[EParameterType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  106201. EParameterType[EParameterType["FLOAT"] = 5126] = "FLOAT";
  106202. EParameterType[EParameterType["FLOAT_VEC2"] = 35664] = "FLOAT_VEC2";
  106203. EParameterType[EParameterType["FLOAT_VEC3"] = 35665] = "FLOAT_VEC3";
  106204. EParameterType[EParameterType["FLOAT_VEC4"] = 35666] = "FLOAT_VEC4";
  106205. EParameterType[EParameterType["INT_VEC2"] = 35667] = "INT_VEC2";
  106206. EParameterType[EParameterType["INT_VEC3"] = 35668] = "INT_VEC3";
  106207. EParameterType[EParameterType["INT_VEC4"] = 35669] = "INT_VEC4";
  106208. EParameterType[EParameterType["BOOL"] = 35670] = "BOOL";
  106209. EParameterType[EParameterType["BOOL_VEC2"] = 35671] = "BOOL_VEC2";
  106210. EParameterType[EParameterType["BOOL_VEC3"] = 35672] = "BOOL_VEC3";
  106211. EParameterType[EParameterType["BOOL_VEC4"] = 35673] = "BOOL_VEC4";
  106212. EParameterType[EParameterType["FLOAT_MAT2"] = 35674] = "FLOAT_MAT2";
  106213. EParameterType[EParameterType["FLOAT_MAT3"] = 35675] = "FLOAT_MAT3";
  106214. EParameterType[EParameterType["FLOAT_MAT4"] = 35676] = "FLOAT_MAT4";
  106215. EParameterType[EParameterType["SAMPLER_2D"] = 35678] = "SAMPLER_2D";
  106216. })(EParameterType = GLTF1.EParameterType || (GLTF1.EParameterType = {}));
  106217. var ETextureWrapMode;
  106218. (function (ETextureWrapMode) {
  106219. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  106220. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  106221. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  106222. })(ETextureWrapMode = GLTF1.ETextureWrapMode || (GLTF1.ETextureWrapMode = {}));
  106223. var ETextureFilterType;
  106224. (function (ETextureFilterType) {
  106225. ETextureFilterType[ETextureFilterType["NEAREST"] = 9728] = "NEAREST";
  106226. ETextureFilterType[ETextureFilterType["LINEAR"] = 9728] = "LINEAR";
  106227. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  106228. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  106229. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  106230. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  106231. })(ETextureFilterType = GLTF1.ETextureFilterType || (GLTF1.ETextureFilterType = {}));
  106232. var ETextureFormat;
  106233. (function (ETextureFormat) {
  106234. ETextureFormat[ETextureFormat["ALPHA"] = 6406] = "ALPHA";
  106235. ETextureFormat[ETextureFormat["RGB"] = 6407] = "RGB";
  106236. ETextureFormat[ETextureFormat["RGBA"] = 6408] = "RGBA";
  106237. ETextureFormat[ETextureFormat["LUMINANCE"] = 6409] = "LUMINANCE";
  106238. ETextureFormat[ETextureFormat["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA";
  106239. })(ETextureFormat = GLTF1.ETextureFormat || (GLTF1.ETextureFormat = {}));
  106240. var ECullingType;
  106241. (function (ECullingType) {
  106242. ECullingType[ECullingType["FRONT"] = 1028] = "FRONT";
  106243. ECullingType[ECullingType["BACK"] = 1029] = "BACK";
  106244. ECullingType[ECullingType["FRONT_AND_BACK"] = 1032] = "FRONT_AND_BACK";
  106245. })(ECullingType = GLTF1.ECullingType || (GLTF1.ECullingType = {}));
  106246. var EBlendingFunction;
  106247. (function (EBlendingFunction) {
  106248. EBlendingFunction[EBlendingFunction["ZERO"] = 0] = "ZERO";
  106249. EBlendingFunction[EBlendingFunction["ONE"] = 1] = "ONE";
  106250. EBlendingFunction[EBlendingFunction["SRC_COLOR"] = 768] = "SRC_COLOR";
  106251. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_COLOR"] = 769] = "ONE_MINUS_SRC_COLOR";
  106252. EBlendingFunction[EBlendingFunction["DST_COLOR"] = 774] = "DST_COLOR";
  106253. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_COLOR"] = 775] = "ONE_MINUS_DST_COLOR";
  106254. EBlendingFunction[EBlendingFunction["SRC_ALPHA"] = 770] = "SRC_ALPHA";
  106255. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_ALPHA"] = 771] = "ONE_MINUS_SRC_ALPHA";
  106256. EBlendingFunction[EBlendingFunction["DST_ALPHA"] = 772] = "DST_ALPHA";
  106257. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_ALPHA"] = 773] = "ONE_MINUS_DST_ALPHA";
  106258. EBlendingFunction[EBlendingFunction["CONSTANT_COLOR"] = 32769] = "CONSTANT_COLOR";
  106259. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_COLOR"] = 32770] = "ONE_MINUS_CONSTANT_COLOR";
  106260. EBlendingFunction[EBlendingFunction["CONSTANT_ALPHA"] = 32771] = "CONSTANT_ALPHA";
  106261. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_ALPHA"] = 32772] = "ONE_MINUS_CONSTANT_ALPHA";
  106262. EBlendingFunction[EBlendingFunction["SRC_ALPHA_SATURATE"] = 776] = "SRC_ALPHA_SATURATE";
  106263. })(EBlendingFunction = GLTF1.EBlendingFunction || (GLTF1.EBlendingFunction = {}));
  106264. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  106265. })(BABYLON || (BABYLON = {}));
  106266. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  106267. var BABYLON;
  106268. (function (BABYLON) {
  106269. var GLTF1;
  106270. (function (GLTF1) {
  106271. /**
  106272. * Tokenizer. Used for shaders compatibility
  106273. * Automatically map world, view, projection, worldViewProjection, attributes and so on
  106274. */
  106275. var ETokenType;
  106276. (function (ETokenType) {
  106277. ETokenType[ETokenType["IDENTIFIER"] = 1] = "IDENTIFIER";
  106278. ETokenType[ETokenType["UNKNOWN"] = 2] = "UNKNOWN";
  106279. ETokenType[ETokenType["END_OF_INPUT"] = 3] = "END_OF_INPUT";
  106280. })(ETokenType || (ETokenType = {}));
  106281. var Tokenizer = /** @class */ (function () {
  106282. function Tokenizer(toParse) {
  106283. this._pos = 0;
  106284. this.isLetterOrDigitPattern = /^[a-zA-Z0-9]+$/;
  106285. this._toParse = toParse;
  106286. this._maxPos = toParse.length;
  106287. }
  106288. Tokenizer.prototype.getNextToken = function () {
  106289. if (this.isEnd())
  106290. return ETokenType.END_OF_INPUT;
  106291. this.currentString = this.read();
  106292. this.currentToken = ETokenType.UNKNOWN;
  106293. if (this.currentString === "_" || this.isLetterOrDigitPattern.test(this.currentString)) {
  106294. this.currentToken = ETokenType.IDENTIFIER;
  106295. this.currentIdentifier = this.currentString;
  106296. while (!this.isEnd() && (this.isLetterOrDigitPattern.test(this.currentString = this.peek()) || this.currentString === "_")) {
  106297. this.currentIdentifier += this.currentString;
  106298. this.forward();
  106299. }
  106300. }
  106301. return this.currentToken;
  106302. };
  106303. Tokenizer.prototype.peek = function () {
  106304. return this._toParse[this._pos];
  106305. };
  106306. Tokenizer.prototype.read = function () {
  106307. return this._toParse[this._pos++];
  106308. };
  106309. Tokenizer.prototype.forward = function () {
  106310. this._pos++;
  106311. };
  106312. Tokenizer.prototype.isEnd = function () {
  106313. return this._pos >= this._maxPos;
  106314. };
  106315. return Tokenizer;
  106316. }());
  106317. /**
  106318. * Values
  106319. */
  106320. var glTFTransforms = ["MODEL", "VIEW", "PROJECTION", "MODELVIEW", "MODELVIEWPROJECTION", "JOINTMATRIX"];
  106321. var babylonTransforms = ["world", "view", "projection", "worldView", "worldViewProjection", "mBones"];
  106322. var glTFAnimationPaths = ["translation", "rotation", "scale"];
  106323. var babylonAnimationPaths = ["position", "rotationQuaternion", "scaling"];
  106324. /**
  106325. * Parse
  106326. */
  106327. var parseBuffers = function (parsedBuffers, gltfRuntime) {
  106328. for (var buf in parsedBuffers) {
  106329. var parsedBuffer = parsedBuffers[buf];
  106330. gltfRuntime.buffers[buf] = parsedBuffer;
  106331. gltfRuntime.buffersCount++;
  106332. }
  106333. };
  106334. var parseShaders = function (parsedShaders, gltfRuntime) {
  106335. for (var sha in parsedShaders) {
  106336. var parsedShader = parsedShaders[sha];
  106337. gltfRuntime.shaders[sha] = parsedShader;
  106338. gltfRuntime.shaderscount++;
  106339. }
  106340. };
  106341. var parseObject = function (parsedObjects, runtimeProperty, gltfRuntime) {
  106342. for (var object in parsedObjects) {
  106343. var parsedObject = parsedObjects[object];
  106344. gltfRuntime[runtimeProperty][object] = parsedObject;
  106345. }
  106346. };
  106347. /**
  106348. * Utils
  106349. */
  106350. var normalizeUVs = function (buffer) {
  106351. if (!buffer) {
  106352. return;
  106353. }
  106354. for (var i = 0; i < buffer.length / 2; i++) {
  106355. buffer[i * 2 + 1] = 1.0 - buffer[i * 2 + 1];
  106356. }
  106357. };
  106358. var getAttribute = function (attributeParameter) {
  106359. if (attributeParameter.semantic === "NORMAL") {
  106360. return "normal";
  106361. }
  106362. else if (attributeParameter.semantic === "POSITION") {
  106363. return "position";
  106364. }
  106365. else if (attributeParameter.semantic === "JOINT") {
  106366. return "matricesIndices";
  106367. }
  106368. else if (attributeParameter.semantic === "WEIGHT") {
  106369. return "matricesWeights";
  106370. }
  106371. else if (attributeParameter.semantic === "COLOR") {
  106372. return "color";
  106373. }
  106374. else if (attributeParameter.semantic && attributeParameter.semantic.indexOf("TEXCOORD_") !== -1) {
  106375. var channel = Number(attributeParameter.semantic.split("_")[1]);
  106376. return "uv" + (channel === 0 ? "" : channel + 1);
  106377. }
  106378. return null;
  106379. };
  106380. /**
  106381. * Loads and creates animations
  106382. */
  106383. var loadAnimations = function (gltfRuntime) {
  106384. for (var anim in gltfRuntime.animations) {
  106385. var animation = gltfRuntime.animations[anim];
  106386. if (!animation.channels || !animation.samplers) {
  106387. continue;
  106388. }
  106389. var lastAnimation = null;
  106390. for (var i = 0; i < animation.channels.length; i++) {
  106391. // Get parameters and load buffers
  106392. var channel = animation.channels[i];
  106393. var sampler = animation.samplers[channel.sampler];
  106394. if (!sampler) {
  106395. continue;
  106396. }
  106397. var inputData = null;
  106398. var outputData = null;
  106399. if (animation.parameters) {
  106400. inputData = animation.parameters[sampler.input];
  106401. outputData = animation.parameters[sampler.output];
  106402. }
  106403. else {
  106404. inputData = sampler.input;
  106405. outputData = sampler.output;
  106406. }
  106407. var bufferInput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[inputData]);
  106408. var bufferOutput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[outputData]);
  106409. var targetID = channel.target.id;
  106410. var targetNode = gltfRuntime.scene.getNodeByID(targetID);
  106411. if (targetNode === null) {
  106412. targetNode = gltfRuntime.scene.getNodeByName(targetID);
  106413. }
  106414. if (targetNode === null) {
  106415. BABYLON.Tools.Warn("Creating animation named " + anim + ". But cannot find node named " + targetID + " to attach to");
  106416. continue;
  106417. }
  106418. var isBone = targetNode instanceof BABYLON.Bone;
  106419. // Get target path (position, rotation or scaling)
  106420. var targetPath = channel.target.path;
  106421. var targetPathIndex = glTFAnimationPaths.indexOf(targetPath);
  106422. if (targetPathIndex !== -1) {
  106423. targetPath = babylonAnimationPaths[targetPathIndex];
  106424. }
  106425. // Determine animation type
  106426. var animationType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  106427. if (!isBone) {
  106428. if (targetPath === "rotationQuaternion") {
  106429. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  106430. targetNode.rotationQuaternion = new BABYLON.Quaternion();
  106431. }
  106432. else {
  106433. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  106434. }
  106435. }
  106436. // Create animation and key frames
  106437. var babylonAnimation = null;
  106438. var keys = [];
  106439. var arrayOffset = 0;
  106440. var modifyKey = false;
  106441. if (isBone && lastAnimation && lastAnimation.getKeys().length === bufferInput.length) {
  106442. babylonAnimation = lastAnimation;
  106443. modifyKey = true;
  106444. }
  106445. if (!modifyKey) {
  106446. babylonAnimation = new BABYLON.Animation(anim, isBone ? "_matrix" : targetPath, 1, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  106447. }
  106448. // For each frame
  106449. for (var j = 0; j < bufferInput.length; j++) {
  106450. var value = null;
  106451. if (targetPath === "rotationQuaternion") {
  106452. value = BABYLON.Quaternion.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2], bufferOutput[arrayOffset + 3]]);
  106453. arrayOffset += 4;
  106454. }
  106455. else {
  106456. value = BABYLON.Vector3.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2]]);
  106457. arrayOffset += 3;
  106458. }
  106459. if (isBone) {
  106460. var bone = targetNode;
  106461. var translation = BABYLON.Vector3.Zero();
  106462. var rotationQuaternion = new BABYLON.Quaternion();
  106463. var scaling = BABYLON.Vector3.Zero();
  106464. // Warning on decompose
  106465. var mat = bone.getBaseMatrix();
  106466. if (modifyKey && lastAnimation) {
  106467. mat = lastAnimation.getKeys()[j].value;
  106468. }
  106469. mat.decompose(scaling, rotationQuaternion, translation);
  106470. if (targetPath === "position") {
  106471. translation = value;
  106472. }
  106473. else if (targetPath === "rotationQuaternion") {
  106474. rotationQuaternion = value;
  106475. }
  106476. else {
  106477. scaling = value;
  106478. }
  106479. value = BABYLON.Matrix.Compose(scaling, rotationQuaternion, translation);
  106480. }
  106481. if (!modifyKey) {
  106482. keys.push({
  106483. frame: bufferInput[j],
  106484. value: value
  106485. });
  106486. }
  106487. else if (lastAnimation) {
  106488. lastAnimation.getKeys()[j].value = value;
  106489. }
  106490. }
  106491. // Finish
  106492. if (!modifyKey && babylonAnimation) {
  106493. babylonAnimation.setKeys(keys);
  106494. targetNode.animations.push(babylonAnimation);
  106495. }
  106496. lastAnimation = babylonAnimation;
  106497. gltfRuntime.scene.stopAnimation(targetNode);
  106498. gltfRuntime.scene.beginAnimation(targetNode, 0, bufferInput[bufferInput.length - 1], true, 1.0);
  106499. }
  106500. }
  106501. };
  106502. /**
  106503. * Returns the bones transformation matrix
  106504. */
  106505. var configureBoneTransformation = function (node) {
  106506. var mat = null;
  106507. if (node.translation || node.rotation || node.scale) {
  106508. var scale = BABYLON.Vector3.FromArray(node.scale || [1, 1, 1]);
  106509. var rotation = BABYLON.Quaternion.FromArray(node.rotation || [0, 0, 0, 1]);
  106510. var position = BABYLON.Vector3.FromArray(node.translation || [0, 0, 0]);
  106511. mat = BABYLON.Matrix.Compose(scale, rotation, position);
  106512. }
  106513. else {
  106514. mat = BABYLON.Matrix.FromArray(node.matrix);
  106515. }
  106516. return mat;
  106517. };
  106518. /**
  106519. * Returns the parent bone
  106520. */
  106521. var getParentBone = function (gltfRuntime, skins, jointName, newSkeleton) {
  106522. // Try to find
  106523. for (var i = 0; i < newSkeleton.bones.length; i++) {
  106524. if (newSkeleton.bones[i].name === jointName) {
  106525. return newSkeleton.bones[i];
  106526. }
  106527. }
  106528. // Not found, search in gltf nodes
  106529. var nodes = gltfRuntime.nodes;
  106530. for (var nde in nodes) {
  106531. var node = nodes[nde];
  106532. if (!node.jointName) {
  106533. continue;
  106534. }
  106535. var children = node.children;
  106536. for (var i = 0; i < children.length; i++) {
  106537. var child = gltfRuntime.nodes[children[i]];
  106538. if (!child.jointName) {
  106539. continue;
  106540. }
  106541. if (child.jointName === jointName) {
  106542. var mat = configureBoneTransformation(node);
  106543. var bone = new BABYLON.Bone(node.name || "", newSkeleton, getParentBone(gltfRuntime, skins, node.jointName, newSkeleton), mat);
  106544. bone.id = nde;
  106545. return bone;
  106546. }
  106547. }
  106548. }
  106549. return null;
  106550. };
  106551. /**
  106552. * Returns the appropriate root node
  106553. */
  106554. var getNodeToRoot = function (nodesToRoot, id) {
  106555. for (var i = 0; i < nodesToRoot.length; i++) {
  106556. var nodeToRoot = nodesToRoot[i];
  106557. for (var j = 0; j < nodeToRoot.node.children.length; j++) {
  106558. var child = nodeToRoot.node.children[j];
  106559. if (child === id) {
  106560. return nodeToRoot.bone;
  106561. }
  106562. }
  106563. }
  106564. return null;
  106565. };
  106566. /**
  106567. * Returns the node with the joint name
  106568. */
  106569. var getJointNode = function (gltfRuntime, jointName) {
  106570. var nodes = gltfRuntime.nodes;
  106571. var node = nodes[jointName];
  106572. if (node) {
  106573. return {
  106574. node: node,
  106575. id: jointName
  106576. };
  106577. }
  106578. for (var nde in nodes) {
  106579. node = nodes[nde];
  106580. if (node.jointName === jointName) {
  106581. return {
  106582. node: node,
  106583. id: nde
  106584. };
  106585. }
  106586. }
  106587. return null;
  106588. };
  106589. /**
  106590. * Checks if a nodes is in joints
  106591. */
  106592. var nodeIsInJoints = function (skins, id) {
  106593. for (var i = 0; i < skins.jointNames.length; i++) {
  106594. if (skins.jointNames[i] === id) {
  106595. return true;
  106596. }
  106597. }
  106598. return false;
  106599. };
  106600. /**
  106601. * Fills the nodes to root for bones and builds hierarchy
  106602. */
  106603. var getNodesToRoot = function (gltfRuntime, newSkeleton, skins, nodesToRoot) {
  106604. // Creates nodes for root
  106605. for (var nde in gltfRuntime.nodes) {
  106606. var node = gltfRuntime.nodes[nde];
  106607. var id = nde;
  106608. if (!node.jointName || nodeIsInJoints(skins, node.jointName)) {
  106609. continue;
  106610. }
  106611. // Create node to root bone
  106612. var mat = configureBoneTransformation(node);
  106613. var bone = new BABYLON.Bone(node.name || "", newSkeleton, null, mat);
  106614. bone.id = id;
  106615. nodesToRoot.push({ bone: bone, node: node, id: id });
  106616. }
  106617. // Parenting
  106618. for (var i = 0; i < nodesToRoot.length; i++) {
  106619. var nodeToRoot = nodesToRoot[i];
  106620. var children = nodeToRoot.node.children;
  106621. for (var j = 0; j < children.length; j++) {
  106622. var child = null;
  106623. for (var k = 0; k < nodesToRoot.length; k++) {
  106624. if (nodesToRoot[k].id === children[j]) {
  106625. child = nodesToRoot[k];
  106626. break;
  106627. }
  106628. }
  106629. if (child) {
  106630. child.bone._parent = nodeToRoot.bone;
  106631. nodeToRoot.bone.children.push(child.bone);
  106632. }
  106633. }
  106634. }
  106635. };
  106636. /**
  106637. * Imports a skeleton
  106638. */
  106639. var importSkeleton = function (gltfRuntime, skins, mesh, newSkeleton, id) {
  106640. if (!newSkeleton) {
  106641. newSkeleton = new BABYLON.Skeleton(skins.name || "", "", gltfRuntime.scene);
  106642. }
  106643. if (!skins.babylonSkeleton) {
  106644. return newSkeleton;
  106645. }
  106646. // Find the root bones
  106647. var nodesToRoot = [];
  106648. var nodesToRootToAdd = [];
  106649. getNodesToRoot(gltfRuntime, newSkeleton, skins, nodesToRoot);
  106650. newSkeleton.bones = [];
  106651. // Joints
  106652. for (var i = 0; i < skins.jointNames.length; i++) {
  106653. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  106654. if (!jointNode) {
  106655. continue;
  106656. }
  106657. var node = jointNode.node;
  106658. if (!node) {
  106659. BABYLON.Tools.Warn("Joint named " + skins.jointNames[i] + " does not exist");
  106660. continue;
  106661. }
  106662. var id = jointNode.id;
  106663. // Optimize, if the bone already exists...
  106664. var existingBone = gltfRuntime.scene.getBoneByID(id);
  106665. if (existingBone) {
  106666. newSkeleton.bones.push(existingBone);
  106667. continue;
  106668. }
  106669. // Search for parent bone
  106670. var foundBone = false;
  106671. var parentBone = null;
  106672. for (var j = 0; j < i; j++) {
  106673. var jointNode_1 = getJointNode(gltfRuntime, skins.jointNames[j]);
  106674. if (!jointNode_1) {
  106675. continue;
  106676. }
  106677. var joint = jointNode_1.node;
  106678. if (!joint) {
  106679. BABYLON.Tools.Warn("Joint named " + skins.jointNames[j] + " does not exist when looking for parent");
  106680. continue;
  106681. }
  106682. var children = joint.children;
  106683. if (!children) {
  106684. continue;
  106685. }
  106686. foundBone = false;
  106687. for (var k = 0; k < children.length; k++) {
  106688. if (children[k] === id) {
  106689. parentBone = getParentBone(gltfRuntime, skins, skins.jointNames[j], newSkeleton);
  106690. foundBone = true;
  106691. break;
  106692. }
  106693. }
  106694. if (foundBone) {
  106695. break;
  106696. }
  106697. }
  106698. // Create bone
  106699. var mat = configureBoneTransformation(node);
  106700. if (!parentBone && nodesToRoot.length > 0) {
  106701. parentBone = getNodeToRoot(nodesToRoot, id);
  106702. if (parentBone) {
  106703. if (nodesToRootToAdd.indexOf(parentBone) === -1) {
  106704. nodesToRootToAdd.push(parentBone);
  106705. }
  106706. }
  106707. }
  106708. var bone = new BABYLON.Bone(node.jointName || "", newSkeleton, parentBone, mat);
  106709. bone.id = id;
  106710. }
  106711. // Polish
  106712. var bones = newSkeleton.bones;
  106713. newSkeleton.bones = [];
  106714. for (var i = 0; i < skins.jointNames.length; i++) {
  106715. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  106716. if (!jointNode) {
  106717. continue;
  106718. }
  106719. for (var j = 0; j < bones.length; j++) {
  106720. if (bones[j].id === jointNode.id) {
  106721. newSkeleton.bones.push(bones[j]);
  106722. break;
  106723. }
  106724. }
  106725. }
  106726. newSkeleton.prepare();
  106727. // Finish
  106728. for (var i = 0; i < nodesToRootToAdd.length; i++) {
  106729. newSkeleton.bones.push(nodesToRootToAdd[i]);
  106730. }
  106731. return newSkeleton;
  106732. };
  106733. /**
  106734. * Imports a mesh and its geometries
  106735. */
  106736. var importMesh = function (gltfRuntime, node, meshes, id, newMesh) {
  106737. if (!newMesh) {
  106738. newMesh = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  106739. newMesh.id = id;
  106740. }
  106741. if (!node.babylonNode) {
  106742. return newMesh;
  106743. }
  106744. var subMaterials = [];
  106745. var vertexData = null;
  106746. var verticesStarts = new Array();
  106747. var verticesCounts = new Array();
  106748. var indexStarts = new Array();
  106749. var indexCounts = new Array();
  106750. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  106751. var meshID = meshes[meshIndex];
  106752. var mesh = gltfRuntime.meshes[meshID];
  106753. if (!mesh) {
  106754. continue;
  106755. }
  106756. // Positions, normals and UVs
  106757. for (var i = 0; i < mesh.primitives.length; i++) {
  106758. // Temporary vertex data
  106759. var tempVertexData = new BABYLON.VertexData();
  106760. var primitive = mesh.primitives[i];
  106761. if (primitive.mode !== 4) {
  106762. // continue;
  106763. }
  106764. var attributes = primitive.attributes;
  106765. var accessor = null;
  106766. var buffer = null;
  106767. // Set positions, normal and uvs
  106768. for (var semantic in attributes) {
  106769. // Link accessor and buffer view
  106770. accessor = gltfRuntime.accessors[attributes[semantic]];
  106771. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  106772. if (semantic === "NORMAL") {
  106773. tempVertexData.normals = new Float32Array(buffer.length);
  106774. tempVertexData.normals.set(buffer);
  106775. }
  106776. else if (semantic === "POSITION") {
  106777. if (BABYLON.GLTFFileLoader.HomogeneousCoordinates) {
  106778. tempVertexData.positions = new Float32Array(buffer.length - buffer.length / 4);
  106779. for (var j = 0; j < buffer.length; j += 4) {
  106780. tempVertexData.positions[j] = buffer[j];
  106781. tempVertexData.positions[j + 1] = buffer[j + 1];
  106782. tempVertexData.positions[j + 2] = buffer[j + 2];
  106783. }
  106784. }
  106785. else {
  106786. tempVertexData.positions = new Float32Array(buffer.length);
  106787. tempVertexData.positions.set(buffer);
  106788. }
  106789. verticesCounts.push(tempVertexData.positions.length);
  106790. }
  106791. else if (semantic.indexOf("TEXCOORD_") !== -1) {
  106792. var channel = Number(semantic.split("_")[1]);
  106793. var uvKind = BABYLON.VertexBuffer.UVKind + (channel === 0 ? "" : (channel + 1));
  106794. var uvs = new Float32Array(buffer.length);
  106795. uvs.set(buffer);
  106796. normalizeUVs(uvs);
  106797. tempVertexData.set(uvs, uvKind);
  106798. }
  106799. else if (semantic === "JOINT") {
  106800. tempVertexData.matricesIndices = new Float32Array(buffer.length);
  106801. tempVertexData.matricesIndices.set(buffer);
  106802. }
  106803. else if (semantic === "WEIGHT") {
  106804. tempVertexData.matricesWeights = new Float32Array(buffer.length);
  106805. tempVertexData.matricesWeights.set(buffer);
  106806. }
  106807. else if (semantic === "COLOR") {
  106808. tempVertexData.colors = new Float32Array(buffer.length);
  106809. tempVertexData.colors.set(buffer);
  106810. }
  106811. }
  106812. // Indices
  106813. accessor = gltfRuntime.accessors[primitive.indices];
  106814. if (accessor) {
  106815. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  106816. tempVertexData.indices = new Int32Array(buffer.length);
  106817. tempVertexData.indices.set(buffer);
  106818. indexCounts.push(tempVertexData.indices.length);
  106819. }
  106820. else {
  106821. // Set indices on the fly
  106822. var indices = [];
  106823. for (var j = 0; j < tempVertexData.positions.length / 3; j++) {
  106824. indices.push(j);
  106825. }
  106826. tempVertexData.indices = new Int32Array(indices);
  106827. indexCounts.push(tempVertexData.indices.length);
  106828. }
  106829. if (!vertexData) {
  106830. vertexData = tempVertexData;
  106831. }
  106832. else {
  106833. vertexData.merge(tempVertexData);
  106834. }
  106835. // Sub material
  106836. var material_1 = gltfRuntime.scene.getMaterialByID(primitive.material);
  106837. subMaterials.push(material_1 === null ? GLTF1.GLTFUtils.GetDefaultMaterial(gltfRuntime.scene) : material_1);
  106838. // Update vertices start and index start
  106839. verticesStarts.push(verticesStarts.length === 0 ? 0 : verticesStarts[verticesStarts.length - 1] + verticesCounts[verticesCounts.length - 2]);
  106840. indexStarts.push(indexStarts.length === 0 ? 0 : indexStarts[indexStarts.length - 1] + indexCounts[indexCounts.length - 2]);
  106841. }
  106842. }
  106843. var material;
  106844. if (subMaterials.length > 1) {
  106845. material = new BABYLON.MultiMaterial("multimat" + id, gltfRuntime.scene);
  106846. material.subMaterials = subMaterials;
  106847. }
  106848. else {
  106849. material = new BABYLON.StandardMaterial("multimat" + id, gltfRuntime.scene);
  106850. }
  106851. if (subMaterials.length === 1) {
  106852. material = subMaterials[0];
  106853. }
  106854. if (!newMesh.material) {
  106855. newMesh.material = material;
  106856. }
  106857. // Apply geometry
  106858. new BABYLON.Geometry(id, gltfRuntime.scene, vertexData, false, newMesh);
  106859. newMesh.computeWorldMatrix(true);
  106860. // Apply submeshes
  106861. newMesh.subMeshes = [];
  106862. var index = 0;
  106863. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  106864. var meshID = meshes[meshIndex];
  106865. var mesh = gltfRuntime.meshes[meshID];
  106866. if (!mesh) {
  106867. continue;
  106868. }
  106869. for (var i = 0; i < mesh.primitives.length; i++) {
  106870. if (mesh.primitives[i].mode !== 4) {
  106871. //continue;
  106872. }
  106873. BABYLON.SubMesh.AddToMesh(index, verticesStarts[index], verticesCounts[index], indexStarts[index], indexCounts[index], newMesh, newMesh, true);
  106874. index++;
  106875. }
  106876. }
  106877. // Finish
  106878. return newMesh;
  106879. };
  106880. /**
  106881. * Configure node transformation from position, rotation and scaling
  106882. */
  106883. var configureNode = function (newNode, position, rotation, scaling) {
  106884. if (newNode.position) {
  106885. newNode.position = position;
  106886. }
  106887. if (newNode.rotationQuaternion || newNode.rotation) {
  106888. newNode.rotationQuaternion = rotation;
  106889. }
  106890. if (newNode.scaling) {
  106891. newNode.scaling = scaling;
  106892. }
  106893. };
  106894. /**
  106895. * Configures node from transformation matrix
  106896. */
  106897. var configureNodeFromMatrix = function (newNode, node, parent) {
  106898. if (node.matrix) {
  106899. var position = new BABYLON.Vector3(0, 0, 0);
  106900. var rotation = new BABYLON.Quaternion();
  106901. var scaling = new BABYLON.Vector3(0, 0, 0);
  106902. var mat = BABYLON.Matrix.FromArray(node.matrix);
  106903. mat.decompose(scaling, rotation, position);
  106904. configureNode(newNode, position, rotation, scaling);
  106905. }
  106906. else if (node.translation && node.rotation && node.scale) {
  106907. configureNode(newNode, BABYLON.Vector3.FromArray(node.translation), BABYLON.Quaternion.FromArray(node.rotation), BABYLON.Vector3.FromArray(node.scale));
  106908. }
  106909. newNode.computeWorldMatrix(true);
  106910. };
  106911. /**
  106912. * Imports a node
  106913. */
  106914. var importNode = function (gltfRuntime, node, id, parent) {
  106915. var lastNode = null;
  106916. if (gltfRuntime.importOnlyMeshes && (node.skin || node.meshes)) {
  106917. if (gltfRuntime.importMeshesNames && gltfRuntime.importMeshesNames.length > 0 && gltfRuntime.importMeshesNames.indexOf(node.name || "") === -1) {
  106918. return null;
  106919. }
  106920. }
  106921. // Meshes
  106922. if (node.skin) {
  106923. if (node.meshes) {
  106924. var skin = gltfRuntime.skins[node.skin];
  106925. var newMesh = importMesh(gltfRuntime, node, node.meshes, id, node.babylonNode);
  106926. newMesh.skeleton = gltfRuntime.scene.getLastSkeletonByID(node.skin);
  106927. if (newMesh.skeleton === null) {
  106928. newMesh.skeleton = importSkeleton(gltfRuntime, skin, newMesh, skin.babylonSkeleton, node.skin);
  106929. if (!skin.babylonSkeleton) {
  106930. skin.babylonSkeleton = newMesh.skeleton;
  106931. }
  106932. }
  106933. lastNode = newMesh;
  106934. }
  106935. }
  106936. else if (node.meshes) {
  106937. /**
  106938. * Improve meshes property
  106939. */
  106940. var newMesh = importMesh(gltfRuntime, node, node.mesh ? [node.mesh] : node.meshes, id, node.babylonNode);
  106941. lastNode = newMesh;
  106942. }
  106943. else if (node.light && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  106944. var light = gltfRuntime.lights[node.light];
  106945. if (light) {
  106946. if (light.type === "ambient") {
  106947. var ambienLight = light[light.type];
  106948. var hemiLight = new BABYLON.HemisphericLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  106949. hemiLight.name = node.name || "";
  106950. if (ambienLight.color) {
  106951. hemiLight.diffuse = BABYLON.Color3.FromArray(ambienLight.color);
  106952. }
  106953. lastNode = hemiLight;
  106954. }
  106955. else if (light.type === "directional") {
  106956. var directionalLight = light[light.type];
  106957. var dirLight = new BABYLON.DirectionalLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  106958. dirLight.name = node.name || "";
  106959. if (directionalLight.color) {
  106960. dirLight.diffuse = BABYLON.Color3.FromArray(directionalLight.color);
  106961. }
  106962. lastNode = dirLight;
  106963. }
  106964. else if (light.type === "point") {
  106965. var pointLight = light[light.type];
  106966. var ptLight = new BABYLON.PointLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  106967. ptLight.name = node.name || "";
  106968. if (pointLight.color) {
  106969. ptLight.diffuse = BABYLON.Color3.FromArray(pointLight.color);
  106970. }
  106971. lastNode = ptLight;
  106972. }
  106973. else if (light.type === "spot") {
  106974. var spotLight = light[light.type];
  106975. var spLight = new BABYLON.SpotLight(node.light, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, gltfRuntime.scene);
  106976. spLight.name = node.name || "";
  106977. if (spotLight.color) {
  106978. spLight.diffuse = BABYLON.Color3.FromArray(spotLight.color);
  106979. }
  106980. if (spotLight.fallOfAngle) {
  106981. spLight.angle = spotLight.fallOfAngle;
  106982. }
  106983. if (spotLight.fallOffExponent) {
  106984. spLight.exponent = spotLight.fallOffExponent;
  106985. }
  106986. lastNode = spLight;
  106987. }
  106988. }
  106989. }
  106990. else if (node.camera && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  106991. var camera = gltfRuntime.cameras[node.camera];
  106992. if (camera) {
  106993. if (camera.type === "orthographic") {
  106994. var orthoCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  106995. orthoCamera.name = node.name || "";
  106996. orthoCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
  106997. orthoCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  106998. lastNode = orthoCamera;
  106999. }
  107000. else if (camera.type === "perspective") {
  107001. var perspectiveCamera = camera[camera.type];
  107002. var persCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  107003. persCamera.name = node.name || "";
  107004. persCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  107005. if (!perspectiveCamera.aspectRatio) {
  107006. perspectiveCamera.aspectRatio = gltfRuntime.scene.getEngine().getRenderWidth() / gltfRuntime.scene.getEngine().getRenderHeight();
  107007. }
  107008. if (perspectiveCamera.znear && perspectiveCamera.zfar) {
  107009. persCamera.maxZ = perspectiveCamera.zfar;
  107010. persCamera.minZ = perspectiveCamera.znear;
  107011. }
  107012. lastNode = persCamera;
  107013. }
  107014. }
  107015. }
  107016. // Empty node
  107017. if (!node.jointName) {
  107018. if (node.babylonNode) {
  107019. return node.babylonNode;
  107020. }
  107021. else if (lastNode === null) {
  107022. var dummy = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  107023. node.babylonNode = dummy;
  107024. lastNode = dummy;
  107025. }
  107026. }
  107027. if (lastNode !== null) {
  107028. if (node.matrix && lastNode instanceof BABYLON.Mesh) {
  107029. configureNodeFromMatrix(lastNode, node, parent);
  107030. }
  107031. else {
  107032. var translation = node.translation || [0, 0, 0];
  107033. var rotation = node.rotation || [0, 0, 0, 1];
  107034. var scale = node.scale || [1, 1, 1];
  107035. configureNode(lastNode, BABYLON.Vector3.FromArray(translation), BABYLON.Quaternion.FromArray(rotation), BABYLON.Vector3.FromArray(scale));
  107036. }
  107037. lastNode.updateCache(true);
  107038. node.babylonNode = lastNode;
  107039. }
  107040. return lastNode;
  107041. };
  107042. /**
  107043. * Traverses nodes and creates them
  107044. */
  107045. var traverseNodes = function (gltfRuntime, id, parent, meshIncluded) {
  107046. if (meshIncluded === void 0) { meshIncluded = false; }
  107047. var node = gltfRuntime.nodes[id];
  107048. var newNode = null;
  107049. if (gltfRuntime.importOnlyMeshes && !meshIncluded && gltfRuntime.importMeshesNames) {
  107050. if (gltfRuntime.importMeshesNames.indexOf(node.name || "") !== -1 || gltfRuntime.importMeshesNames.length === 0) {
  107051. meshIncluded = true;
  107052. }
  107053. else {
  107054. meshIncluded = false;
  107055. }
  107056. }
  107057. else {
  107058. meshIncluded = true;
  107059. }
  107060. if (!node.jointName && meshIncluded) {
  107061. newNode = importNode(gltfRuntime, node, id, parent);
  107062. if (newNode !== null) {
  107063. newNode.id = id;
  107064. newNode.parent = parent;
  107065. }
  107066. }
  107067. if (node.children) {
  107068. for (var i = 0; i < node.children.length; i++) {
  107069. traverseNodes(gltfRuntime, node.children[i], newNode, meshIncluded);
  107070. }
  107071. }
  107072. };
  107073. /**
  107074. * do stuff after buffers, shaders are loaded (e.g. hook up materials, load animations, etc.)
  107075. */
  107076. var postLoad = function (gltfRuntime) {
  107077. // Nodes
  107078. var currentScene = gltfRuntime.currentScene;
  107079. if (currentScene) {
  107080. for (var i = 0; i < currentScene.nodes.length; i++) {
  107081. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  107082. }
  107083. }
  107084. else {
  107085. for (var thing in gltfRuntime.scenes) {
  107086. currentScene = gltfRuntime.scenes[thing];
  107087. for (var i = 0; i < currentScene.nodes.length; i++) {
  107088. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  107089. }
  107090. }
  107091. }
  107092. // Set animations
  107093. loadAnimations(gltfRuntime);
  107094. for (var i = 0; i < gltfRuntime.scene.skeletons.length; i++) {
  107095. var skeleton = gltfRuntime.scene.skeletons[i];
  107096. gltfRuntime.scene.beginAnimation(skeleton, 0, Number.MAX_VALUE, true, 1.0);
  107097. }
  107098. };
  107099. /**
  107100. * onBind shaderrs callback to set uniforms and matrices
  107101. */
  107102. var onBindShaderMaterial = function (mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess) {
  107103. var materialValues = material.values || technique.parameters;
  107104. for (var unif in unTreatedUniforms) {
  107105. var uniform = unTreatedUniforms[unif];
  107106. var type = uniform.type;
  107107. if (type === GLTF1.EParameterType.FLOAT_MAT2 || type === GLTF1.EParameterType.FLOAT_MAT3 || type === GLTF1.EParameterType.FLOAT_MAT4) {
  107108. if (uniform.semantic && !uniform.source && !uniform.node) {
  107109. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, mesh, uniform, unif, shaderMaterial.getEffect());
  107110. }
  107111. else if (uniform.semantic && (uniform.source || uniform.node)) {
  107112. var source = gltfRuntime.scene.getNodeByName(uniform.source || uniform.node || "");
  107113. if (source === null) {
  107114. source = gltfRuntime.scene.getNodeByID(uniform.source || uniform.node || "");
  107115. }
  107116. if (source === null) {
  107117. continue;
  107118. }
  107119. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, source, uniform, unif, shaderMaterial.getEffect());
  107120. }
  107121. }
  107122. else {
  107123. var value = materialValues[technique.uniforms[unif]];
  107124. if (!value) {
  107125. continue;
  107126. }
  107127. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  107128. var texture = gltfRuntime.textures[material.values ? value : uniform.value].babylonTexture;
  107129. if (texture === null || texture === undefined) {
  107130. continue;
  107131. }
  107132. shaderMaterial.getEffect().setTexture(unif, texture);
  107133. }
  107134. else {
  107135. GLTF1.GLTFUtils.SetUniform((shaderMaterial.getEffect()), unif, value, type);
  107136. }
  107137. }
  107138. }
  107139. onSuccess(shaderMaterial);
  107140. };
  107141. /**
  107142. * Prepare uniforms to send the only one time
  107143. * Loads the appropriate textures
  107144. */
  107145. var prepareShaderMaterialUniforms = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms) {
  107146. var materialValues = material.values || technique.parameters;
  107147. var techniqueUniforms = technique.uniforms;
  107148. /**
  107149. * Prepare values here (not matrices)
  107150. */
  107151. for (var unif in unTreatedUniforms) {
  107152. var uniform = unTreatedUniforms[unif];
  107153. var type = uniform.type;
  107154. var value = materialValues[techniqueUniforms[unif]];
  107155. if (value === undefined) {
  107156. // In case the value is the same for all materials
  107157. value = uniform.value;
  107158. }
  107159. if (!value) {
  107160. continue;
  107161. }
  107162. var onLoadTexture = function (uniformName) {
  107163. return function (texture) {
  107164. if (uniform.value && uniformName) {
  107165. // Static uniform
  107166. shaderMaterial.setTexture(uniformName, texture);
  107167. delete unTreatedUniforms[uniformName];
  107168. }
  107169. };
  107170. };
  107171. // Texture (sampler2D)
  107172. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  107173. GLTF1.GLTFLoaderExtension.LoadTextureAsync(gltfRuntime, material.values ? value : uniform.value, onLoadTexture(unif), function () { return onLoadTexture(null); });
  107174. }
  107175. else {
  107176. if (uniform.value && GLTF1.GLTFUtils.SetUniform(shaderMaterial, unif, material.values ? value : uniform.value, type)) {
  107177. // Static uniform
  107178. delete unTreatedUniforms[unif];
  107179. }
  107180. }
  107181. }
  107182. };
  107183. /**
  107184. * Shader compilation failed
  107185. */
  107186. var onShaderCompileError = function (program, shaderMaterial, onError) {
  107187. return function (effect, error) {
  107188. shaderMaterial.dispose(true);
  107189. onError("Cannot compile program named " + program.name + ". Error: " + error + ". Default material will be applied");
  107190. };
  107191. };
  107192. /**
  107193. * Shader compilation success
  107194. */
  107195. var onShaderCompileSuccess = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess) {
  107196. return function (_) {
  107197. prepareShaderMaterialUniforms(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms);
  107198. shaderMaterial.onBind = function (mesh) {
  107199. onBindShaderMaterial(mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess);
  107200. };
  107201. };
  107202. };
  107203. /**
  107204. * Returns the appropriate uniform if already handled by babylon
  107205. */
  107206. var parseShaderUniforms = function (tokenizer, technique, unTreatedUniforms) {
  107207. for (var unif in technique.uniforms) {
  107208. var uniform = technique.uniforms[unif];
  107209. var uniformParameter = technique.parameters[uniform];
  107210. if (tokenizer.currentIdentifier === unif) {
  107211. if (uniformParameter.semantic && !uniformParameter.source && !uniformParameter.node) {
  107212. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  107213. if (transformIndex !== -1) {
  107214. delete unTreatedUniforms[unif];
  107215. return babylonTransforms[transformIndex];
  107216. }
  107217. }
  107218. }
  107219. }
  107220. return tokenizer.currentIdentifier;
  107221. };
  107222. /**
  107223. * All shaders loaded. Create materials one by one
  107224. */
  107225. var importMaterials = function (gltfRuntime) {
  107226. // Create materials
  107227. for (var mat in gltfRuntime.materials) {
  107228. GLTF1.GLTFLoaderExtension.LoadMaterialAsync(gltfRuntime, mat, function (material) { }, function () { });
  107229. }
  107230. };
  107231. /**
  107232. * Implementation of the base glTF spec
  107233. */
  107234. var GLTFLoaderBase = /** @class */ (function () {
  107235. function GLTFLoaderBase() {
  107236. }
  107237. GLTFLoaderBase.CreateRuntime = function (parsedData, scene, rootUrl) {
  107238. var gltfRuntime = {
  107239. extensions: {},
  107240. accessors: {},
  107241. buffers: {},
  107242. bufferViews: {},
  107243. meshes: {},
  107244. lights: {},
  107245. cameras: {},
  107246. nodes: {},
  107247. images: {},
  107248. textures: {},
  107249. shaders: {},
  107250. programs: {},
  107251. samplers: {},
  107252. techniques: {},
  107253. materials: {},
  107254. animations: {},
  107255. skins: {},
  107256. extensionsUsed: [],
  107257. scenes: {},
  107258. buffersCount: 0,
  107259. shaderscount: 0,
  107260. scene: scene,
  107261. rootUrl: rootUrl,
  107262. loadedBufferCount: 0,
  107263. loadedBufferViews: {},
  107264. loadedShaderCount: 0,
  107265. importOnlyMeshes: false,
  107266. dummyNodes: []
  107267. };
  107268. // Parse
  107269. if (parsedData.extensions) {
  107270. parseObject(parsedData.extensions, "extensions", gltfRuntime);
  107271. }
  107272. if (parsedData.extensionsUsed) {
  107273. parseObject(parsedData.extensionsUsed, "extensionsUsed", gltfRuntime);
  107274. }
  107275. if (parsedData.buffers) {
  107276. parseBuffers(parsedData.buffers, gltfRuntime);
  107277. }
  107278. if (parsedData.bufferViews) {
  107279. parseObject(parsedData.bufferViews, "bufferViews", gltfRuntime);
  107280. }
  107281. if (parsedData.accessors) {
  107282. parseObject(parsedData.accessors, "accessors", gltfRuntime);
  107283. }
  107284. if (parsedData.meshes) {
  107285. parseObject(parsedData.meshes, "meshes", gltfRuntime);
  107286. }
  107287. if (parsedData.lights) {
  107288. parseObject(parsedData.lights, "lights", gltfRuntime);
  107289. }
  107290. if (parsedData.cameras) {
  107291. parseObject(parsedData.cameras, "cameras", gltfRuntime);
  107292. }
  107293. if (parsedData.nodes) {
  107294. parseObject(parsedData.nodes, "nodes", gltfRuntime);
  107295. }
  107296. if (parsedData.images) {
  107297. parseObject(parsedData.images, "images", gltfRuntime);
  107298. }
  107299. if (parsedData.textures) {
  107300. parseObject(parsedData.textures, "textures", gltfRuntime);
  107301. }
  107302. if (parsedData.shaders) {
  107303. parseShaders(parsedData.shaders, gltfRuntime);
  107304. }
  107305. if (parsedData.programs) {
  107306. parseObject(parsedData.programs, "programs", gltfRuntime);
  107307. }
  107308. if (parsedData.samplers) {
  107309. parseObject(parsedData.samplers, "samplers", gltfRuntime);
  107310. }
  107311. if (parsedData.techniques) {
  107312. parseObject(parsedData.techniques, "techniques", gltfRuntime);
  107313. }
  107314. if (parsedData.materials) {
  107315. parseObject(parsedData.materials, "materials", gltfRuntime);
  107316. }
  107317. if (parsedData.animations) {
  107318. parseObject(parsedData.animations, "animations", gltfRuntime);
  107319. }
  107320. if (parsedData.skins) {
  107321. parseObject(parsedData.skins, "skins", gltfRuntime);
  107322. }
  107323. if (parsedData.scenes) {
  107324. gltfRuntime.scenes = parsedData.scenes;
  107325. }
  107326. if (parsedData.scene && parsedData.scenes) {
  107327. gltfRuntime.currentScene = parsedData.scenes[parsedData.scene];
  107328. }
  107329. return gltfRuntime;
  107330. };
  107331. GLTFLoaderBase.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  107332. var buffer = gltfRuntime.buffers[id];
  107333. if (BABYLON.Tools.IsBase64(buffer.uri)) {
  107334. setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.Tools.DecodeBase64(buffer.uri))); });
  107335. }
  107336. else {
  107337. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + buffer.uri, function (data) { return onSuccess(new Uint8Array(data)); }, onProgress, undefined, true, function (request) {
  107338. if (request) {
  107339. onError(request.status + " " + request.statusText);
  107340. }
  107341. });
  107342. }
  107343. };
  107344. GLTFLoaderBase.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  107345. var texture = gltfRuntime.textures[id];
  107346. if (!texture || !texture.source) {
  107347. onError("");
  107348. return;
  107349. }
  107350. if (texture.babylonTexture) {
  107351. onSuccess(null);
  107352. return;
  107353. }
  107354. var source = gltfRuntime.images[texture.source];
  107355. if (BABYLON.Tools.IsBase64(source.uri)) {
  107356. setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.Tools.DecodeBase64(source.uri))); });
  107357. }
  107358. else {
  107359. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + source.uri, function (data) { return onSuccess(new Uint8Array(data)); }, undefined, undefined, true, function (request) {
  107360. if (request) {
  107361. onError(request.status + " " + request.statusText);
  107362. }
  107363. });
  107364. }
  107365. };
  107366. GLTFLoaderBase.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  107367. var texture = gltfRuntime.textures[id];
  107368. if (texture.babylonTexture) {
  107369. onSuccess(texture.babylonTexture);
  107370. return;
  107371. }
  107372. var sampler = gltfRuntime.samplers[texture.sampler];
  107373. var createMipMaps = (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST) ||
  107374. (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_LINEAR) ||
  107375. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST) ||
  107376. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR);
  107377. var samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  107378. var blob = new Blob([buffer]);
  107379. var blobURL = URL.createObjectURL(blob);
  107380. var revokeBlobURL = function () { return URL.revokeObjectURL(blobURL); };
  107381. var newTexture = new BABYLON.Texture(blobURL, gltfRuntime.scene, !createMipMaps, true, samplingMode, revokeBlobURL, revokeBlobURL);
  107382. if (sampler.wrapS !== undefined) {
  107383. newTexture.wrapU = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapS);
  107384. }
  107385. if (sampler.wrapT !== undefined) {
  107386. newTexture.wrapV = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapT);
  107387. }
  107388. newTexture.name = id;
  107389. texture.babylonTexture = newTexture;
  107390. onSuccess(newTexture);
  107391. };
  107392. GLTFLoaderBase.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  107393. var shader = gltfRuntime.shaders[id];
  107394. if (BABYLON.Tools.IsBase64(shader.uri)) {
  107395. var shaderString = atob(shader.uri.split(",")[1]);
  107396. onSuccess(shaderString);
  107397. }
  107398. else {
  107399. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + shader.uri, onSuccess, undefined, undefined, false, function (request) {
  107400. if (request) {
  107401. onError(request.status + " " + request.statusText);
  107402. }
  107403. });
  107404. }
  107405. };
  107406. GLTFLoaderBase.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  107407. var material = gltfRuntime.materials[id];
  107408. if (!material.technique) {
  107409. if (onError) {
  107410. onError("No technique found.");
  107411. }
  107412. return;
  107413. }
  107414. var technique = gltfRuntime.techniques[material.technique];
  107415. if (!technique) {
  107416. var defaultMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  107417. defaultMaterial.diffuseColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  107418. defaultMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  107419. onSuccess(defaultMaterial);
  107420. return;
  107421. }
  107422. var program = gltfRuntime.programs[technique.program];
  107423. var states = technique.states;
  107424. var vertexShader = BABYLON.Effect.ShadersStore[program.vertexShader + "VertexShader"];
  107425. var pixelShader = BABYLON.Effect.ShadersStore[program.fragmentShader + "PixelShader"];
  107426. var newVertexShader = "";
  107427. var newPixelShader = "";
  107428. var vertexTokenizer = new Tokenizer(vertexShader);
  107429. var pixelTokenizer = new Tokenizer(pixelShader);
  107430. var unTreatedUniforms = {};
  107431. var uniforms = [];
  107432. var attributes = [];
  107433. var samplers = [];
  107434. // Fill uniform, sampler2D and attributes
  107435. for (var unif in technique.uniforms) {
  107436. var uniform = technique.uniforms[unif];
  107437. var uniformParameter = technique.parameters[uniform];
  107438. unTreatedUniforms[unif] = uniformParameter;
  107439. if (uniformParameter.semantic && !uniformParameter.node && !uniformParameter.source) {
  107440. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  107441. if (transformIndex !== -1) {
  107442. uniforms.push(babylonTransforms[transformIndex]);
  107443. delete unTreatedUniforms[unif];
  107444. }
  107445. else {
  107446. uniforms.push(unif);
  107447. }
  107448. }
  107449. else if (uniformParameter.type === GLTF1.EParameterType.SAMPLER_2D) {
  107450. samplers.push(unif);
  107451. }
  107452. else {
  107453. uniforms.push(unif);
  107454. }
  107455. }
  107456. for (var attr in technique.attributes) {
  107457. var attribute = technique.attributes[attr];
  107458. var attributeParameter = technique.parameters[attribute];
  107459. if (attributeParameter.semantic) {
  107460. attributes.push(getAttribute(attributeParameter));
  107461. }
  107462. }
  107463. // Configure vertex shader
  107464. while (!vertexTokenizer.isEnd() && vertexTokenizer.getNextToken()) {
  107465. var tokenType = vertexTokenizer.currentToken;
  107466. if (tokenType !== ETokenType.IDENTIFIER) {
  107467. newVertexShader += vertexTokenizer.currentString;
  107468. continue;
  107469. }
  107470. var foundAttribute = false;
  107471. for (var attr in technique.attributes) {
  107472. var attribute = technique.attributes[attr];
  107473. var attributeParameter = technique.parameters[attribute];
  107474. if (vertexTokenizer.currentIdentifier === attr && attributeParameter.semantic) {
  107475. newVertexShader += getAttribute(attributeParameter);
  107476. foundAttribute = true;
  107477. break;
  107478. }
  107479. }
  107480. if (foundAttribute) {
  107481. continue;
  107482. }
  107483. newVertexShader += parseShaderUniforms(vertexTokenizer, technique, unTreatedUniforms);
  107484. }
  107485. // Configure pixel shader
  107486. while (!pixelTokenizer.isEnd() && pixelTokenizer.getNextToken()) {
  107487. var tokenType = pixelTokenizer.currentToken;
  107488. if (tokenType !== ETokenType.IDENTIFIER) {
  107489. newPixelShader += pixelTokenizer.currentString;
  107490. continue;
  107491. }
  107492. newPixelShader += parseShaderUniforms(pixelTokenizer, technique, unTreatedUniforms);
  107493. }
  107494. // Create shader material
  107495. var shaderPath = {
  107496. vertex: program.vertexShader + id,
  107497. fragment: program.fragmentShader + id
  107498. };
  107499. var options = {
  107500. attributes: attributes,
  107501. uniforms: uniforms,
  107502. samplers: samplers,
  107503. needAlphaBlending: states && states.enable && states.enable.indexOf(3042) !== -1
  107504. };
  107505. BABYLON.Effect.ShadersStore[program.vertexShader + id + "VertexShader"] = newVertexShader;
  107506. BABYLON.Effect.ShadersStore[program.fragmentShader + id + "PixelShader"] = newPixelShader;
  107507. var shaderMaterial = new BABYLON.ShaderMaterial(id, gltfRuntime.scene, shaderPath, options);
  107508. shaderMaterial.onError = onShaderCompileError(program, shaderMaterial, onError);
  107509. shaderMaterial.onCompiled = onShaderCompileSuccess(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess);
  107510. shaderMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  107511. if (states && states.functions) {
  107512. var functions = states.functions;
  107513. if (functions.cullFace && functions.cullFace[0] !== GLTF1.ECullingType.BACK) {
  107514. shaderMaterial.backFaceCulling = false;
  107515. }
  107516. var blendFunc = functions.blendFuncSeparate;
  107517. if (blendFunc) {
  107518. if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE_MINUS_SRC_ALPHA && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  107519. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  107520. }
  107521. else if (blendFunc[0] === GLTF1.EBlendingFunction.ONE && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  107522. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  107523. }
  107524. else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  107525. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ADD;
  107526. }
  107527. else if (blendFunc[0] === GLTF1.EBlendingFunction.ZERO && blendFunc[1] === GLTF1.EBlendingFunction.ONE_MINUS_SRC_COLOR && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  107528. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_SUBTRACT;
  107529. }
  107530. else if (blendFunc[0] === GLTF1.EBlendingFunction.DST_COLOR && blendFunc[1] === GLTF1.EBlendingFunction.ZERO && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  107531. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MULTIPLY;
  107532. }
  107533. else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE_MINUS_SRC_COLOR && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  107534. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MAXIMIZED;
  107535. }
  107536. }
  107537. }
  107538. };
  107539. return GLTFLoaderBase;
  107540. }());
  107541. GLTF1.GLTFLoaderBase = GLTFLoaderBase;
  107542. /**
  107543. * glTF V1 Loader
  107544. */
  107545. var GLTFLoader = /** @class */ (function () {
  107546. function GLTFLoader() {
  107547. // #region Stubs for IGLTFLoader interface
  107548. this.coordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode.AUTO;
  107549. this.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.FIRST;
  107550. this.compileMaterials = false;
  107551. this.useClipPlane = false;
  107552. this.compileShadowGenerators = false;
  107553. this.onDisposeObservable = new BABYLON.Observable();
  107554. this.onMeshLoadedObservable = new BABYLON.Observable();
  107555. this.onTextureLoadedObservable = new BABYLON.Observable();
  107556. this.onMaterialLoadedObservable = new BABYLON.Observable();
  107557. this.onAnimationGroupLoadedObservable = new BABYLON.Observable();
  107558. this.onCompleteObservable = new BABYLON.Observable();
  107559. this.onExtensionLoadedObservable = new BABYLON.Observable();
  107560. this.state = null;
  107561. }
  107562. GLTFLoader.RegisterExtension = function (extension) {
  107563. if (GLTFLoader.Extensions[extension.name]) {
  107564. BABYLON.Tools.Error("Tool with the same name \"" + extension.name + "\" already exists");
  107565. return;
  107566. }
  107567. GLTFLoader.Extensions[extension.name] = extension;
  107568. };
  107569. GLTFLoader.prototype.dispose = function () { };
  107570. // #endregion
  107571. GLTFLoader.prototype._importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  107572. var _this = this;
  107573. scene.useRightHandedSystem = true;
  107574. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  107575. gltfRuntime.importOnlyMeshes = true;
  107576. if (meshesNames === "") {
  107577. gltfRuntime.importMeshesNames = [];
  107578. }
  107579. else if (typeof meshesNames === "string") {
  107580. gltfRuntime.importMeshesNames = [meshesNames];
  107581. }
  107582. else if (meshesNames && !(meshesNames instanceof Array)) {
  107583. gltfRuntime.importMeshesNames = [meshesNames];
  107584. }
  107585. else {
  107586. gltfRuntime.importMeshesNames = [];
  107587. BABYLON.Tools.Warn("Argument meshesNames must be of type string or string[]");
  107588. }
  107589. // Create nodes
  107590. _this._createNodes(gltfRuntime);
  107591. var meshes = new Array();
  107592. var skeletons = new Array();
  107593. // Fill arrays of meshes and skeletons
  107594. for (var nde in gltfRuntime.nodes) {
  107595. var node = gltfRuntime.nodes[nde];
  107596. if (node.babylonNode instanceof BABYLON.AbstractMesh) {
  107597. meshes.push(node.babylonNode);
  107598. }
  107599. }
  107600. for (var skl in gltfRuntime.skins) {
  107601. var skin = gltfRuntime.skins[skl];
  107602. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  107603. skeletons.push(skin.babylonSkeleton);
  107604. }
  107605. }
  107606. // Load buffers, shaders, materials, etc.
  107607. _this._loadBuffersAsync(gltfRuntime, function () {
  107608. _this._loadShadersAsync(gltfRuntime, function () {
  107609. importMaterials(gltfRuntime);
  107610. postLoad(gltfRuntime);
  107611. if (!BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  107612. onSuccess(meshes, [], skeletons);
  107613. }
  107614. });
  107615. }, onProgress);
  107616. if (BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  107617. onSuccess(meshes, [], skeletons);
  107618. }
  107619. }, onError);
  107620. return true;
  107621. };
  107622. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  107623. var _this = this;
  107624. return new Promise(function (resolve, reject) {
  107625. _this._importMeshAsync(meshesNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  107626. resolve({
  107627. meshes: meshes,
  107628. particleSystems: particleSystems,
  107629. skeletons: skeletons
  107630. });
  107631. }, onProgress, function (message) {
  107632. reject(new Error(message));
  107633. });
  107634. });
  107635. };
  107636. GLTFLoader.prototype._loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  107637. var _this = this;
  107638. scene.useRightHandedSystem = true;
  107639. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  107640. // Load runtime extensios
  107641. GLTF1.GLTFLoaderExtension.LoadRuntimeExtensionsAsync(gltfRuntime, function () {
  107642. // Create nodes
  107643. _this._createNodes(gltfRuntime);
  107644. // Load buffers, shaders, materials, etc.
  107645. _this._loadBuffersAsync(gltfRuntime, function () {
  107646. _this._loadShadersAsync(gltfRuntime, function () {
  107647. importMaterials(gltfRuntime);
  107648. postLoad(gltfRuntime);
  107649. if (!BABYLON.GLTFFileLoader.IncrementalLoading) {
  107650. onSuccess();
  107651. }
  107652. });
  107653. });
  107654. if (BABYLON.GLTFFileLoader.IncrementalLoading) {
  107655. onSuccess();
  107656. }
  107657. }, onError);
  107658. }, onError);
  107659. };
  107660. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  107661. var _this = this;
  107662. return new Promise(function (resolve, reject) {
  107663. _this._loadAsync(scene, data, rootUrl, function () {
  107664. resolve();
  107665. }, onProgress, function (message) {
  107666. reject(new Error(message));
  107667. });
  107668. });
  107669. };
  107670. GLTFLoader.prototype._loadShadersAsync = function (gltfRuntime, onload) {
  107671. var hasShaders = false;
  107672. var processShader = function (sha, shader) {
  107673. GLTF1.GLTFLoaderExtension.LoadShaderStringAsync(gltfRuntime, sha, function (shaderString) {
  107674. gltfRuntime.loadedShaderCount++;
  107675. if (shaderString) {
  107676. BABYLON.Effect.ShadersStore[sha + (shader.type === GLTF1.EShaderType.VERTEX ? "VertexShader" : "PixelShader")] = shaderString;
  107677. }
  107678. if (gltfRuntime.loadedShaderCount === gltfRuntime.shaderscount) {
  107679. onload();
  107680. }
  107681. }, function () {
  107682. BABYLON.Tools.Error("Error when loading shader program named " + sha + " located at " + shader.uri);
  107683. });
  107684. };
  107685. for (var sha in gltfRuntime.shaders) {
  107686. hasShaders = true;
  107687. var shader = gltfRuntime.shaders[sha];
  107688. if (shader) {
  107689. processShader.bind(this, sha, shader)();
  107690. }
  107691. else {
  107692. BABYLON.Tools.Error("No shader named: " + sha);
  107693. }
  107694. }
  107695. if (!hasShaders) {
  107696. onload();
  107697. }
  107698. };
  107699. ;
  107700. GLTFLoader.prototype._loadBuffersAsync = function (gltfRuntime, onLoad, onProgress) {
  107701. var hasBuffers = false;
  107702. var processBuffer = function (buf, buffer) {
  107703. GLTF1.GLTFLoaderExtension.LoadBufferAsync(gltfRuntime, buf, function (bufferView) {
  107704. gltfRuntime.loadedBufferCount++;
  107705. if (bufferView) {
  107706. if (bufferView.byteLength != gltfRuntime.buffers[buf].byteLength) {
  107707. BABYLON.Tools.Error("Buffer named " + buf + " is length " + bufferView.byteLength + ". Expected: " + buffer.byteLength); // Improve error message
  107708. }
  107709. gltfRuntime.loadedBufferViews[buf] = bufferView;
  107710. }
  107711. if (gltfRuntime.loadedBufferCount === gltfRuntime.buffersCount) {
  107712. onLoad();
  107713. }
  107714. }, function () {
  107715. BABYLON.Tools.Error("Error when loading buffer named " + buf + " located at " + buffer.uri);
  107716. });
  107717. };
  107718. for (var buf in gltfRuntime.buffers) {
  107719. hasBuffers = true;
  107720. var buffer = gltfRuntime.buffers[buf];
  107721. if (buffer) {
  107722. processBuffer.bind(this, buf, buffer)();
  107723. }
  107724. else {
  107725. BABYLON.Tools.Error("No buffer named: " + buf);
  107726. }
  107727. }
  107728. if (!hasBuffers) {
  107729. onLoad();
  107730. }
  107731. };
  107732. GLTFLoader.prototype._createNodes = function (gltfRuntime) {
  107733. var currentScene = gltfRuntime.currentScene;
  107734. if (currentScene) {
  107735. // Only one scene even if multiple scenes are defined
  107736. for (var i = 0; i < currentScene.nodes.length; i++) {
  107737. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  107738. }
  107739. }
  107740. else {
  107741. // Load all scenes
  107742. for (var thing in gltfRuntime.scenes) {
  107743. currentScene = gltfRuntime.scenes[thing];
  107744. for (var i = 0; i < currentScene.nodes.length; i++) {
  107745. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  107746. }
  107747. }
  107748. }
  107749. };
  107750. GLTFLoader.Extensions = {};
  107751. return GLTFLoader;
  107752. }());
  107753. GLTF1.GLTFLoader = GLTFLoader;
  107754. ;
  107755. BABYLON.GLTFFileLoader.CreateGLTFLoaderV1 = function () { return new GLTFLoader(); };
  107756. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  107757. })(BABYLON || (BABYLON = {}));
  107758. //# sourceMappingURL=babylon.glTFLoader.js.map
  107759. var BABYLON;
  107760. (function (BABYLON) {
  107761. var GLTF1;
  107762. (function (GLTF1) {
  107763. /**
  107764. * Utils functions for GLTF
  107765. */
  107766. var GLTFUtils = /** @class */ (function () {
  107767. function GLTFUtils() {
  107768. }
  107769. /**
  107770. * Sets the given "parameter" matrix
  107771. * @param scene: the {BABYLON.Scene} object
  107772. * @param source: the source node where to pick the matrix
  107773. * @param parameter: the GLTF technique parameter
  107774. * @param uniformName: the name of the shader's uniform
  107775. * @param shaderMaterial: the shader material
  107776. */
  107777. GLTFUtils.SetMatrix = function (scene, source, parameter, uniformName, shaderMaterial) {
  107778. var mat = null;
  107779. if (parameter.semantic === "MODEL") {
  107780. mat = source.getWorldMatrix();
  107781. }
  107782. else if (parameter.semantic === "PROJECTION") {
  107783. mat = scene.getProjectionMatrix();
  107784. }
  107785. else if (parameter.semantic === "VIEW") {
  107786. mat = scene.getViewMatrix();
  107787. }
  107788. else if (parameter.semantic === "MODELVIEWINVERSETRANSPOSE") {
  107789. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().multiply(scene.getViewMatrix()).invert());
  107790. }
  107791. else if (parameter.semantic === "MODELVIEW") {
  107792. mat = source.getWorldMatrix().multiply(scene.getViewMatrix());
  107793. }
  107794. else if (parameter.semantic === "MODELVIEWPROJECTION") {
  107795. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix());
  107796. }
  107797. else if (parameter.semantic === "MODELINVERSE") {
  107798. mat = source.getWorldMatrix().invert();
  107799. }
  107800. else if (parameter.semantic === "VIEWINVERSE") {
  107801. mat = scene.getViewMatrix().invert();
  107802. }
  107803. else if (parameter.semantic === "PROJECTIONINVERSE") {
  107804. mat = scene.getProjectionMatrix().invert();
  107805. }
  107806. else if (parameter.semantic === "MODELVIEWINVERSE") {
  107807. mat = source.getWorldMatrix().multiply(scene.getViewMatrix()).invert();
  107808. }
  107809. else if (parameter.semantic === "MODELVIEWPROJECTIONINVERSE") {
  107810. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix()).invert();
  107811. }
  107812. else if (parameter.semantic === "MODELINVERSETRANSPOSE") {
  107813. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().invert());
  107814. }
  107815. else {
  107816. debugger;
  107817. }
  107818. if (mat) {
  107819. switch (parameter.type) {
  107820. case GLTF1.EParameterType.FLOAT_MAT2:
  107821. shaderMaterial.setMatrix2x2(uniformName, BABYLON.Matrix.GetAsMatrix2x2(mat));
  107822. break;
  107823. case GLTF1.EParameterType.FLOAT_MAT3:
  107824. shaderMaterial.setMatrix3x3(uniformName, BABYLON.Matrix.GetAsMatrix3x3(mat));
  107825. break;
  107826. case GLTF1.EParameterType.FLOAT_MAT4:
  107827. shaderMaterial.setMatrix(uniformName, mat);
  107828. break;
  107829. default: break;
  107830. }
  107831. }
  107832. };
  107833. /**
  107834. * Sets the given "parameter" matrix
  107835. * @param shaderMaterial: the shader material
  107836. * @param uniform: the name of the shader's uniform
  107837. * @param value: the value of the uniform
  107838. * @param type: the uniform's type (EParameterType FLOAT, VEC2, VEC3 or VEC4)
  107839. */
  107840. GLTFUtils.SetUniform = function (shaderMaterial, uniform, value, type) {
  107841. switch (type) {
  107842. case GLTF1.EParameterType.FLOAT:
  107843. shaderMaterial.setFloat(uniform, value);
  107844. return true;
  107845. case GLTF1.EParameterType.FLOAT_VEC2:
  107846. shaderMaterial.setVector2(uniform, BABYLON.Vector2.FromArray(value));
  107847. return true;
  107848. case GLTF1.EParameterType.FLOAT_VEC3:
  107849. shaderMaterial.setVector3(uniform, BABYLON.Vector3.FromArray(value));
  107850. return true;
  107851. case GLTF1.EParameterType.FLOAT_VEC4:
  107852. shaderMaterial.setVector4(uniform, BABYLON.Vector4.FromArray(value));
  107853. return true;
  107854. default: return false;
  107855. }
  107856. };
  107857. /**
  107858. * Returns the wrap mode of the texture
  107859. * @param mode: the mode value
  107860. */
  107861. GLTFUtils.GetWrapMode = function (mode) {
  107862. switch (mode) {
  107863. case GLTF1.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  107864. case GLTF1.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  107865. case GLTF1.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  107866. default: return BABYLON.Texture.WRAP_ADDRESSMODE;
  107867. }
  107868. };
  107869. /**
  107870. * Returns the byte stride giving an accessor
  107871. * @param accessor: the GLTF accessor objet
  107872. */
  107873. GLTFUtils.GetByteStrideFromType = function (accessor) {
  107874. // Needs this function since "byteStride" isn't requiered in glTF format
  107875. var type = accessor.type;
  107876. switch (type) {
  107877. case "VEC2": return 2;
  107878. case "VEC3": return 3;
  107879. case "VEC4": return 4;
  107880. case "MAT2": return 4;
  107881. case "MAT3": return 9;
  107882. case "MAT4": return 16;
  107883. default: return 1;
  107884. }
  107885. };
  107886. /**
  107887. * Returns the texture filter mode giving a mode value
  107888. * @param mode: the filter mode value
  107889. */
  107890. GLTFUtils.GetTextureFilterMode = function (mode) {
  107891. switch (mode) {
  107892. case GLTF1.ETextureFilterType.LINEAR:
  107893. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST:
  107894. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  107895. case GLTF1.ETextureFilterType.NEAREST:
  107896. case GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_SAMPLINGMODE;
  107897. default: return BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  107898. }
  107899. };
  107900. GLTFUtils.GetBufferFromBufferView = function (gltfRuntime, bufferView, byteOffset, byteLength, componentType) {
  107901. var byteOffset = bufferView.byteOffset + byteOffset;
  107902. var loadedBufferView = gltfRuntime.loadedBufferViews[bufferView.buffer];
  107903. if (byteOffset + byteLength > loadedBufferView.byteLength) {
  107904. throw new Error("Buffer access is out of range");
  107905. }
  107906. var buffer = loadedBufferView.buffer;
  107907. byteOffset += loadedBufferView.byteOffset;
  107908. switch (componentType) {
  107909. case GLTF1.EComponentType.BYTE: return new Int8Array(buffer, byteOffset, byteLength);
  107910. case GLTF1.EComponentType.UNSIGNED_BYTE: return new Uint8Array(buffer, byteOffset, byteLength);
  107911. case GLTF1.EComponentType.SHORT: return new Int16Array(buffer, byteOffset, byteLength);
  107912. case GLTF1.EComponentType.UNSIGNED_SHORT: return new Uint16Array(buffer, byteOffset, byteLength);
  107913. default: return new Float32Array(buffer, byteOffset, byteLength);
  107914. }
  107915. };
  107916. /**
  107917. * Returns a buffer from its accessor
  107918. * @param gltfRuntime: the GLTF runtime
  107919. * @param accessor: the GLTF accessor
  107920. */
  107921. GLTFUtils.GetBufferFromAccessor = function (gltfRuntime, accessor) {
  107922. var bufferView = gltfRuntime.bufferViews[accessor.bufferView];
  107923. var byteLength = accessor.count * GLTFUtils.GetByteStrideFromType(accessor);
  107924. return GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, accessor.byteOffset, byteLength, accessor.componentType);
  107925. };
  107926. /**
  107927. * Decodes a buffer view into a string
  107928. * @param view: the buffer view
  107929. */
  107930. GLTFUtils.DecodeBufferToText = function (view) {
  107931. var result = "";
  107932. var length = view.byteLength;
  107933. for (var i = 0; i < length; ++i) {
  107934. result += String.fromCharCode(view[i]);
  107935. }
  107936. return result;
  107937. };
  107938. /**
  107939. * Returns the default material of gltf. Related to
  107940. * https://github.com/KhronosGroup/glTF/tree/master/specification/1.0#appendix-a-default-material
  107941. * @param scene: the Babylon.js scene
  107942. */
  107943. GLTFUtils.GetDefaultMaterial = function (scene) {
  107944. if (!GLTFUtils._DefaultMaterial) {
  107945. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialVertexShader"] = [
  107946. "precision highp float;",
  107947. "",
  107948. "uniform mat4 worldView;",
  107949. "uniform mat4 projection;",
  107950. "",
  107951. "attribute vec3 position;",
  107952. "",
  107953. "void main(void)",
  107954. "{",
  107955. " gl_Position = projection * worldView * vec4(position, 1.0);",
  107956. "}"
  107957. ].join("\n");
  107958. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialPixelShader"] = [
  107959. "precision highp float;",
  107960. "",
  107961. "uniform vec4 u_emission;",
  107962. "",
  107963. "void main(void)",
  107964. "{",
  107965. " gl_FragColor = u_emission;",
  107966. "}"
  107967. ].join("\n");
  107968. var shaderPath = {
  107969. vertex: "GLTFDefaultMaterial",
  107970. fragment: "GLTFDefaultMaterial"
  107971. };
  107972. var options = {
  107973. attributes: ["position"],
  107974. uniforms: ["worldView", "projection", "u_emission"],
  107975. samplers: new Array(),
  107976. needAlphaBlending: false
  107977. };
  107978. GLTFUtils._DefaultMaterial = new BABYLON.ShaderMaterial("GLTFDefaultMaterial", scene, shaderPath, options);
  107979. GLTFUtils._DefaultMaterial.setColor4("u_emission", new BABYLON.Color4(0.5, 0.5, 0.5, 1.0));
  107980. }
  107981. return GLTFUtils._DefaultMaterial;
  107982. };
  107983. // The GLTF default material
  107984. GLTFUtils._DefaultMaterial = null;
  107985. return GLTFUtils;
  107986. }());
  107987. GLTF1.GLTFUtils = GLTFUtils;
  107988. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  107989. })(BABYLON || (BABYLON = {}));
  107990. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  107991. var BABYLON;
  107992. (function (BABYLON) {
  107993. var GLTF1;
  107994. (function (GLTF1) {
  107995. var GLTFLoaderExtension = /** @class */ (function () {
  107996. function GLTFLoaderExtension(name) {
  107997. this._name = name;
  107998. }
  107999. Object.defineProperty(GLTFLoaderExtension.prototype, "name", {
  108000. get: function () {
  108001. return this._name;
  108002. },
  108003. enumerable: true,
  108004. configurable: true
  108005. });
  108006. /**
  108007. * Defines an override for loading the runtime
  108008. * Return true to stop further extensions from loading the runtime
  108009. */
  108010. GLTFLoaderExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  108011. return false;
  108012. };
  108013. /**
  108014. * Defines an onverride for creating gltf runtime
  108015. * Return true to stop further extensions from creating the runtime
  108016. */
  108017. GLTFLoaderExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  108018. return false;
  108019. };
  108020. /**
  108021. * Defines an override for loading buffers
  108022. * Return true to stop further extensions from loading this buffer
  108023. */
  108024. GLTFLoaderExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  108025. return false;
  108026. };
  108027. /**
  108028. * Defines an override for loading texture buffers
  108029. * Return true to stop further extensions from loading this texture data
  108030. */
  108031. GLTFLoaderExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  108032. return false;
  108033. };
  108034. /**
  108035. * Defines an override for creating textures
  108036. * Return true to stop further extensions from loading this texture
  108037. */
  108038. GLTFLoaderExtension.prototype.createTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  108039. return false;
  108040. };
  108041. /**
  108042. * Defines an override for loading shader strings
  108043. * Return true to stop further extensions from loading this shader data
  108044. */
  108045. GLTFLoaderExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  108046. return false;
  108047. };
  108048. /**
  108049. * Defines an override for loading materials
  108050. * Return true to stop further extensions from loading this material
  108051. */
  108052. GLTFLoaderExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  108053. return false;
  108054. };
  108055. // ---------
  108056. // Utilities
  108057. // ---------
  108058. GLTFLoaderExtension.LoadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  108059. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  108060. return loaderExtension.loadRuntimeAsync(scene, data, rootUrl, onSuccess, onError);
  108061. }, function () {
  108062. setTimeout(function () {
  108063. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  108064. });
  108065. });
  108066. };
  108067. GLTFLoaderExtension.LoadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  108068. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  108069. return loaderExtension.loadRuntimeExtensionsAsync(gltfRuntime, onSuccess, onError);
  108070. }, function () {
  108071. setTimeout(function () {
  108072. onSuccess();
  108073. });
  108074. });
  108075. };
  108076. GLTFLoaderExtension.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  108077. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  108078. return loaderExtension.loadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  108079. }, function () {
  108080. GLTF1.GLTFLoaderBase.LoadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  108081. });
  108082. };
  108083. GLTFLoaderExtension.LoadTextureAsync = function (gltfRuntime, id, onSuccess, onError) {
  108084. GLTFLoaderExtension.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) { return GLTFLoaderExtension.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError); }, onError);
  108085. };
  108086. GLTFLoaderExtension.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  108087. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  108088. return loaderExtension.loadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  108089. }, function () {
  108090. GLTF1.GLTFLoaderBase.LoadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  108091. });
  108092. };
  108093. GLTFLoaderExtension.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  108094. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  108095. return loaderExtension.loadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  108096. }, function () {
  108097. GLTF1.GLTFLoaderBase.LoadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  108098. });
  108099. };
  108100. GLTFLoaderExtension.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  108101. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  108102. return loaderExtension.loadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  108103. }, function () {
  108104. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  108105. });
  108106. };
  108107. GLTFLoaderExtension.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  108108. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  108109. return loaderExtension.createTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  108110. }, function () {
  108111. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  108112. });
  108113. };
  108114. GLTFLoaderExtension.ApplyExtensions = function (func, defaultFunc) {
  108115. for (var extensionName in GLTF1.GLTFLoader.Extensions) {
  108116. var loaderExtension = GLTF1.GLTFLoader.Extensions[extensionName];
  108117. if (func(loaderExtension)) {
  108118. return;
  108119. }
  108120. }
  108121. defaultFunc();
  108122. };
  108123. return GLTFLoaderExtension;
  108124. }());
  108125. GLTF1.GLTFLoaderExtension = GLTFLoaderExtension;
  108126. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  108127. })(BABYLON || (BABYLON = {}));
  108128. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  108129. var BABYLON;
  108130. (function (BABYLON) {
  108131. var GLTF1;
  108132. (function (GLTF1) {
  108133. var BinaryExtensionBufferName = "binary_glTF";
  108134. ;
  108135. ;
  108136. var GLTFBinaryExtension = /** @class */ (function (_super) {
  108137. __extends(GLTFBinaryExtension, _super);
  108138. function GLTFBinaryExtension() {
  108139. return _super.call(this, "KHR_binary_glTF") || this;
  108140. }
  108141. GLTFBinaryExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  108142. var extensionsUsed = data.json.extensionsUsed;
  108143. if (!extensionsUsed || extensionsUsed.indexOf(this.name) === -1 || !data.bin) {
  108144. return false;
  108145. }
  108146. this._bin = data.bin;
  108147. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  108148. return true;
  108149. };
  108150. GLTFBinaryExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  108151. if (gltfRuntime.extensionsUsed.indexOf(this.name) === -1) {
  108152. return false;
  108153. }
  108154. if (id !== BinaryExtensionBufferName) {
  108155. return false;
  108156. }
  108157. onSuccess(this._bin);
  108158. return true;
  108159. };
  108160. GLTFBinaryExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  108161. var texture = gltfRuntime.textures[id];
  108162. var source = gltfRuntime.images[texture.source];
  108163. if (!source.extensions || !(this.name in source.extensions)) {
  108164. return false;
  108165. }
  108166. var sourceExt = source.extensions[this.name];
  108167. var bufferView = gltfRuntime.bufferViews[sourceExt.bufferView];
  108168. var buffer = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  108169. onSuccess(buffer);
  108170. return true;
  108171. };
  108172. GLTFBinaryExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  108173. var shader = gltfRuntime.shaders[id];
  108174. if (!shader.extensions || !(this.name in shader.extensions)) {
  108175. return false;
  108176. }
  108177. var binaryExtensionShader = shader.extensions[this.name];
  108178. var bufferView = gltfRuntime.bufferViews[binaryExtensionShader.bufferView];
  108179. var shaderBytes = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  108180. setTimeout(function () {
  108181. var shaderString = GLTF1.GLTFUtils.DecodeBufferToText(shaderBytes);
  108182. onSuccess(shaderString);
  108183. });
  108184. return true;
  108185. };
  108186. return GLTFBinaryExtension;
  108187. }(GLTF1.GLTFLoaderExtension));
  108188. GLTF1.GLTFBinaryExtension = GLTFBinaryExtension;
  108189. GLTF1.GLTFLoader.RegisterExtension(new GLTFBinaryExtension());
  108190. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  108191. })(BABYLON || (BABYLON = {}));
  108192. //# sourceMappingURL=babylon.glTFBinaryExtension.js.map
  108193. var BABYLON;
  108194. (function (BABYLON) {
  108195. var GLTF1;
  108196. (function (GLTF1) {
  108197. ;
  108198. ;
  108199. ;
  108200. var GLTFMaterialsCommonExtension = /** @class */ (function (_super) {
  108201. __extends(GLTFMaterialsCommonExtension, _super);
  108202. function GLTFMaterialsCommonExtension() {
  108203. return _super.call(this, "KHR_materials_common") || this;
  108204. }
  108205. GLTFMaterialsCommonExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  108206. if (!gltfRuntime.extensions)
  108207. return false;
  108208. var extension = gltfRuntime.extensions[this.name];
  108209. if (!extension)
  108210. return false;
  108211. // Create lights
  108212. var lights = extension.lights;
  108213. if (lights) {
  108214. for (var thing in lights) {
  108215. var light = lights[thing];
  108216. switch (light.type) {
  108217. case "ambient":
  108218. var ambientLight = new BABYLON.HemisphericLight(light.name, new BABYLON.Vector3(0, 1, 0), gltfRuntime.scene);
  108219. var ambient = light.ambient;
  108220. if (ambient) {
  108221. ambientLight.diffuse = BABYLON.Color3.FromArray(ambient.color || [1, 1, 1]);
  108222. }
  108223. break;
  108224. case "point":
  108225. var pointLight = new BABYLON.PointLight(light.name, new BABYLON.Vector3(10, 10, 10), gltfRuntime.scene);
  108226. var point = light.point;
  108227. if (point) {
  108228. pointLight.diffuse = BABYLON.Color3.FromArray(point.color || [1, 1, 1]);
  108229. }
  108230. break;
  108231. case "directional":
  108232. var dirLight = new BABYLON.DirectionalLight(light.name, new BABYLON.Vector3(0, -1, 0), gltfRuntime.scene);
  108233. var directional = light.directional;
  108234. if (directional) {
  108235. dirLight.diffuse = BABYLON.Color3.FromArray(directional.color || [1, 1, 1]);
  108236. }
  108237. break;
  108238. case "spot":
  108239. var spot = light.spot;
  108240. if (spot) {
  108241. var spotLight = new BABYLON.SpotLight(light.name, new BABYLON.Vector3(0, 10, 0), new BABYLON.Vector3(0, -1, 0), spot.fallOffAngle || Math.PI, spot.fallOffExponent || 0.0, gltfRuntime.scene);
  108242. spotLight.diffuse = BABYLON.Color3.FromArray(spot.color || [1, 1, 1]);
  108243. }
  108244. break;
  108245. default:
  108246. BABYLON.Tools.Warn("GLTF Material Common extension: light type \"" + light.type + "\” not supported");
  108247. break;
  108248. }
  108249. }
  108250. }
  108251. return false;
  108252. };
  108253. GLTFMaterialsCommonExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  108254. var material = gltfRuntime.materials[id];
  108255. if (!material || !material.extensions)
  108256. return false;
  108257. var extension = material.extensions[this.name];
  108258. if (!extension)
  108259. return false;
  108260. var standardMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  108261. standardMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  108262. if (extension.technique === "CONSTANT") {
  108263. standardMaterial.disableLighting = true;
  108264. }
  108265. standardMaterial.backFaceCulling = extension.doubleSided === undefined ? false : !extension.doubleSided;
  108266. standardMaterial.alpha = extension.values.transparency === undefined ? 1.0 : extension.values.transparency;
  108267. standardMaterial.specularPower = extension.values.shininess === undefined ? 0.0 : extension.values.shininess;
  108268. // Ambient
  108269. if (typeof extension.values.ambient === "string") {
  108270. this._loadTexture(gltfRuntime, extension.values.ambient, standardMaterial, "ambientTexture", onError);
  108271. }
  108272. else {
  108273. standardMaterial.ambientColor = BABYLON.Color3.FromArray(extension.values.ambient || [0, 0, 0]);
  108274. }
  108275. // Diffuse
  108276. if (typeof extension.values.diffuse === "string") {
  108277. this._loadTexture(gltfRuntime, extension.values.diffuse, standardMaterial, "diffuseTexture", onError);
  108278. }
  108279. else {
  108280. standardMaterial.diffuseColor = BABYLON.Color3.FromArray(extension.values.diffuse || [0, 0, 0]);
  108281. }
  108282. // Emission
  108283. if (typeof extension.values.emission === "string") {
  108284. this._loadTexture(gltfRuntime, extension.values.emission, standardMaterial, "emissiveTexture", onError);
  108285. }
  108286. else {
  108287. standardMaterial.emissiveColor = BABYLON.Color3.FromArray(extension.values.emission || [0, 0, 0]);
  108288. }
  108289. // Specular
  108290. if (typeof extension.values.specular === "string") {
  108291. this._loadTexture(gltfRuntime, extension.values.specular, standardMaterial, "specularTexture", onError);
  108292. }
  108293. else {
  108294. standardMaterial.specularColor = BABYLON.Color3.FromArray(extension.values.specular || [0, 0, 0]);
  108295. }
  108296. return true;
  108297. };
  108298. GLTFMaterialsCommonExtension.prototype._loadTexture = function (gltfRuntime, id, material, propertyPath, onError) {
  108299. // Create buffer from texture url
  108300. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  108301. // Create texture from buffer
  108302. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, function (texture) { return material[propertyPath] = texture; }, onError);
  108303. }, onError);
  108304. };
  108305. return GLTFMaterialsCommonExtension;
  108306. }(GLTF1.GLTFLoaderExtension));
  108307. GLTF1.GLTFMaterialsCommonExtension = GLTFMaterialsCommonExtension;
  108308. GLTF1.GLTFLoader.RegisterExtension(new GLTFMaterialsCommonExtension());
  108309. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  108310. })(BABYLON || (BABYLON = {}));
  108311. //# sourceMappingURL=babylon.glTFMaterialsCommonExtension.js.map
  108312. var BABYLON;
  108313. (function (BABYLON) {
  108314. var GLTF2;
  108315. (function (GLTF2) {
  108316. var ArrayItem = /** @class */ (function () {
  108317. function ArrayItem() {
  108318. }
  108319. ArrayItem.Assign = function (values) {
  108320. if (values) {
  108321. for (var index = 0; index < values.length; index++) {
  108322. values[index]._index = index;
  108323. }
  108324. }
  108325. };
  108326. return ArrayItem;
  108327. }());
  108328. GLTF2.ArrayItem = ArrayItem;
  108329. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  108330. })(BABYLON || (BABYLON = {}));
  108331. //# sourceMappingURL=babylon.glTFLoaderUtilities.js.map
  108332. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  108333. var BABYLON;
  108334. (function (BABYLON) {
  108335. var GLTF2;
  108336. (function (GLTF2) {
  108337. var GLTFLoader = /** @class */ (function () {
  108338. function GLTFLoader() {
  108339. this._completePromises = new Array();
  108340. this._disposed = false;
  108341. this._state = null;
  108342. this._extensions = {};
  108343. this._defaultSampler = {};
  108344. this._requests = new Array();
  108345. this.coordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode.AUTO;
  108346. this.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.FIRST;
  108347. this.compileMaterials = false;
  108348. this.useClipPlane = false;
  108349. this.compileShadowGenerators = false;
  108350. this.onDisposeObservable = new BABYLON.Observable();
  108351. this.onMeshLoadedObservable = new BABYLON.Observable();
  108352. this.onTextureLoadedObservable = new BABYLON.Observable();
  108353. this.onMaterialLoadedObservable = new BABYLON.Observable();
  108354. this.onAnimationGroupLoadedObservable = new BABYLON.Observable();
  108355. this.onExtensionLoadedObservable = new BABYLON.Observable();
  108356. this.onCompleteObservable = new BABYLON.Observable();
  108357. }
  108358. GLTFLoader._Register = function (name, factory) {
  108359. if (GLTFLoader._Factories[name]) {
  108360. BABYLON.Tools.Error("Extension with the name '" + name + "' already exists");
  108361. return;
  108362. }
  108363. GLTFLoader._Factories[name] = factory;
  108364. // Keep the order of registration so that extensions registered first are called first.
  108365. GLTFLoader._Names.push(name);
  108366. };
  108367. Object.defineProperty(GLTFLoader.prototype, "state", {
  108368. get: function () {
  108369. return this._state;
  108370. },
  108371. enumerable: true,
  108372. configurable: true
  108373. });
  108374. GLTFLoader.prototype.dispose = function () {
  108375. if (this._disposed) {
  108376. return;
  108377. }
  108378. this._disposed = true;
  108379. this.onDisposeObservable.notifyObservers(this);
  108380. this.onDisposeObservable.clear();
  108381. this._clear();
  108382. };
  108383. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  108384. var _this = this;
  108385. return Promise.resolve().then(function () {
  108386. var nodes = null;
  108387. if (meshesNames) {
  108388. var nodeMap_1 = {};
  108389. if (_this._gltf.nodes) {
  108390. for (var _i = 0, _a = _this._gltf.nodes; _i < _a.length; _i++) {
  108391. var node = _a[_i];
  108392. if (node.name) {
  108393. nodeMap_1[node.name] = node;
  108394. }
  108395. }
  108396. }
  108397. var names = (meshesNames instanceof Array) ? meshesNames : [meshesNames];
  108398. nodes = names.map(function (name) {
  108399. var node = nodeMap_1[name];
  108400. if (!node) {
  108401. throw new Error("Failed to find node '" + name + "'");
  108402. }
  108403. return node;
  108404. });
  108405. }
  108406. return _this._loadAsync(nodes, scene, data, rootUrl, onProgress).then(function () {
  108407. return {
  108408. meshes: _this._getMeshes(),
  108409. particleSystems: [],
  108410. skeletons: _this._getSkeletons(),
  108411. };
  108412. });
  108413. });
  108414. };
  108415. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  108416. return this._loadAsync(null, scene, data, rootUrl, onProgress);
  108417. };
  108418. GLTFLoader.prototype._loadAsync = function (nodes, scene, data, rootUrl, onProgress) {
  108419. var _this = this;
  108420. return Promise.resolve().then(function () {
  108421. _this._loadExtensions();
  108422. _this._babylonScene = scene;
  108423. _this._rootUrl = rootUrl;
  108424. _this._progressCallback = onProgress;
  108425. _this._state = BABYLON.GLTFLoaderState.Loading;
  108426. _this._loadData(data);
  108427. _this._checkExtensions();
  108428. var promises = new Array();
  108429. if (nodes) {
  108430. promises.push(_this._loadNodesAsync(nodes));
  108431. }
  108432. else {
  108433. var scene_1 = GLTFLoader._GetProperty("#/scene", _this._gltf.scenes, _this._gltf.scene || 0);
  108434. promises.push(_this._loadSceneAsync("#/scenes/" + scene_1._index, scene_1));
  108435. }
  108436. if (_this.compileMaterials) {
  108437. promises.push(_this._compileMaterialsAsync());
  108438. }
  108439. if (_this.compileShadowGenerators) {
  108440. promises.push(_this._compileShadowGeneratorsAsync());
  108441. }
  108442. var resultPromise = Promise.all(promises).then(function () {
  108443. _this._state = BABYLON.GLTFLoaderState.Ready;
  108444. _this._startAnimations();
  108445. });
  108446. resultPromise.then(function () {
  108447. _this._rootBabylonMesh.setEnabled(true);
  108448. BABYLON.Tools.SetImmediate(function () {
  108449. if (!_this._disposed) {
  108450. Promise.all(_this._completePromises).then(function () {
  108451. _this._state = BABYLON.GLTFLoaderState.Complete;
  108452. _this.onCompleteObservable.notifyObservers(_this);
  108453. _this.onCompleteObservable.clear();
  108454. _this._clear();
  108455. }).catch(function (error) {
  108456. BABYLON.Tools.Error("glTF Loader: " + error.message);
  108457. _this._clear();
  108458. });
  108459. }
  108460. });
  108461. });
  108462. return resultPromise;
  108463. }).catch(function (error) {
  108464. BABYLON.Tools.Error("glTF Loader: " + error.message);
  108465. _this._clear();
  108466. throw error;
  108467. });
  108468. };
  108469. GLTFLoader.prototype._loadExtensions = function () {
  108470. for (var _i = 0, _a = GLTFLoader._Names; _i < _a.length; _i++) {
  108471. var name_1 = _a[_i];
  108472. var extension = GLTFLoader._Factories[name_1](this);
  108473. this._extensions[name_1] = extension;
  108474. this.onExtensionLoadedObservable.notifyObservers(extension);
  108475. }
  108476. this.onExtensionLoadedObservable.clear();
  108477. };
  108478. GLTFLoader.prototype._loadData = function (data) {
  108479. this._gltf = data.json;
  108480. this._setupData();
  108481. if (data.bin) {
  108482. var buffers = this._gltf.buffers;
  108483. if (buffers && buffers[0] && !buffers[0].uri) {
  108484. var binaryBuffer = buffers[0];
  108485. if (binaryBuffer.byteLength < data.bin.byteLength - 3 || binaryBuffer.byteLength > data.bin.byteLength) {
  108486. BABYLON.Tools.Warn("Binary buffer length (" + binaryBuffer.byteLength + ") from JSON does not match chunk length (" + data.bin.byteLength + ")");
  108487. }
  108488. binaryBuffer._data = Promise.resolve(data.bin);
  108489. }
  108490. else {
  108491. BABYLON.Tools.Warn("Unexpected BIN chunk");
  108492. }
  108493. }
  108494. };
  108495. GLTFLoader.prototype._setupData = function () {
  108496. GLTF2.ArrayItem.Assign(this._gltf.accessors);
  108497. GLTF2.ArrayItem.Assign(this._gltf.animations);
  108498. GLTF2.ArrayItem.Assign(this._gltf.buffers);
  108499. GLTF2.ArrayItem.Assign(this._gltf.bufferViews);
  108500. GLTF2.ArrayItem.Assign(this._gltf.cameras);
  108501. GLTF2.ArrayItem.Assign(this._gltf.images);
  108502. GLTF2.ArrayItem.Assign(this._gltf.materials);
  108503. GLTF2.ArrayItem.Assign(this._gltf.meshes);
  108504. GLTF2.ArrayItem.Assign(this._gltf.nodes);
  108505. GLTF2.ArrayItem.Assign(this._gltf.samplers);
  108506. GLTF2.ArrayItem.Assign(this._gltf.scenes);
  108507. GLTF2.ArrayItem.Assign(this._gltf.skins);
  108508. GLTF2.ArrayItem.Assign(this._gltf.textures);
  108509. if (this._gltf.nodes) {
  108510. var nodeParents = {};
  108511. for (var _i = 0, _a = this._gltf.nodes; _i < _a.length; _i++) {
  108512. var node = _a[_i];
  108513. if (node.children) {
  108514. for (var _b = 0, _c = node.children; _b < _c.length; _b++) {
  108515. var index = _c[_b];
  108516. nodeParents[index] = node._index;
  108517. }
  108518. }
  108519. }
  108520. var rootNode = this._createRootNode();
  108521. for (var _d = 0, _e = this._gltf.nodes; _d < _e.length; _d++) {
  108522. var node = _e[_d];
  108523. var parentIndex = nodeParents[node._index];
  108524. node._parent = parentIndex === undefined ? rootNode : this._gltf.nodes[parentIndex];
  108525. }
  108526. }
  108527. };
  108528. GLTFLoader.prototype._checkExtensions = function () {
  108529. if (this._gltf.extensionsRequired) {
  108530. for (var _i = 0, _a = this._gltf.extensionsRequired; _i < _a.length; _i++) {
  108531. var name_2 = _a[_i];
  108532. var extension = this._extensions[name_2];
  108533. if (!extension || !extension.enabled) {
  108534. throw new Error("Require extension " + name_2 + " is not available");
  108535. }
  108536. }
  108537. }
  108538. };
  108539. GLTFLoader.prototype._createRootNode = function () {
  108540. this._rootBabylonMesh = new BABYLON.Mesh("__root__", this._babylonScene);
  108541. this._rootBabylonMesh.setEnabled(false);
  108542. var rootNode = { _babylonMesh: this._rootBabylonMesh };
  108543. switch (this.coordinateSystemMode) {
  108544. case BABYLON.GLTFLoaderCoordinateSystemMode.AUTO: {
  108545. if (!this._babylonScene.useRightHandedSystem) {
  108546. rootNode.rotation = [0, 1, 0, 0];
  108547. rootNode.scale = [1, 1, -1];
  108548. GLTFLoader._LoadTransform(rootNode, this._rootBabylonMesh);
  108549. }
  108550. break;
  108551. }
  108552. case BABYLON.GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED: {
  108553. this._babylonScene.useRightHandedSystem = true;
  108554. break;
  108555. }
  108556. default: {
  108557. throw new Error("Invalid coordinate system mode (" + this.coordinateSystemMode + ")");
  108558. }
  108559. }
  108560. this.onMeshLoadedObservable.notifyObservers(this._rootBabylonMesh);
  108561. return rootNode;
  108562. };
  108563. GLTFLoader.prototype._loadNodesAsync = function (nodes) {
  108564. var promises = new Array();
  108565. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  108566. var node = nodes_1[_i];
  108567. promises.push(this._loadNodeAsync("#/nodes/" + node._index, node));
  108568. }
  108569. promises.push(this._loadAnimationsAsync());
  108570. return Promise.all(promises).then(function () { });
  108571. };
  108572. GLTFLoader.prototype._loadSceneAsync = function (context, scene) {
  108573. var promise = GLTF2.GLTFLoaderExtension._LoadSceneAsync(this, context, scene);
  108574. if (promise) {
  108575. return promise;
  108576. }
  108577. var promises = new Array();
  108578. for (var _i = 0, _a = scene.nodes; _i < _a.length; _i++) {
  108579. var index = _a[_i];
  108580. var node = GLTFLoader._GetProperty(context + "/nodes/" + index, this._gltf.nodes, index);
  108581. promises.push(this._loadNodeAsync("#/nodes/" + node._index, node));
  108582. }
  108583. promises.push(this._loadAnimationsAsync());
  108584. return Promise.all(promises).then(function () { });
  108585. };
  108586. GLTFLoader.prototype._forEachNodeMesh = function (node, callback) {
  108587. if (node._babylonMesh) {
  108588. callback(node._babylonMesh);
  108589. }
  108590. if (node._primitiveBabylonMeshes) {
  108591. for (var _i = 0, _a = node._primitiveBabylonMeshes; _i < _a.length; _i++) {
  108592. var babylonMesh = _a[_i];
  108593. callback(babylonMesh);
  108594. }
  108595. }
  108596. };
  108597. GLTFLoader.prototype._getMeshes = function () {
  108598. var meshes = new Array();
  108599. // Root mesh is always first.
  108600. meshes.push(this._rootBabylonMesh);
  108601. var nodes = this._gltf.nodes;
  108602. if (nodes) {
  108603. for (var _i = 0, nodes_2 = nodes; _i < nodes_2.length; _i++) {
  108604. var node = nodes_2[_i];
  108605. this._forEachNodeMesh(node, function (mesh) {
  108606. meshes.push(mesh);
  108607. });
  108608. }
  108609. }
  108610. return meshes;
  108611. };
  108612. GLTFLoader.prototype._getSkeletons = function () {
  108613. var skeletons = new Array();
  108614. var skins = this._gltf.skins;
  108615. if (skins) {
  108616. for (var _i = 0, skins_1 = skins; _i < skins_1.length; _i++) {
  108617. var skin = skins_1[_i];
  108618. if (skin._babylonSkeleton) {
  108619. skeletons.push(skin._babylonSkeleton);
  108620. }
  108621. }
  108622. }
  108623. return skeletons;
  108624. };
  108625. GLTFLoader.prototype._startAnimations = function () {
  108626. var animations = this._gltf.animations;
  108627. if (!animations) {
  108628. return;
  108629. }
  108630. switch (this.animationStartMode) {
  108631. case BABYLON.GLTFLoaderAnimationStartMode.NONE: {
  108632. // do nothing
  108633. break;
  108634. }
  108635. case BABYLON.GLTFLoaderAnimationStartMode.FIRST: {
  108636. var animation = animations[0];
  108637. animation._babylonAnimationGroup.start(true);
  108638. break;
  108639. }
  108640. case BABYLON.GLTFLoaderAnimationStartMode.ALL: {
  108641. for (var _i = 0, animations_1 = animations; _i < animations_1.length; _i++) {
  108642. var animation = animations_1[_i];
  108643. animation._babylonAnimationGroup.start(true);
  108644. }
  108645. break;
  108646. }
  108647. default: {
  108648. BABYLON.Tools.Error("Invalid animation start mode (" + this.animationStartMode + ")");
  108649. return;
  108650. }
  108651. }
  108652. };
  108653. GLTFLoader.prototype._loadNodeAsync = function (context, node) {
  108654. var promise = GLTF2.GLTFLoaderExtension._LoadNodeAsync(this, context, node);
  108655. if (promise) {
  108656. return promise;
  108657. }
  108658. if (node._babylonMesh) {
  108659. throw new Error(context + ": Invalid recursive node hierarchy");
  108660. }
  108661. var promises = new Array();
  108662. var babylonMesh = new BABYLON.Mesh(node.name || "node" + node._index, this._babylonScene, node._parent._babylonMesh);
  108663. node._babylonMesh = babylonMesh;
  108664. node._babylonAnimationTargets = node._babylonAnimationTargets || [];
  108665. node._babylonAnimationTargets.push(babylonMesh);
  108666. GLTFLoader._LoadTransform(node, babylonMesh);
  108667. if (node.mesh != undefined) {
  108668. var mesh = GLTFLoader._GetProperty(context + "/mesh", this._gltf.meshes, node.mesh);
  108669. promises.push(this._loadMeshAsync("#/meshes/" + mesh._index, node, mesh, babylonMesh));
  108670. }
  108671. if (node.children) {
  108672. for (var _i = 0, _a = node.children; _i < _a.length; _i++) {
  108673. var index = _a[_i];
  108674. var childNode = GLTFLoader._GetProperty(context + "/children/" + index, this._gltf.nodes, index);
  108675. promises.push(this._loadNodeAsync("#/nodes/" + index, childNode));
  108676. }
  108677. }
  108678. this.onMeshLoadedObservable.notifyObservers(babylonMesh);
  108679. return Promise.all(promises).then(function () { });
  108680. };
  108681. GLTFLoader.prototype._loadMeshAsync = function (context, node, mesh, babylonMesh) {
  108682. // TODO: instancing
  108683. var _this = this;
  108684. var promises = new Array();
  108685. var primitives = mesh.primitives;
  108686. if (!primitives || primitives.length === 0) {
  108687. throw new Error(context + ": Primitives are missing");
  108688. }
  108689. GLTF2.ArrayItem.Assign(primitives);
  108690. if (primitives.length === 1) {
  108691. var primitive = primitives[0];
  108692. promises.push(this._loadPrimitiveAsync(context + "/primitives/" + primitive._index, node, mesh, primitive, babylonMesh));
  108693. }
  108694. else {
  108695. node._primitiveBabylonMeshes = [];
  108696. for (var _i = 0, primitives_1 = primitives; _i < primitives_1.length; _i++) {
  108697. var primitive = primitives_1[_i];
  108698. var primitiveBabylonMesh = new BABYLON.Mesh((mesh.name || babylonMesh.name) + "_" + primitive._index, this._babylonScene, babylonMesh);
  108699. node._primitiveBabylonMeshes.push(babylonMesh);
  108700. promises.push(this._loadPrimitiveAsync(context + "/primitives/" + primitive._index, node, mesh, primitive, primitiveBabylonMesh));
  108701. this.onMeshLoadedObservable.notifyObservers(babylonMesh);
  108702. }
  108703. }
  108704. if (node.skin != undefined) {
  108705. var skin = GLTFLoader._GetProperty(context + "/skin", this._gltf.skins, node.skin);
  108706. promises.push(this._loadSkinAsync("#/skins/" + skin._index, node, mesh, skin));
  108707. }
  108708. return Promise.all(promises).then(function () {
  108709. _this._forEachNodeMesh(node, function (babylonMesh) {
  108710. babylonMesh._refreshBoundingInfo(true);
  108711. });
  108712. });
  108713. };
  108714. GLTFLoader.prototype._loadPrimitiveAsync = function (context, node, mesh, primitive, babylonMesh) {
  108715. var _this = this;
  108716. var promises = new Array();
  108717. this._createMorphTargets(context, node, mesh, primitive, babylonMesh);
  108718. promises.push(this._loadVertexDataAsync(context, primitive, babylonMesh).then(function (babylonVertexData) {
  108719. new BABYLON.Geometry(babylonMesh.name, _this._babylonScene, babylonVertexData, false, babylonMesh);
  108720. return _this._loadMorphTargetsAsync(context, primitive, babylonMesh, babylonVertexData);
  108721. }));
  108722. if (primitive.material == undefined) {
  108723. babylonMesh.material = this._getDefaultMaterial();
  108724. }
  108725. else {
  108726. var material = GLTFLoader._GetProperty(context + "/material}", this._gltf.materials, primitive.material);
  108727. promises.push(this._loadMaterialAsync("#/materials/" + material._index, material, babylonMesh, function (babylonMaterial) {
  108728. babylonMesh.material = babylonMaterial;
  108729. }));
  108730. }
  108731. return Promise.all(promises).then(function () { });
  108732. };
  108733. GLTFLoader.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) {
  108734. var _this = this;
  108735. var promise = GLTF2.GLTFLoaderExtension._LoadVertexDataAsync(this, context, primitive, babylonMesh);
  108736. if (promise) {
  108737. return promise;
  108738. }
  108739. var attributes = primitive.attributes;
  108740. if (!attributes) {
  108741. throw new Error(context + ": Attributes are missing");
  108742. }
  108743. if (primitive.mode != undefined && primitive.mode !== 4 /* TRIANGLES */) {
  108744. // TODO: handle other primitive modes
  108745. throw new Error(context + ": Mode (" + primitive.mode + ") is not currently supported");
  108746. }
  108747. var promises = new Array();
  108748. var babylonVertexData = new BABYLON.VertexData();
  108749. if (primitive.indices == undefined) {
  108750. var positionAccessorIndex = attributes["POSITION"];
  108751. if (positionAccessorIndex != undefined) {
  108752. var accessor = GLTFLoader._GetProperty(context + "/attributes/POSITION", this._gltf.accessors, positionAccessorIndex);
  108753. babylonVertexData.indices = new Uint32Array(accessor.count);
  108754. for (var i = 0; i < babylonVertexData.indices.length; i++) {
  108755. babylonVertexData.indices[i] = i;
  108756. }
  108757. }
  108758. }
  108759. else {
  108760. var indicesAccessor = GLTFLoader._GetProperty(context + "/indices", this._gltf.accessors, primitive.indices);
  108761. promises.push(this._loadAccessorAsync("#/accessors/" + indicesAccessor._index, indicesAccessor).then(function (data) {
  108762. babylonVertexData.indices = data;
  108763. }));
  108764. }
  108765. var loadAttribute = function (attribute, kind) {
  108766. if (attributes[attribute] == undefined) {
  108767. return;
  108768. }
  108769. babylonMesh._delayInfo = babylonMesh._delayInfo || [];
  108770. if (babylonMesh._delayInfo.indexOf(kind) === -1) {
  108771. babylonMesh._delayInfo.push(kind);
  108772. }
  108773. if (attribute === "COLOR_0") {
  108774. // Assume vertex color has alpha on the mesh. The alphaMode of the material controls whether the material should use alpha or not.
  108775. babylonMesh.hasVertexAlpha = true;
  108776. }
  108777. var accessor = GLTFLoader._GetProperty(context + "/attributes/" + attribute, _this._gltf.accessors, attributes[attribute]);
  108778. promises.push(_this._loadAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  108779. var attributeData = GLTFLoader._ConvertToFloat32Array(context, accessor, data);
  108780. if (attribute === "COLOR_0" && accessor.type === "VEC3") {
  108781. attributeData = GLTFLoader._ConvertVec3ToVec4(context, attributeData);
  108782. }
  108783. babylonVertexData.set(attributeData, kind);
  108784. }));
  108785. };
  108786. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind);
  108787. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind);
  108788. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind);
  108789. loadAttribute("TEXCOORD_0", BABYLON.VertexBuffer.UVKind);
  108790. loadAttribute("TEXCOORD_1", BABYLON.VertexBuffer.UV2Kind);
  108791. loadAttribute("JOINTS_0", BABYLON.VertexBuffer.MatricesIndicesKind);
  108792. loadAttribute("WEIGHTS_0", BABYLON.VertexBuffer.MatricesWeightsKind);
  108793. loadAttribute("COLOR_0", BABYLON.VertexBuffer.ColorKind);
  108794. return Promise.all(promises).then(function () {
  108795. return babylonVertexData;
  108796. });
  108797. };
  108798. GLTFLoader.prototype._createMorphTargets = function (context, node, mesh, primitive, babylonMesh) {
  108799. if (!primitive.targets) {
  108800. return;
  108801. }
  108802. if (node._numMorphTargets == undefined) {
  108803. node._numMorphTargets = primitive.targets.length;
  108804. }
  108805. else if (primitive.targets.length !== node._numMorphTargets) {
  108806. throw new Error(context + ": Primitives do not have the same number of targets");
  108807. }
  108808. babylonMesh.morphTargetManager = new BABYLON.MorphTargetManager();
  108809. for (var index = 0; index < primitive.targets.length; index++) {
  108810. var weight = node.weights ? node.weights[index] : mesh.weights ? mesh.weights[index] : 0;
  108811. babylonMesh.morphTargetManager.addTarget(new BABYLON.MorphTarget("morphTarget" + index, weight));
  108812. // TODO: tell the target whether it has positions, normals, tangents
  108813. }
  108814. };
  108815. GLTFLoader.prototype._loadMorphTargetsAsync = function (context, primitive, babylonMesh, babylonVertexData) {
  108816. if (!primitive.targets) {
  108817. return Promise.resolve();
  108818. }
  108819. var promises = new Array();
  108820. var morphTargetManager = babylonMesh.morphTargetManager;
  108821. for (var index = 0; index < morphTargetManager.numTargets; index++) {
  108822. var babylonMorphTarget = morphTargetManager.getTarget(index);
  108823. promises.push(this._loadMorphTargetVertexDataAsync(context + "/targets/" + index, babylonVertexData, primitive.targets[index], babylonMorphTarget));
  108824. }
  108825. return Promise.all(promises).then(function () { });
  108826. };
  108827. GLTFLoader.prototype._loadMorphTargetVertexDataAsync = function (context, babylonVertexData, attributes, babylonMorphTarget) {
  108828. var _this = this;
  108829. var promises = new Array();
  108830. var loadAttribute = function (attribute, setData) {
  108831. if (attributes[attribute] == undefined) {
  108832. return;
  108833. }
  108834. var accessor = GLTFLoader._GetProperty(context + "/" + attribute, _this._gltf.accessors, attributes[attribute]);
  108835. promises.push(_this._loadAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  108836. setData(data);
  108837. }));
  108838. };
  108839. loadAttribute("POSITION", function (data) {
  108840. if (babylonVertexData.positions) {
  108841. for (var i = 0; i < data.length; i++) {
  108842. data[i] += babylonVertexData.positions[i];
  108843. }
  108844. babylonMorphTarget.setPositions(data);
  108845. }
  108846. });
  108847. loadAttribute("NORMAL", function (data) {
  108848. if (babylonVertexData.normals) {
  108849. for (var i = 0; i < data.length; i++) {
  108850. data[i] += babylonVertexData.normals[i];
  108851. }
  108852. babylonMorphTarget.setNormals(data);
  108853. }
  108854. });
  108855. loadAttribute("TANGENT", function (data) {
  108856. if (babylonVertexData.tangents) {
  108857. // Tangent data for morph targets is stored as xyz delta.
  108858. // The vertexData.tangent is stored as xyzw.
  108859. // So we need to skip every fourth vertexData.tangent.
  108860. for (var i = 0, j = 0; i < data.length; i++) {
  108861. data[i] += babylonVertexData.tangents[j++];
  108862. if ((i + 1) % 3 == 0) {
  108863. j++;
  108864. }
  108865. }
  108866. babylonMorphTarget.setTangents(data);
  108867. }
  108868. });
  108869. return Promise.all(promises).then(function () { });
  108870. };
  108871. GLTFLoader._ConvertToFloat32Array = function (context, accessor, data) {
  108872. if (accessor.componentType == 5126 /* FLOAT */) {
  108873. return data;
  108874. }
  108875. var factor = 1;
  108876. if (accessor.normalized) {
  108877. switch (accessor.componentType) {
  108878. case 5121 /* UNSIGNED_BYTE */: {
  108879. factor = 1 / 255;
  108880. break;
  108881. }
  108882. case 5123 /* UNSIGNED_SHORT */: {
  108883. factor = 1 / 65535;
  108884. break;
  108885. }
  108886. default: {
  108887. throw new Error(context + ": Invalid component type (" + accessor.componentType + ")");
  108888. }
  108889. }
  108890. }
  108891. var result = new Float32Array(accessor.count * GLTFLoader._GetNumComponents(context, accessor.type));
  108892. for (var i = 0; i < result.length; i++) {
  108893. result[i] = data[i] * factor;
  108894. }
  108895. return result;
  108896. };
  108897. GLTFLoader._ConvertVec3ToVec4 = function (context, data) {
  108898. var result = new Float32Array(data.length / 3 * 4);
  108899. var offset = 0;
  108900. for (var i = 0; i < result.length; i++) {
  108901. if ((i + 1) % 4 === 0) {
  108902. result[i] = 1;
  108903. }
  108904. else {
  108905. result[i] = data[offset++];
  108906. }
  108907. }
  108908. return result;
  108909. };
  108910. GLTFLoader._LoadTransform = function (node, babylonNode) {
  108911. var position = BABYLON.Vector3.Zero();
  108912. var rotation = BABYLON.Quaternion.Identity();
  108913. var scaling = BABYLON.Vector3.One();
  108914. if (node.matrix) {
  108915. var matrix = BABYLON.Matrix.FromArray(node.matrix);
  108916. matrix.decompose(scaling, rotation, position);
  108917. }
  108918. else {
  108919. if (node.translation)
  108920. position = BABYLON.Vector3.FromArray(node.translation);
  108921. if (node.rotation)
  108922. rotation = BABYLON.Quaternion.FromArray(node.rotation);
  108923. if (node.scale)
  108924. scaling = BABYLON.Vector3.FromArray(node.scale);
  108925. }
  108926. babylonNode.position = position;
  108927. babylonNode.rotationQuaternion = rotation;
  108928. babylonNode.scaling = scaling;
  108929. };
  108930. GLTFLoader.prototype._loadSkinAsync = function (context, node, mesh, skin) {
  108931. var _this = this;
  108932. var assignSkeleton = function () {
  108933. _this._forEachNodeMesh(node, function (babylonMesh) {
  108934. babylonMesh.skeleton = skin._babylonSkeleton;
  108935. });
  108936. node._babylonMesh.parent = _this._rootBabylonMesh;
  108937. node._babylonMesh.position = BABYLON.Vector3.Zero();
  108938. node._babylonMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  108939. node._babylonMesh.scaling = BABYLON.Vector3.One();
  108940. };
  108941. if (skin._loaded) {
  108942. return skin._loaded.then(function () {
  108943. assignSkeleton();
  108944. });
  108945. }
  108946. // TODO: split into two parts so that bones are created before inverseBindMatricesData is loaded (for compiling materials).
  108947. return (skin._loaded = this._loadSkinInverseBindMatricesDataAsync(context, skin).then(function (inverseBindMatricesData) {
  108948. var skeletonId = "skeleton" + skin._index;
  108949. var babylonSkeleton = new BABYLON.Skeleton(skin.name || skeletonId, skeletonId, _this._babylonScene);
  108950. skin._babylonSkeleton = babylonSkeleton;
  108951. _this._loadBones(context, skin, inverseBindMatricesData);
  108952. assignSkeleton();
  108953. }));
  108954. };
  108955. GLTFLoader.prototype._loadSkinInverseBindMatricesDataAsync = function (context, skin) {
  108956. if (skin.inverseBindMatrices == undefined) {
  108957. return Promise.resolve(null);
  108958. }
  108959. var accessor = GLTFLoader._GetProperty(context + "/inverseBindMatrices", this._gltf.accessors, skin.inverseBindMatrices);
  108960. return this._loadAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  108961. return data;
  108962. });
  108963. };
  108964. GLTFLoader.prototype._createBone = function (node, skin, parent, localMatrix, baseMatrix, index) {
  108965. var babylonBone = new BABYLON.Bone(node.name || "joint" + node._index, skin._babylonSkeleton, parent, localMatrix, null, baseMatrix, index);
  108966. node._babylonAnimationTargets = node._babylonAnimationTargets || [];
  108967. node._babylonAnimationTargets.push(babylonBone);
  108968. return babylonBone;
  108969. };
  108970. GLTFLoader.prototype._loadBones = function (context, skin, inverseBindMatricesData) {
  108971. var babylonBones = {};
  108972. for (var _i = 0, _a = skin.joints; _i < _a.length; _i++) {
  108973. var index = _a[_i];
  108974. var node = GLTFLoader._GetProperty(context + "/joints/" + index, this._gltf.nodes, index);
  108975. this._loadBone(node, skin, inverseBindMatricesData, babylonBones);
  108976. }
  108977. };
  108978. GLTFLoader.prototype._loadBone = function (node, skin, inverseBindMatricesData, babylonBones) {
  108979. var babylonBone = babylonBones[node._index];
  108980. if (babylonBone) {
  108981. return babylonBone;
  108982. }
  108983. var boneIndex = skin.joints.indexOf(node._index);
  108984. var baseMatrix = BABYLON.Matrix.Identity();
  108985. if (inverseBindMatricesData && boneIndex !== -1) {
  108986. baseMatrix = BABYLON.Matrix.FromArray(inverseBindMatricesData, boneIndex * 16);
  108987. baseMatrix.invertToRef(baseMatrix);
  108988. }
  108989. var babylonParentBone = null;
  108990. if (node._parent._babylonMesh !== this._rootBabylonMesh) {
  108991. babylonParentBone = this._loadBone(node._parent, skin, inverseBindMatricesData, babylonBones);
  108992. baseMatrix.multiplyToRef(babylonParentBone.getInvertedAbsoluteTransform(), baseMatrix);
  108993. }
  108994. babylonBone = this._createBone(node, skin, babylonParentBone, this._getNodeMatrix(node), baseMatrix, boneIndex);
  108995. babylonBones[node._index] = babylonBone;
  108996. return babylonBone;
  108997. };
  108998. GLTFLoader.prototype._getNodeMatrix = function (node) {
  108999. return node.matrix ?
  109000. BABYLON.Matrix.FromArray(node.matrix) :
  109001. BABYLON.Matrix.Compose(node.scale ? BABYLON.Vector3.FromArray(node.scale) : BABYLON.Vector3.One(), node.rotation ? BABYLON.Quaternion.FromArray(node.rotation) : BABYLON.Quaternion.Identity(), node.translation ? BABYLON.Vector3.FromArray(node.translation) : BABYLON.Vector3.Zero());
  109002. };
  109003. GLTFLoader.prototype._loadAnimationsAsync = function () {
  109004. var animations = this._gltf.animations;
  109005. if (!animations) {
  109006. return Promise.resolve();
  109007. }
  109008. var promises = new Array();
  109009. for (var index = 0; index < animations.length; index++) {
  109010. var animation = animations[index];
  109011. promises.push(this._loadAnimationAsync("#/animations/" + index, animation));
  109012. }
  109013. return Promise.all(promises).then(function () { });
  109014. };
  109015. GLTFLoader.prototype._loadAnimationAsync = function (context, animation) {
  109016. var babylonAnimationGroup = new BABYLON.AnimationGroup(animation.name || "animation" + animation._index, this._babylonScene);
  109017. animation._babylonAnimationGroup = babylonAnimationGroup;
  109018. var promises = new Array();
  109019. GLTF2.ArrayItem.Assign(animation.channels);
  109020. GLTF2.ArrayItem.Assign(animation.samplers);
  109021. for (var _i = 0, _a = animation.channels; _i < _a.length; _i++) {
  109022. var channel = _a[_i];
  109023. promises.push(this._loadAnimationChannelAsync(context + "/channels/" + channel._index, context, animation, channel, babylonAnimationGroup));
  109024. }
  109025. this.onAnimationGroupLoadedObservable.notifyObservers(babylonAnimationGroup);
  109026. return Promise.all(promises).then(function () {
  109027. babylonAnimationGroup.normalize();
  109028. });
  109029. };
  109030. GLTFLoader.prototype._loadAnimationChannelAsync = function (context, animationContext, animation, channel, babylonAnimationGroup) {
  109031. var _this = this;
  109032. var targetNode = GLTFLoader._GetProperty(context + "/target/node", this._gltf.nodes, channel.target.node);
  109033. if (!targetNode._babylonMesh || targetNode.skin != undefined) {
  109034. return Promise.resolve();
  109035. }
  109036. var sampler = GLTFLoader._GetProperty(context + "/sampler", animation.samplers, channel.sampler);
  109037. return this._loadAnimationSamplerAsync(animationContext + "/samplers/" + channel.sampler, sampler).then(function (data) {
  109038. var targetPath;
  109039. var animationType;
  109040. switch (channel.target.path) {
  109041. case "translation" /* TRANSLATION */: {
  109042. targetPath = "position";
  109043. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  109044. break;
  109045. }
  109046. case "rotation" /* ROTATION */: {
  109047. targetPath = "rotationQuaternion";
  109048. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  109049. break;
  109050. }
  109051. case "scale" /* SCALE */: {
  109052. targetPath = "scaling";
  109053. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  109054. break;
  109055. }
  109056. case "weights" /* WEIGHTS */: {
  109057. targetPath = "influence";
  109058. animationType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  109059. break;
  109060. }
  109061. default: {
  109062. throw new Error(context + ": Invalid target path (" + channel.target.path + ")");
  109063. }
  109064. }
  109065. var outputBufferOffset = 0;
  109066. var getNextOutputValue;
  109067. switch (targetPath) {
  109068. case "position": {
  109069. getNextOutputValue = function () {
  109070. var value = BABYLON.Vector3.FromArray(data.output, outputBufferOffset);
  109071. outputBufferOffset += 3;
  109072. return value;
  109073. };
  109074. break;
  109075. }
  109076. case "rotationQuaternion": {
  109077. getNextOutputValue = function () {
  109078. var value = BABYLON.Quaternion.FromArray(data.output, outputBufferOffset);
  109079. outputBufferOffset += 4;
  109080. return value;
  109081. };
  109082. break;
  109083. }
  109084. case "scaling": {
  109085. getNextOutputValue = function () {
  109086. var value = BABYLON.Vector3.FromArray(data.output, outputBufferOffset);
  109087. outputBufferOffset += 3;
  109088. return value;
  109089. };
  109090. break;
  109091. }
  109092. case "influence": {
  109093. getNextOutputValue = function () {
  109094. var value = new Array(targetNode._numMorphTargets);
  109095. for (var i = 0; i < targetNode._numMorphTargets; i++) {
  109096. value[i] = data.output[outputBufferOffset++];
  109097. }
  109098. return value;
  109099. };
  109100. break;
  109101. }
  109102. }
  109103. var getNextKey;
  109104. switch (data.interpolation) {
  109105. case "STEP" /* STEP */: {
  109106. getNextKey = function (frameIndex) { return ({
  109107. frame: data.input[frameIndex],
  109108. value: getNextOutputValue(),
  109109. interpolation: BABYLON.AnimationKeyInterpolation.STEP
  109110. }); };
  109111. break;
  109112. }
  109113. case "LINEAR" /* LINEAR */: {
  109114. getNextKey = function (frameIndex) { return ({
  109115. frame: data.input[frameIndex],
  109116. value: getNextOutputValue()
  109117. }); };
  109118. break;
  109119. }
  109120. case "CUBICSPLINE" /* CUBICSPLINE */: {
  109121. getNextKey = function (frameIndex) { return ({
  109122. frame: data.input[frameIndex],
  109123. inTangent: getNextOutputValue(),
  109124. value: getNextOutputValue(),
  109125. outTangent: getNextOutputValue()
  109126. }); };
  109127. break;
  109128. }
  109129. }
  109130. var keys;
  109131. if (data.input.length === 1) {
  109132. var key = getNextKey(0);
  109133. keys = [
  109134. { frame: key.frame, value: key.value },
  109135. { frame: key.frame + 1, value: key.value }
  109136. ];
  109137. }
  109138. else {
  109139. keys = new Array(data.input.length);
  109140. for (var frameIndex = 0; frameIndex < data.input.length; frameIndex++) {
  109141. keys[frameIndex] = getNextKey(frameIndex);
  109142. }
  109143. }
  109144. if (targetPath === "influence") {
  109145. var _loop_1 = function (targetIndex) {
  109146. var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
  109147. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  109148. babylonAnimation.setKeys(keys.map(function (key) { return ({
  109149. frame: key.frame,
  109150. inTangent: key.inTangent ? key.inTangent[targetIndex] : undefined,
  109151. value: key.value[targetIndex],
  109152. outTangent: key.outTangent ? key.outTangent[targetIndex] : undefined
  109153. }); }));
  109154. _this._forEachNodeMesh(targetNode, function (babylonMesh) {
  109155. var morphTarget = babylonMesh.morphTargetManager.getTarget(targetIndex);
  109156. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, morphTarget);
  109157. });
  109158. };
  109159. for (var targetIndex = 0; targetIndex < targetNode._numMorphTargets; targetIndex++) {
  109160. _loop_1(targetIndex);
  109161. }
  109162. }
  109163. else {
  109164. var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
  109165. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  109166. babylonAnimation.setKeys(keys);
  109167. if (targetNode._babylonAnimationTargets) {
  109168. for (var _i = 0, _a = targetNode._babylonAnimationTargets; _i < _a.length; _i++) {
  109169. var target = _a[_i];
  109170. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, target);
  109171. }
  109172. }
  109173. }
  109174. });
  109175. };
  109176. GLTFLoader.prototype._loadAnimationSamplerAsync = function (context, sampler) {
  109177. if (sampler._data) {
  109178. return sampler._data;
  109179. }
  109180. var interpolation = sampler.interpolation || "LINEAR" /* LINEAR */;
  109181. switch (interpolation) {
  109182. case "STEP" /* STEP */:
  109183. case "LINEAR" /* LINEAR */:
  109184. case "CUBICSPLINE" /* CUBICSPLINE */: {
  109185. break;
  109186. }
  109187. default: {
  109188. throw new Error(context + ": Invalid interpolation (" + sampler.interpolation + ")");
  109189. }
  109190. }
  109191. var inputData;
  109192. var outputData;
  109193. var inputAccessor = GLTFLoader._GetProperty(context + "/input", this._gltf.accessors, sampler.input);
  109194. var outputAccessor = GLTFLoader._GetProperty(context + "/output", this._gltf.accessors, sampler.output);
  109195. sampler._data = Promise.all([
  109196. this._loadAccessorAsync("#/accessors/" + inputAccessor._index, inputAccessor).then(function (data) {
  109197. inputData = data;
  109198. }),
  109199. this._loadAccessorAsync("#/accessors/" + outputAccessor._index, outputAccessor).then(function (data) {
  109200. outputData = data;
  109201. })
  109202. ]).then(function () {
  109203. return {
  109204. input: inputData,
  109205. interpolation: interpolation,
  109206. output: outputData,
  109207. };
  109208. });
  109209. return sampler._data;
  109210. };
  109211. GLTFLoader.prototype._loadBufferAsync = function (context, buffer) {
  109212. if (buffer._data) {
  109213. return buffer._data;
  109214. }
  109215. if (!buffer.uri) {
  109216. throw new Error(context + ": Uri is missing");
  109217. }
  109218. buffer._data = this._loadUriAsync(context, buffer.uri);
  109219. return buffer._data;
  109220. };
  109221. GLTFLoader.prototype._loadBufferViewAsync = function (context, bufferView) {
  109222. if (bufferView._data) {
  109223. return bufferView._data;
  109224. }
  109225. var buffer = GLTFLoader._GetProperty(context + "/buffer", this._gltf.buffers, bufferView.buffer);
  109226. bufferView._data = this._loadBufferAsync("#/buffers/" + buffer._index, buffer).then(function (bufferData) {
  109227. try {
  109228. return new Uint8Array(bufferData.buffer, bufferData.byteOffset + (bufferView.byteOffset || 0), bufferView.byteLength);
  109229. }
  109230. catch (e) {
  109231. throw new Error(context + ": " + e.message);
  109232. }
  109233. });
  109234. return bufferView._data;
  109235. };
  109236. GLTFLoader.prototype._loadAccessorAsync = function (context, accessor) {
  109237. var _this = this;
  109238. if (accessor.sparse) {
  109239. throw new Error(context + ": Sparse accessors are not currently supported");
  109240. }
  109241. if (accessor._data) {
  109242. return accessor._data;
  109243. }
  109244. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, accessor.bufferView);
  109245. accessor._data = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView).then(function (bufferViewData) {
  109246. var numComponents = GLTFLoader._GetNumComponents(context, accessor.type);
  109247. var byteOffset = accessor.byteOffset || 0;
  109248. var byteStride = bufferView.byteStride;
  109249. if (byteStride === 0) {
  109250. BABYLON.Tools.Warn(context + ": Byte stride of 0 is not valid");
  109251. }
  109252. try {
  109253. switch (accessor.componentType) {
  109254. case 5120 /* BYTE */: {
  109255. return _this._buildArrayBuffer(Float32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  109256. }
  109257. case 5121 /* UNSIGNED_BYTE */: {
  109258. return _this._buildArrayBuffer(Uint8Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  109259. }
  109260. case 5122 /* SHORT */: {
  109261. return _this._buildArrayBuffer(Int16Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  109262. }
  109263. case 5123 /* UNSIGNED_SHORT */: {
  109264. return _this._buildArrayBuffer(Uint16Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  109265. }
  109266. case 5125 /* UNSIGNED_INT */: {
  109267. return _this._buildArrayBuffer(Uint32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  109268. }
  109269. case 5126 /* FLOAT */: {
  109270. return _this._buildArrayBuffer(Float32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  109271. }
  109272. default: {
  109273. throw new Error(context + ": Invalid component type (" + accessor.componentType + ")");
  109274. }
  109275. }
  109276. }
  109277. catch (e) {
  109278. throw new Error(context + ": " + e.messsage);
  109279. }
  109280. });
  109281. return accessor._data;
  109282. };
  109283. GLTFLoader.prototype._buildArrayBuffer = function (typedArray, data, byteOffset, count, numComponents, byteStride) {
  109284. byteOffset += data.byteOffset;
  109285. var targetLength = count * numComponents;
  109286. if (!byteStride || byteStride === numComponents * typedArray.BYTES_PER_ELEMENT) {
  109287. return new typedArray(data.buffer, byteOffset, targetLength);
  109288. }
  109289. var elementStride = byteStride / typedArray.BYTES_PER_ELEMENT;
  109290. var sourceBuffer = new typedArray(data.buffer, byteOffset, elementStride * count);
  109291. var targetBuffer = new typedArray(targetLength);
  109292. var sourceIndex = 0;
  109293. var targetIndex = 0;
  109294. while (targetIndex < targetLength) {
  109295. for (var componentIndex = 0; componentIndex < numComponents; componentIndex++) {
  109296. targetBuffer[targetIndex] = sourceBuffer[sourceIndex + componentIndex];
  109297. targetIndex++;
  109298. }
  109299. sourceIndex += elementStride;
  109300. }
  109301. return targetBuffer;
  109302. };
  109303. GLTFLoader.prototype._getDefaultMaterial = function () {
  109304. var id = "__gltf_default";
  109305. var babylonMaterial = this._babylonScene.getMaterialByName(id);
  109306. if (!babylonMaterial) {
  109307. babylonMaterial = new BABYLON.PBRMaterial(id, this._babylonScene);
  109308. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  109309. babylonMaterial.sideOrientation = this._babylonScene.useRightHandedSystem ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation;
  109310. babylonMaterial.metallic = 1;
  109311. babylonMaterial.roughness = 1;
  109312. this.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  109313. }
  109314. return babylonMaterial;
  109315. };
  109316. GLTFLoader.prototype._loadMaterialMetallicRoughnessPropertiesAsync = function (context, material) {
  109317. var promises = new Array();
  109318. var babylonMaterial = material._babylonMaterial;
  109319. // Ensure metallic workflow
  109320. babylonMaterial.metallic = 1;
  109321. babylonMaterial.roughness = 1;
  109322. var properties = material.pbrMetallicRoughness;
  109323. if (properties) {
  109324. if (properties.baseColorFactor) {
  109325. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.baseColorFactor);
  109326. babylonMaterial.alpha = properties.baseColorFactor[3];
  109327. }
  109328. else {
  109329. babylonMaterial.albedoColor = BABYLON.Color3.White();
  109330. }
  109331. babylonMaterial.metallic = properties.metallicFactor == undefined ? 1 : properties.metallicFactor;
  109332. babylonMaterial.roughness = properties.roughnessFactor == undefined ? 1 : properties.roughnessFactor;
  109333. if (properties.baseColorTexture) {
  109334. promises.push(this._loadTextureAsync(context + "/baseColorTexture", properties.baseColorTexture, function (texture) {
  109335. babylonMaterial.albedoTexture = texture;
  109336. }));
  109337. }
  109338. if (properties.metallicRoughnessTexture) {
  109339. promises.push(this._loadTextureAsync(context + "/metallicRoughnessTexture", properties.metallicRoughnessTexture, function (texture) {
  109340. babylonMaterial.metallicTexture = texture;
  109341. }));
  109342. babylonMaterial.useMetallnessFromMetallicTextureBlue = true;
  109343. babylonMaterial.useRoughnessFromMetallicTextureGreen = true;
  109344. babylonMaterial.useRoughnessFromMetallicTextureAlpha = false;
  109345. }
  109346. }
  109347. this._loadMaterialAlphaProperties(context, material);
  109348. return Promise.all(promises).then(function () { });
  109349. };
  109350. GLTFLoader.prototype._loadMaterialAsync = function (context, material, babylonMesh, assign) {
  109351. var promise = GLTF2.GLTFLoaderExtension._LoadMaterialAsync(this, context, material, babylonMesh, assign);
  109352. if (promise) {
  109353. return promise;
  109354. }
  109355. material._babylonMeshes = material._babylonMeshes || [];
  109356. material._babylonMeshes.push(babylonMesh);
  109357. if (!material._loaded) {
  109358. var promises = new Array();
  109359. var babylonMaterial = this._createMaterial(material);
  109360. material._babylonMaterial = babylonMaterial;
  109361. promises.push(this._loadMaterialBasePropertiesAsync(context, material));
  109362. promises.push(this._loadMaterialMetallicRoughnessPropertiesAsync(context, material));
  109363. this.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  109364. material._loaded = Promise.all(promises).then(function () { });
  109365. }
  109366. assign(material._babylonMaterial);
  109367. return material._loaded;
  109368. };
  109369. GLTFLoader.prototype._createMaterial = function (material) {
  109370. var babylonMaterial = new BABYLON.PBRMaterial(material.name || "material" + material._index, this._babylonScene);
  109371. babylonMaterial.sideOrientation = this._babylonScene.useRightHandedSystem ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation;
  109372. return babylonMaterial;
  109373. };
  109374. GLTFLoader.prototype._loadMaterialBasePropertiesAsync = function (context, material) {
  109375. var promises = new Array();
  109376. var babylonMaterial = material._babylonMaterial;
  109377. babylonMaterial.emissiveColor = material.emissiveFactor ? BABYLON.Color3.FromArray(material.emissiveFactor) : new BABYLON.Color3(0, 0, 0);
  109378. if (material.doubleSided) {
  109379. babylonMaterial.backFaceCulling = false;
  109380. babylonMaterial.twoSidedLighting = true;
  109381. }
  109382. if (material.normalTexture) {
  109383. promises.push(this._loadTextureAsync(context + "/normalTexture", material.normalTexture, function (texture) {
  109384. babylonMaterial.bumpTexture = texture;
  109385. }));
  109386. babylonMaterial.invertNormalMapX = !this._babylonScene.useRightHandedSystem;
  109387. babylonMaterial.invertNormalMapY = this._babylonScene.useRightHandedSystem;
  109388. if (material.normalTexture.scale != undefined) {
  109389. babylonMaterial.bumpTexture.level = material.normalTexture.scale;
  109390. }
  109391. }
  109392. if (material.occlusionTexture) {
  109393. promises.push(this._loadTextureAsync(context + "/occlusionTexture", material.occlusionTexture, function (texture) {
  109394. babylonMaterial.ambientTexture = texture;
  109395. }));
  109396. babylonMaterial.useAmbientInGrayScale = true;
  109397. if (material.occlusionTexture.strength != undefined) {
  109398. babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength;
  109399. }
  109400. }
  109401. if (material.emissiveTexture) {
  109402. promises.push(this._loadTextureAsync(context + "/emissiveTexture", material.emissiveTexture, function (texture) {
  109403. babylonMaterial.emissiveTexture = texture;
  109404. }));
  109405. }
  109406. return Promise.all(promises).then(function () { });
  109407. };
  109408. GLTFLoader.prototype._loadMaterialAlphaProperties = function (context, material) {
  109409. var babylonMaterial = material._babylonMaterial;
  109410. var alphaMode = material.alphaMode || "OPAQUE" /* OPAQUE */;
  109411. switch (alphaMode) {
  109412. case "OPAQUE" /* OPAQUE */: {
  109413. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  109414. break;
  109415. }
  109416. case "MASK" /* MASK */: {
  109417. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST;
  109418. babylonMaterial.alphaCutOff = (material.alphaCutoff == undefined ? 0.5 : material.alphaCutoff);
  109419. if (babylonMaterial.alpha) {
  109420. if (babylonMaterial.alpha === 0) {
  109421. babylonMaterial.alphaCutOff = 1;
  109422. }
  109423. else {
  109424. babylonMaterial.alphaCutOff /= babylonMaterial.alpha;
  109425. }
  109426. babylonMaterial.alpha = 1;
  109427. }
  109428. if (babylonMaterial.albedoTexture) {
  109429. babylonMaterial.albedoTexture.hasAlpha = true;
  109430. }
  109431. break;
  109432. }
  109433. case "BLEND" /* BLEND */: {
  109434. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND;
  109435. if (babylonMaterial.albedoTexture) {
  109436. babylonMaterial.albedoTexture.hasAlpha = true;
  109437. babylonMaterial.useAlphaFromAlbedoTexture = true;
  109438. }
  109439. break;
  109440. }
  109441. default: {
  109442. throw new Error(context + ": Invalid alpha mode (" + material.alphaMode + ")");
  109443. }
  109444. }
  109445. };
  109446. GLTFLoader.prototype._loadTextureAsync = function (context, textureInfo, assign) {
  109447. var _this = this;
  109448. var texture = GLTFLoader._GetProperty(context + "/index", this._gltf.textures, textureInfo.index);
  109449. context = "#/textures/" + textureInfo.index;
  109450. var promises = new Array();
  109451. var sampler = (texture.sampler == undefined ? this._defaultSampler : GLTFLoader._GetProperty(context + "/sampler", this._gltf.samplers, texture.sampler));
  109452. var samplerData = this._loadSampler("#/samplers/" + sampler._index, sampler);
  109453. var deferred = new BABYLON.Deferred();
  109454. var babylonTexture = new BABYLON.Texture(null, this._babylonScene, samplerData.noMipMaps, false, samplerData.samplingMode, function () {
  109455. if (!_this._disposed) {
  109456. deferred.resolve();
  109457. }
  109458. }, function (message, exception) {
  109459. if (!_this._disposed) {
  109460. deferred.reject(new Error(context + ": " + ((exception && exception.message) ? exception.message : message || "Failed to load texture")));
  109461. }
  109462. });
  109463. promises.push(deferred.promise);
  109464. babylonTexture.name = texture.name || "texture" + texture._index;
  109465. babylonTexture.wrapU = samplerData.wrapU;
  109466. babylonTexture.wrapV = samplerData.wrapV;
  109467. babylonTexture.coordinatesIndex = textureInfo.texCoord || 0;
  109468. var image = GLTFLoader._GetProperty(context + "/source", this._gltf.images, texture.source);
  109469. promises.push(this._loadImageAsync("#/images/" + image._index, image).then(function (objectURL) {
  109470. babylonTexture.updateURL(objectURL);
  109471. }));
  109472. assign(babylonTexture);
  109473. this.onTextureLoadedObservable.notifyObservers(babylonTexture);
  109474. return Promise.all(promises).then(function () { });
  109475. };
  109476. GLTFLoader.prototype._loadSampler = function (context, sampler) {
  109477. if (!sampler._data) {
  109478. sampler._data = {
  109479. noMipMaps: (sampler.minFilter === 9728 /* NEAREST */ || sampler.minFilter === 9729 /* LINEAR */),
  109480. samplingMode: GLTFLoader._GetTextureSamplingMode(context, sampler.magFilter, sampler.minFilter),
  109481. wrapU: GLTFLoader._GetTextureWrapMode(context, sampler.wrapS),
  109482. wrapV: GLTFLoader._GetTextureWrapMode(context, sampler.wrapT)
  109483. };
  109484. }
  109485. ;
  109486. return sampler._data;
  109487. };
  109488. GLTFLoader.prototype._loadImageAsync = function (context, image) {
  109489. if (image._objectURL) {
  109490. return image._objectURL;
  109491. }
  109492. var promise;
  109493. if (image.uri) {
  109494. promise = this._loadUriAsync(context, image.uri);
  109495. }
  109496. else {
  109497. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, image.bufferView);
  109498. promise = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView);
  109499. }
  109500. image._objectURL = promise.then(function (data) {
  109501. return URL.createObjectURL(new Blob([data], { type: image.mimeType }));
  109502. });
  109503. return image._objectURL;
  109504. };
  109505. GLTFLoader.prototype._loadUriAsync = function (context, uri) {
  109506. var _this = this;
  109507. var promise = GLTF2.GLTFLoaderExtension._LoadUriAsync(this, context, uri);
  109508. if (promise) {
  109509. return promise;
  109510. }
  109511. if (!GLTFLoader._ValidateUri(uri)) {
  109512. throw new Error(context + ": Uri '" + uri + "' is invalid");
  109513. }
  109514. if (BABYLON.Tools.IsBase64(uri)) {
  109515. return Promise.resolve(new Uint8Array(BABYLON.Tools.DecodeBase64(uri)));
  109516. }
  109517. return new Promise(function (resolve, reject) {
  109518. var request = BABYLON.Tools.LoadFile(_this._rootUrl + uri, function (data) {
  109519. if (!_this._disposed) {
  109520. resolve(new Uint8Array(data));
  109521. }
  109522. }, function (event) {
  109523. if (!_this._disposed) {
  109524. try {
  109525. if (request && _this._state === BABYLON.GLTFLoaderState.Loading) {
  109526. request._lengthComputable = event.lengthComputable;
  109527. request._loaded = event.loaded;
  109528. request._total = event.total;
  109529. _this._onProgress();
  109530. }
  109531. }
  109532. catch (e) {
  109533. reject(e);
  109534. }
  109535. }
  109536. }, _this._babylonScene.database, true, function (request, exception) {
  109537. if (!_this._disposed) {
  109538. reject(new BABYLON.LoadFileError(context + ": Failed to load '" + uri + "'" + (request ? ": " + request.status + " " + request.statusText : ""), request));
  109539. }
  109540. });
  109541. _this._requests.push(request);
  109542. });
  109543. };
  109544. GLTFLoader.prototype._onProgress = function () {
  109545. if (!this._progressCallback) {
  109546. return;
  109547. }
  109548. var lengthComputable = true;
  109549. var loaded = 0;
  109550. var total = 0;
  109551. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  109552. var request = _a[_i];
  109553. if (request._lengthComputable === undefined || request._loaded === undefined || request._total === undefined) {
  109554. return;
  109555. }
  109556. lengthComputable = lengthComputable && request._lengthComputable;
  109557. loaded += request._loaded;
  109558. total += request._total;
  109559. }
  109560. this._progressCallback(new BABYLON.SceneLoaderProgressEvent(lengthComputable, loaded, lengthComputable ? total : 0));
  109561. };
  109562. GLTFLoader._GetProperty = function (context, array, index) {
  109563. if (!array || index == undefined || !array[index]) {
  109564. throw new Error(context + ": Failed to find index (" + index + ")");
  109565. }
  109566. return array[index];
  109567. };
  109568. GLTFLoader._GetTextureWrapMode = function (context, mode) {
  109569. // Set defaults if undefined
  109570. mode = mode == undefined ? 10497 /* REPEAT */ : mode;
  109571. switch (mode) {
  109572. case 33071 /* CLAMP_TO_EDGE */: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  109573. case 33648 /* MIRRORED_REPEAT */: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  109574. case 10497 /* REPEAT */: return BABYLON.Texture.WRAP_ADDRESSMODE;
  109575. default:
  109576. BABYLON.Tools.Warn(context + ": Invalid texture wrap mode (" + mode + ")");
  109577. return BABYLON.Texture.WRAP_ADDRESSMODE;
  109578. }
  109579. };
  109580. GLTFLoader._GetTextureSamplingMode = function (context, magFilter, minFilter) {
  109581. // Set defaults if undefined
  109582. magFilter = magFilter == undefined ? 9729 /* LINEAR */ : magFilter;
  109583. minFilter = minFilter == undefined ? 9987 /* LINEAR_MIPMAP_LINEAR */ : minFilter;
  109584. if (magFilter === 9729 /* LINEAR */) {
  109585. switch (minFilter) {
  109586. case 9728 /* NEAREST */: return BABYLON.Texture.LINEAR_NEAREST;
  109587. case 9729 /* LINEAR */: return BABYLON.Texture.LINEAR_LINEAR;
  109588. case 9984 /* NEAREST_MIPMAP_NEAREST */: return BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST;
  109589. case 9985 /* LINEAR_MIPMAP_NEAREST */: return BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST;
  109590. case 9986 /* NEAREST_MIPMAP_LINEAR */: return BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR;
  109591. case 9987 /* LINEAR_MIPMAP_LINEAR */: return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  109592. default:
  109593. BABYLON.Tools.Warn(context + ": Invalid texture minification filter (" + minFilter + ")");
  109594. return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  109595. }
  109596. }
  109597. else {
  109598. if (magFilter !== 9728 /* NEAREST */) {
  109599. BABYLON.Tools.Warn(context + ": Invalid texture magnification filter (" + magFilter + ")");
  109600. }
  109601. switch (minFilter) {
  109602. case 9728 /* NEAREST */: return BABYLON.Texture.NEAREST_NEAREST;
  109603. case 9729 /* LINEAR */: return BABYLON.Texture.NEAREST_LINEAR;
  109604. case 9984 /* NEAREST_MIPMAP_NEAREST */: return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  109605. case 9985 /* LINEAR_MIPMAP_NEAREST */: return BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST;
  109606. case 9986 /* NEAREST_MIPMAP_LINEAR */: return BABYLON.Texture.NEAREST_NEAREST_MIPLINEAR;
  109607. case 9987 /* LINEAR_MIPMAP_LINEAR */: return BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR;
  109608. default:
  109609. BABYLON.Tools.Warn(context + ": Invalid texture minification filter (" + minFilter + ")");
  109610. return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  109611. }
  109612. }
  109613. };
  109614. GLTFLoader._GetNumComponents = function (context, type) {
  109615. switch (type) {
  109616. case "SCALAR": return 1;
  109617. case "VEC2": return 2;
  109618. case "VEC3": return 3;
  109619. case "VEC4": return 4;
  109620. case "MAT2": return 4;
  109621. case "MAT3": return 9;
  109622. case "MAT4": return 16;
  109623. }
  109624. throw new Error(context + ": Invalid type (" + type + ")");
  109625. };
  109626. GLTFLoader._ValidateUri = function (uri) {
  109627. return (BABYLON.Tools.IsBase64(uri) || uri.indexOf("..") === -1);
  109628. };
  109629. GLTFLoader.prototype._compileMaterialsAsync = function () {
  109630. var promises = new Array();
  109631. if (this._gltf.materials) {
  109632. for (var _i = 0, _a = this._gltf.materials; _i < _a.length; _i++) {
  109633. var material = _a[_i];
  109634. var babylonMaterial = material._babylonMaterial;
  109635. var babylonMeshes = material._babylonMeshes;
  109636. if (babylonMaterial && babylonMeshes) {
  109637. for (var _b = 0, babylonMeshes_1 = babylonMeshes; _b < babylonMeshes_1.length; _b++) {
  109638. var babylonMesh = babylonMeshes_1[_b];
  109639. // Ensure nonUniformScaling is set if necessary.
  109640. babylonMesh.computeWorldMatrix(true);
  109641. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh));
  109642. if (this.useClipPlane) {
  109643. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh, { clipPlane: true }));
  109644. }
  109645. }
  109646. }
  109647. }
  109648. }
  109649. return Promise.all(promises).then(function () { });
  109650. };
  109651. GLTFLoader.prototype._compileShadowGeneratorsAsync = function () {
  109652. var promises = new Array();
  109653. var lights = this._babylonScene.lights;
  109654. for (var _i = 0, lights_1 = lights; _i < lights_1.length; _i++) {
  109655. var light = lights_1[_i];
  109656. var generator = light.getShadowGenerator();
  109657. if (generator) {
  109658. promises.push(generator.forceCompilationAsync());
  109659. }
  109660. }
  109661. return Promise.all(promises).then(function () { });
  109662. };
  109663. GLTFLoader.prototype._clear = function () {
  109664. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  109665. var request = _a[_i];
  109666. request.abort();
  109667. }
  109668. this._requests.length = 0;
  109669. if (this._gltf && this._gltf.images) {
  109670. for (var _b = 0, _c = this._gltf.images; _b < _c.length; _b++) {
  109671. var image = _c[_b];
  109672. if (image._objectURL) {
  109673. image._objectURL.then(function (value) {
  109674. URL.revokeObjectURL(value);
  109675. });
  109676. image._objectURL = undefined;
  109677. }
  109678. }
  109679. }
  109680. delete this._gltf;
  109681. delete this._babylonScene;
  109682. this._completePromises.length = 0;
  109683. for (var name_3 in this._extensions) {
  109684. this._extensions[name_3].dispose();
  109685. }
  109686. this._extensions = {};
  109687. delete this._rootBabylonMesh;
  109688. delete this._progressCallback;
  109689. this.onMeshLoadedObservable.clear();
  109690. this.onTextureLoadedObservable.clear();
  109691. this.onMaterialLoadedObservable.clear();
  109692. };
  109693. GLTFLoader.prototype._applyExtensions = function (actionAsync) {
  109694. for (var _i = 0, _a = GLTFLoader._Names; _i < _a.length; _i++) {
  109695. var name_4 = _a[_i];
  109696. var extension = this._extensions[name_4];
  109697. if (extension.enabled) {
  109698. var promise = actionAsync(extension);
  109699. if (promise) {
  109700. return promise;
  109701. }
  109702. }
  109703. }
  109704. return null;
  109705. };
  109706. GLTFLoader._Names = new Array();
  109707. GLTFLoader._Factories = {};
  109708. return GLTFLoader;
  109709. }());
  109710. GLTF2.GLTFLoader = GLTFLoader;
  109711. BABYLON.GLTFFileLoader.CreateGLTFLoaderV2 = function () { return new GLTFLoader(); };
  109712. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  109713. })(BABYLON || (BABYLON = {}));
  109714. //# sourceMappingURL=babylon.glTFLoader.js.map
  109715. var BABYLON;
  109716. (function (BABYLON) {
  109717. var GLTF2;
  109718. (function (GLTF2) {
  109719. var GLTFLoaderExtension = /** @class */ (function () {
  109720. function GLTFLoaderExtension(loader) {
  109721. this.enabled = true;
  109722. this._loader = loader;
  109723. }
  109724. GLTFLoaderExtension.prototype.dispose = function () {
  109725. delete this._loader;
  109726. };
  109727. // #region Overridable Methods
  109728. /** Override this method to modify the default behavior for loading scenes. */
  109729. GLTFLoaderExtension.prototype._loadSceneAsync = function (context, node) { return null; };
  109730. /** Override this method to modify the default behavior for loading nodes. */
  109731. GLTFLoaderExtension.prototype._loadNodeAsync = function (context, node) { return null; };
  109732. /** Override this method to modify the default behavior for loading mesh primitive vertex data. */
  109733. GLTFLoaderExtension.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) { return null; };
  109734. /** Override this method to modify the default behavior for loading materials. */
  109735. GLTFLoaderExtension.prototype._loadMaterialAsync = function (context, material, babylonMesh, assign) { return null; };
  109736. /** Override this method to modify the default behavior for loading uris. */
  109737. GLTFLoaderExtension.prototype._loadUriAsync = function (context, uri) { return null; };
  109738. // #endregion
  109739. /** Helper method called by a loader extension to load an glTF extension. */
  109740. GLTFLoaderExtension.prototype._loadExtensionAsync = function (context, property, actionAsync) {
  109741. if (!property.extensions) {
  109742. return null;
  109743. }
  109744. var extensions = property.extensions;
  109745. var extension = extensions[this.name];
  109746. if (!extension) {
  109747. return null;
  109748. }
  109749. // Clear out the extension before executing the action to avoid recursing into the same property.
  109750. delete extensions[this.name];
  109751. try {
  109752. return actionAsync(context + "/extensions/" + this.name, extension);
  109753. }
  109754. finally {
  109755. // Restore the extension after executing the action.
  109756. extensions[this.name] = extension;
  109757. }
  109758. };
  109759. /** Helper method called by the loader to allow extensions to override loading scenes. */
  109760. GLTFLoaderExtension._LoadSceneAsync = function (loader, context, scene) {
  109761. return loader._applyExtensions(function (extension) { return extension._loadSceneAsync(context, scene); });
  109762. };
  109763. /** Helper method called by the loader to allow extensions to override loading nodes. */
  109764. GLTFLoaderExtension._LoadNodeAsync = function (loader, context, node) {
  109765. return loader._applyExtensions(function (extension) { return extension._loadNodeAsync(context, node); });
  109766. };
  109767. /** Helper method called by the loader to allow extensions to override loading mesh primitive vertex data. */
  109768. GLTFLoaderExtension._LoadVertexDataAsync = function (loader, context, primitive, babylonMesh) {
  109769. return loader._applyExtensions(function (extension) { return extension._loadVertexDataAsync(context, primitive, babylonMesh); });
  109770. };
  109771. /** Helper method called by the loader to allow extensions to override loading materials. */
  109772. GLTFLoaderExtension._LoadMaterialAsync = function (loader, context, material, babylonMesh, assign) {
  109773. return loader._applyExtensions(function (extension) { return extension._loadMaterialAsync(context, material, babylonMesh, assign); });
  109774. };
  109775. /** Helper method called by the loader to allow extensions to override loading uris. */
  109776. GLTFLoaderExtension._LoadUriAsync = function (loader, context, uri) {
  109777. return loader._applyExtensions(function (extension) { return extension._loadUriAsync(context, uri); });
  109778. };
  109779. return GLTFLoaderExtension;
  109780. }());
  109781. GLTF2.GLTFLoaderExtension = GLTFLoaderExtension;
  109782. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  109783. })(BABYLON || (BABYLON = {}));
  109784. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  109785. var BABYLON;
  109786. (function (BABYLON) {
  109787. var GLTF2;
  109788. (function (GLTF2) {
  109789. var Extensions;
  109790. (function (Extensions) {
  109791. // https://github.com/sbtron/glTF/tree/MSFT_lod/extensions/Vendor/MSFT_lod
  109792. var NAME = "MSFT_lod";
  109793. var MSFT_lod = /** @class */ (function (_super) {
  109794. __extends(MSFT_lod, _super);
  109795. function MSFT_lod() {
  109796. var _this = _super !== null && _super.apply(this, arguments) || this;
  109797. _this.name = NAME;
  109798. /**
  109799. * Maximum number of LODs to load, starting from the lowest LOD.
  109800. */
  109801. _this.maxLODsToLoad = Number.MAX_VALUE;
  109802. _this._loadingNodeLOD = null;
  109803. _this._loadNodeSignals = {};
  109804. _this._loadingMaterialLOD = null;
  109805. _this._loadMaterialSignals = {};
  109806. return _this;
  109807. }
  109808. MSFT_lod.prototype._loadNodeAsync = function (context, node) {
  109809. var _this = this;
  109810. return this._loadExtensionAsync(context, node, function (context, extension) {
  109811. var firstPromise;
  109812. var nodeLODs = _this._getLODs(context, node, _this._loader._gltf.nodes, extension.ids);
  109813. var _loop_1 = function (indexLOD) {
  109814. var nodeLOD = nodeLODs[indexLOD];
  109815. if (indexLOD !== 0) {
  109816. _this._loadingNodeLOD = nodeLOD;
  109817. if (!_this._loadNodeSignals[nodeLOD._index]) {
  109818. _this._loadNodeSignals[nodeLOD._index] = new BABYLON.Deferred();
  109819. }
  109820. }
  109821. var promise = _this._loader._loadNodeAsync("#/nodes/" + nodeLOD._index, nodeLOD).then(function () {
  109822. if (indexLOD !== 0) {
  109823. var previousNodeLOD = nodeLODs[indexLOD - 1];
  109824. if (previousNodeLOD._babylonMesh) {
  109825. previousNodeLOD._babylonMesh.dispose();
  109826. delete previousNodeLOD._babylonMesh;
  109827. }
  109828. }
  109829. if (indexLOD !== nodeLODs.length - 1) {
  109830. var nodeIndex = nodeLODs[indexLOD + 1]._index;
  109831. if (_this._loadNodeSignals[nodeIndex]) {
  109832. _this._loadNodeSignals[nodeIndex].resolve();
  109833. delete _this._loadNodeSignals[nodeIndex];
  109834. }
  109835. }
  109836. });
  109837. if (indexLOD === 0) {
  109838. firstPromise = promise;
  109839. }
  109840. else {
  109841. _this._loader._completePromises.push(promise);
  109842. _this._loadingNodeLOD = null;
  109843. }
  109844. };
  109845. for (var indexLOD = 0; indexLOD < nodeLODs.length; indexLOD++) {
  109846. _loop_1(indexLOD);
  109847. }
  109848. return firstPromise;
  109849. });
  109850. };
  109851. MSFT_lod.prototype._loadMaterialAsync = function (context, material, babylonMesh, assign) {
  109852. var _this = this;
  109853. // Don't load material LODs if already loading a node LOD.
  109854. if (this._loadingNodeLOD) {
  109855. return null;
  109856. }
  109857. return this._loadExtensionAsync(context, material, function (context, extension) {
  109858. var firstPromise;
  109859. var materialLODs = _this._getLODs(context, material, _this._loader._gltf.materials, extension.ids);
  109860. var _loop_2 = function (indexLOD) {
  109861. var materialLOD = materialLODs[indexLOD];
  109862. if (indexLOD !== 0) {
  109863. _this._loadingMaterialLOD = materialLOD;
  109864. if (!_this._loadMaterialSignals[materialLOD._index]) {
  109865. _this._loadMaterialSignals[materialLOD._index] = new BABYLON.Deferred();
  109866. }
  109867. }
  109868. var promise = _this._loader._loadMaterialAsync("#/materials/" + materialLOD._index, materialLOD, babylonMesh, indexLOD === 0 ? assign : function () { }).then(function () {
  109869. if (indexLOD !== 0) {
  109870. assign(materialLOD._babylonMaterial);
  109871. var previousMaterialLOD = materialLODs[indexLOD - 1];
  109872. if (previousMaterialLOD._babylonMaterial) {
  109873. previousMaterialLOD._babylonMaterial.dispose();
  109874. delete previousMaterialLOD._babylonMaterial;
  109875. }
  109876. }
  109877. if (indexLOD !== materialLODs.length - 1) {
  109878. var materialIndex = materialLODs[indexLOD + 1]._index;
  109879. if (_this._loadMaterialSignals[materialIndex]) {
  109880. _this._loadMaterialSignals[materialIndex].resolve();
  109881. delete _this._loadMaterialSignals[materialIndex];
  109882. }
  109883. }
  109884. });
  109885. if (indexLOD === 0) {
  109886. firstPromise = promise;
  109887. }
  109888. else {
  109889. _this._loader._completePromises.push(promise);
  109890. _this._loadingMaterialLOD = null;
  109891. }
  109892. };
  109893. for (var indexLOD = 0; indexLOD < materialLODs.length; indexLOD++) {
  109894. _loop_2(indexLOD);
  109895. }
  109896. return firstPromise;
  109897. });
  109898. };
  109899. MSFT_lod.prototype._loadUriAsync = function (context, uri) {
  109900. var _this = this;
  109901. // Defer the loading of uris if loading a material or node LOD.
  109902. if (this._loadingMaterialLOD) {
  109903. var index = this._loadingMaterialLOD._index;
  109904. return this._loadMaterialSignals[index].promise.then(function () {
  109905. return _this._loader._loadUriAsync(context, uri);
  109906. });
  109907. }
  109908. else if (this._loadingNodeLOD) {
  109909. var index = this._loadingNodeLOD._index;
  109910. return this._loadNodeSignals[index].promise.then(function () {
  109911. return _this._loader._loadUriAsync(context, uri);
  109912. });
  109913. }
  109914. return null;
  109915. };
  109916. /**
  109917. * Gets an array of LOD properties from lowest to highest.
  109918. */
  109919. MSFT_lod.prototype._getLODs = function (context, property, array, ids) {
  109920. if (this.maxLODsToLoad <= 0) {
  109921. throw new Error("maxLODsToLoad must be greater than zero");
  109922. }
  109923. var properties = new Array();
  109924. for (var i = ids.length - 1; i >= 0; i--) {
  109925. properties.push(GLTF2.GLTFLoader._GetProperty(context + "/ids/" + ids[i], array, ids[i]));
  109926. if (properties.length === this.maxLODsToLoad) {
  109927. return properties;
  109928. }
  109929. }
  109930. properties.push(property);
  109931. return properties;
  109932. };
  109933. return MSFT_lod;
  109934. }(GLTF2.GLTFLoaderExtension));
  109935. Extensions.MSFT_lod = MSFT_lod;
  109936. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new MSFT_lod(loader); });
  109937. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  109938. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  109939. })(BABYLON || (BABYLON = {}));
  109940. //# sourceMappingURL=MSFT_lod.js.map
  109941. var BABYLON;
  109942. (function (BABYLON) {
  109943. var GLTF2;
  109944. (function (GLTF2) {
  109945. var Extensions;
  109946. (function (Extensions) {
  109947. // https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_draco_mesh_compression
  109948. var NAME = "KHR_draco_mesh_compression";
  109949. var KHR_draco_mesh_compression = /** @class */ (function (_super) {
  109950. __extends(KHR_draco_mesh_compression, _super);
  109951. function KHR_draco_mesh_compression(loader) {
  109952. var _this = _super.call(this, loader) || this;
  109953. _this.name = NAME;
  109954. _this._dracoCompression = null;
  109955. // Disable extension if decoder is not available.
  109956. if (!BABYLON.DracoCompression.DecoderUrl) {
  109957. _this.enabled = false;
  109958. }
  109959. return _this;
  109960. }
  109961. KHR_draco_mesh_compression.prototype.dispose = function () {
  109962. if (this._dracoCompression) {
  109963. this._dracoCompression.dispose();
  109964. }
  109965. _super.prototype.dispose.call(this);
  109966. };
  109967. KHR_draco_mesh_compression.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) {
  109968. var _this = this;
  109969. return this._loadExtensionAsync(context, primitive, function (extensionContext, extension) {
  109970. if (primitive.mode != undefined) {
  109971. if (primitive.mode !== 5 /* TRIANGLE_STRIP */ &&
  109972. primitive.mode !== 4 /* TRIANGLES */) {
  109973. throw new Error(context + ": Unsupported mode " + primitive.mode);
  109974. }
  109975. // TODO: handle triangle strips
  109976. if (primitive.mode === 5 /* TRIANGLE_STRIP */) {
  109977. throw new Error(context + ": Mode " + primitive.mode + " is not currently supported");
  109978. }
  109979. }
  109980. var attributes = {};
  109981. var loadAttribute = function (name, kind) {
  109982. var uniqueId = extension.attributes[name];
  109983. if (uniqueId == undefined) {
  109984. return;
  109985. }
  109986. babylonMesh._delayInfo = babylonMesh._delayInfo || [];
  109987. if (babylonMesh._delayInfo.indexOf(kind) === -1) {
  109988. babylonMesh._delayInfo.push(kind);
  109989. }
  109990. attributes[kind] = uniqueId;
  109991. };
  109992. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind);
  109993. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind);
  109994. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind);
  109995. loadAttribute("TEXCOORD_0", BABYLON.VertexBuffer.UVKind);
  109996. loadAttribute("TEXCOORD_1", BABYLON.VertexBuffer.UV2Kind);
  109997. loadAttribute("JOINTS_0", BABYLON.VertexBuffer.MatricesIndicesKind);
  109998. loadAttribute("WEIGHTS_0", BABYLON.VertexBuffer.MatricesWeightsKind);
  109999. loadAttribute("COLOR_0", BABYLON.VertexBuffer.ColorKind);
  110000. var bufferView = GLTF2.GLTFLoader._GetProperty(extensionContext, _this._loader._gltf.bufferViews, extension.bufferView);
  110001. return _this._loader._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView).then(function (data) {
  110002. try {
  110003. if (!_this._dracoCompression) {
  110004. _this._dracoCompression = new BABYLON.DracoCompression();
  110005. }
  110006. return _this._dracoCompression.decodeMeshAsync(data, attributes);
  110007. }
  110008. catch (e) {
  110009. throw new Error(context + ": " + e.message);
  110010. }
  110011. });
  110012. });
  110013. };
  110014. return KHR_draco_mesh_compression;
  110015. }(GLTF2.GLTFLoaderExtension));
  110016. Extensions.KHR_draco_mesh_compression = KHR_draco_mesh_compression;
  110017. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_draco_mesh_compression(loader); });
  110018. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  110019. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  110020. })(BABYLON || (BABYLON = {}));
  110021. //# sourceMappingURL=KHR_draco_mesh_compression.js.map
  110022. var BABYLON;
  110023. (function (BABYLON) {
  110024. var GLTF2;
  110025. (function (GLTF2) {
  110026. var Extensions;
  110027. (function (Extensions) {
  110028. // https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_pbrSpecularGlossiness
  110029. var NAME = "KHR_materials_pbrSpecularGlossiness";
  110030. var KHR_materials_pbrSpecularGlossiness = /** @class */ (function (_super) {
  110031. __extends(KHR_materials_pbrSpecularGlossiness, _super);
  110032. function KHR_materials_pbrSpecularGlossiness() {
  110033. var _this = _super !== null && _super.apply(this, arguments) || this;
  110034. _this.name = NAME;
  110035. return _this;
  110036. }
  110037. KHR_materials_pbrSpecularGlossiness.prototype._loadMaterialAsync = function (context, material, babylonMesh, assign) {
  110038. var _this = this;
  110039. return this._loadExtensionAsync(context, material, function (context, extension) {
  110040. material._babylonMeshes = material._babylonMeshes || [];
  110041. material._babylonMeshes.push(babylonMesh);
  110042. if (!material._loaded) {
  110043. var promises = new Array();
  110044. var babylonMaterial = _this._loader._createMaterial(material);
  110045. material._babylonMaterial = babylonMaterial;
  110046. promises.push(_this._loader._loadMaterialBasePropertiesAsync(context, material));
  110047. promises.push(_this._loadSpecularGlossinessPropertiesAsync(context, material, extension));
  110048. _this._loader.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  110049. material._loaded = Promise.all(promises).then(function () { });
  110050. }
  110051. assign(material._babylonMaterial);
  110052. return material._loaded;
  110053. });
  110054. };
  110055. KHR_materials_pbrSpecularGlossiness.prototype._loadSpecularGlossinessPropertiesAsync = function (context, material, properties) {
  110056. var promises = new Array();
  110057. var babylonMaterial = material._babylonMaterial;
  110058. if (properties.diffuseFactor) {
  110059. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.diffuseFactor);
  110060. babylonMaterial.alpha = properties.diffuseFactor[3];
  110061. }
  110062. else {
  110063. babylonMaterial.albedoColor = BABYLON.Color3.White();
  110064. }
  110065. babylonMaterial.reflectivityColor = properties.specularFactor ? BABYLON.Color3.FromArray(properties.specularFactor) : BABYLON.Color3.White();
  110066. babylonMaterial.microSurface = properties.glossinessFactor == undefined ? 1 : properties.glossinessFactor;
  110067. if (properties.diffuseTexture) {
  110068. promises.push(this._loader._loadTextureAsync(context + "/diffuseTexture", properties.diffuseTexture, function (texture) {
  110069. babylonMaterial.albedoTexture = texture;
  110070. }));
  110071. }
  110072. if (properties.specularGlossinessTexture) {
  110073. promises.push(this._loader._loadTextureAsync(context + "/specularGlossinessTexture", properties.specularGlossinessTexture, function (texture) {
  110074. babylonMaterial.reflectivityTexture = texture;
  110075. }));
  110076. babylonMaterial.reflectivityTexture.hasAlpha = true;
  110077. babylonMaterial.useMicroSurfaceFromReflectivityMapAlpha = true;
  110078. }
  110079. this._loader._loadMaterialAlphaProperties(context, material);
  110080. return Promise.all(promises).then(function () { });
  110081. };
  110082. return KHR_materials_pbrSpecularGlossiness;
  110083. }(GLTF2.GLTFLoaderExtension));
  110084. Extensions.KHR_materials_pbrSpecularGlossiness = KHR_materials_pbrSpecularGlossiness;
  110085. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_materials_pbrSpecularGlossiness(loader); });
  110086. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  110087. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  110088. })(BABYLON || (BABYLON = {}));
  110089. //# sourceMappingURL=KHR_materials_pbrSpecularGlossiness.js.map
  110090. var BABYLON;
  110091. (function (BABYLON) {
  110092. var GLTF2;
  110093. (function (GLTF2) {
  110094. var Extensions;
  110095. (function (Extensions) {
  110096. // https://github.com/MiiBond/glTF/tree/khr_lights_v1/extensions/Khronos/KHR_lights
  110097. var NAME = "KHR_lights";
  110098. var LightType;
  110099. (function (LightType) {
  110100. LightType["AMBIENT"] = "ambient";
  110101. LightType["DIRECTIONAL"] = "directional";
  110102. LightType["POINT"] = "point";
  110103. LightType["SPOT"] = "spot";
  110104. })(LightType || (LightType = {}));
  110105. var KHR_lights = /** @class */ (function (_super) {
  110106. __extends(KHR_lights, _super);
  110107. function KHR_lights() {
  110108. var _this = _super !== null && _super.apply(this, arguments) || this;
  110109. _this.name = NAME;
  110110. return _this;
  110111. }
  110112. KHR_lights.prototype._loadSceneAsync = function (context, scene) {
  110113. var _this = this;
  110114. return this._loadExtensionAsync(context, scene, function (context, extension) {
  110115. var promise = _this._loader._loadSceneAsync(context, scene);
  110116. var light = GLTF2.GLTFLoader._GetProperty(context, _this._lights, extension.light);
  110117. if (light.type !== LightType.AMBIENT) {
  110118. throw new Error(context + ": Only ambient lights are allowed on a scene");
  110119. }
  110120. _this._loader._babylonScene.ambientColor = light.color ? BABYLON.Color3.FromArray(light.color) : BABYLON.Color3.Black();
  110121. return promise;
  110122. });
  110123. };
  110124. KHR_lights.prototype._loadNodeAsync = function (context, node) {
  110125. var _this = this;
  110126. return this._loadExtensionAsync(context, node, function (context, extension) {
  110127. var promise = _this._loader._loadNodeAsync(context, node);
  110128. var babylonLight;
  110129. var light = GLTF2.GLTFLoader._GetProperty(context, _this._lights, extension.light);
  110130. var name = node._babylonMesh.name;
  110131. switch (light.type) {
  110132. case LightType.AMBIENT: {
  110133. throw new Error(context + ": Ambient lights are not allowed on a node");
  110134. }
  110135. case LightType.DIRECTIONAL: {
  110136. babylonLight = new BABYLON.DirectionalLight(name, BABYLON.Vector3.Forward(), _this._loader._babylonScene);
  110137. break;
  110138. }
  110139. case LightType.POINT: {
  110140. babylonLight = new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), _this._loader._babylonScene);
  110141. break;
  110142. }
  110143. case LightType.SPOT: {
  110144. var spotLight = light;
  110145. // TODO: support inner and outer cone angles
  110146. //const innerConeAngle = spotLight.innerConeAngle || 0;
  110147. var outerConeAngle = spotLight.outerConeAngle || Math.PI / 4;
  110148. babylonLight = new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward(), outerConeAngle, 2, _this._loader._babylonScene);
  110149. break;
  110150. }
  110151. default: {
  110152. throw new Error(context + ": Invalid light type (" + light.type + ")");
  110153. }
  110154. }
  110155. babylonLight.diffuse = light.color ? BABYLON.Color3.FromArray(light.color) : BABYLON.Color3.White();
  110156. babylonLight.intensity = light.intensity == undefined ? 1 : light.intensity;
  110157. babylonLight.parent = node._babylonMesh;
  110158. return promise;
  110159. });
  110160. };
  110161. Object.defineProperty(KHR_lights.prototype, "_lights", {
  110162. get: function () {
  110163. var extensions = this._loader._gltf.extensions;
  110164. if (!extensions || !extensions[this.name]) {
  110165. throw new Error("#/extensions: '" + this.name + "' not found");
  110166. }
  110167. var extension = extensions[this.name];
  110168. return extension.lights;
  110169. },
  110170. enumerable: true,
  110171. configurable: true
  110172. });
  110173. return KHR_lights;
  110174. }(GLTF2.GLTFLoaderExtension));
  110175. Extensions.KHR_lights = KHR_lights;
  110176. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_lights(loader); });
  110177. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  110178. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  110179. })(BABYLON || (BABYLON = {}));
  110180. //# sourceMappingURL=KHR_lights.js.map
  110181. return BABYLON;
  110182. });
  110183. /***/ }),
  110184. /* 33 */
  110185. /***/ (function(module, exports, __webpack_require__) {
  110186. /*!
  110187. * PEP v0.4.3 | https://github.com/jquery/PEP
  110188. * Copyright jQuery Foundation and other contributors | http://jquery.org/license
  110189. */
  110190. !function(a,b){ true?module.exports=b():"function"==typeof define&&define.amd?define(b):a.PointerEventsPolyfill=b()}(this,function(){"use strict";function a(a,b){b=b||Object.create(null);var c=document.createEvent("Event");c.initEvent(a,b.bubbles||!1,b.cancelable||!1);
  110191. // define inherited MouseEvent properties
  110192. // skip bubbles and cancelable since they're set above in initEvent()
  110193. for(var d,e=2;e<m.length;e++)d=m[e],c[d]=b[d]||n[e];c.buttons=b.buttons||0;
  110194. // Spec requires that pointers without pressure specified use 0.5 for down
  110195. // state and 0 for up state.
  110196. var f=0;
  110197. // add x/y properties aliased to clientX/Y
  110198. // define the properties of the PointerEvent interface
  110199. return f=b.pressure&&c.buttons?b.pressure:c.buttons?.5:0,c.x=c.clientX,c.y=c.clientY,c.pointerId=b.pointerId||0,c.width=b.width||0,c.height=b.height||0,c.pressure=f,c.tiltX=b.tiltX||0,c.tiltY=b.tiltY||0,c.twist=b.twist||0,c.tangentialPressure=b.tangentialPressure||0,c.pointerType=b.pointerType||"",c.hwTimestamp=b.hwTimestamp||0,c.isPrimary=b.isPrimary||!1,c}function b(){this.array=[],this.size=0}function c(a,b,c,d){this.addCallback=a.bind(d),this.removeCallback=b.bind(d),this.changedCallback=c.bind(d),A&&(this.observer=new A(this.mutationWatcher.bind(this)))}function d(a){return"body /shadow-deep/ "+e(a)}function e(a){return'[touch-action="'+a+'"]'}function f(a){return"{ -ms-touch-action: "+a+"; touch-action: "+a+"; }"}function g(){if(F){D.forEach(function(a){String(a)===a?(E+=e(a)+f(a)+"\n",G&&(E+=d(a)+f(a)+"\n")):(E+=a.selectors.map(e)+f(a.rule)+"\n",G&&(E+=a.selectors.map(d)+f(a.rule)+"\n"))});var a=document.createElement("style");a.textContent=E,document.head.appendChild(a)}}function h(){
  110200. // only activate if this platform does not have pointer events
  110201. if(!window.PointerEvent){if(window.PointerEvent=a,window.navigator.msPointerEnabled){var b=window.navigator.msMaxTouchPoints;Object.defineProperty(window.navigator,"maxTouchPoints",{value:b,enumerable:!0}),u.registerSource("ms",_)}else Object.defineProperty(window.navigator,"maxTouchPoints",{value:0,enumerable:!0}),u.registerSource("mouse",N),void 0!==window.ontouchstart&&u.registerSource("touch",V);u.register(document)}}function i(a){if(!u.pointermap.has(a)){var b=new Error("InvalidPointerId");throw b.name="InvalidPointerId",b}}function j(a){for(var b=a.parentNode;b&&b!==a.ownerDocument;)b=b.parentNode;if(!b){var c=new Error("InvalidStateError");throw c.name="InvalidStateError",c}}function k(a){var b=u.pointermap.get(a);return 0!==b.buttons}function l(){window.Element&&!Element.prototype.setPointerCapture&&Object.defineProperties(Element.prototype,{setPointerCapture:{value:W},releasePointerCapture:{value:X},hasPointerCapture:{value:Y}})}/**
  110202. * This is the constructor for new PointerEvents.
  110203. *
  110204. * New Pointer Events must be given a type, and an optional dictionary of
  110205. * initialization properties.
  110206. *
  110207. * Due to certain platform requirements, events returned from the constructor
  110208. * identify as MouseEvents.
  110209. *
  110210. * @constructor
  110211. * @param {String} inType The type of the event to create.
  110212. * @param {Object} [inDict] An optional dictionary of initial event properties.
  110213. * @return {Event} A new PointerEvent of type `inType`, initialized with properties from `inDict`.
  110214. */
  110215. var m=["bubbles","cancelable","view","detail","screenX","screenY","clientX","clientY","ctrlKey","altKey","shiftKey","metaKey","button","relatedTarget","pageX","pageY"],n=[!1,!1,null,null,0,0,0,0,!1,!1,!1,!1,0,null,0,0],o=window.Map&&window.Map.prototype.forEach,p=o?Map:b;b.prototype={set:function(a,b){return void 0===b?this["delete"](a):(this.has(a)||this.size++,void(this.array[a]=b))},has:function(a){return void 0!==this.array[a]},"delete":function(a){this.has(a)&&(delete this.array[a],this.size--)},get:function(a){return this.array[a]},clear:function(){this.array.length=0,this.size=0},
  110216. // return value, key, map
  110217. forEach:function(a,b){return this.array.forEach(function(c,d){a.call(b,c,d,this)},this)}};var q=[
  110218. // MouseEvent
  110219. "bubbles","cancelable","view","detail","screenX","screenY","clientX","clientY","ctrlKey","altKey","shiftKey","metaKey","button","relatedTarget",
  110220. // DOM Level 3
  110221. "buttons",
  110222. // PointerEvent
  110223. "pointerId","width","height","pressure","tiltX","tiltY","pointerType","hwTimestamp","isPrimary",
  110224. // event instance
  110225. "type","target","currentTarget","which","pageX","pageY","timeStamp"],r=[
  110226. // MouseEvent
  110227. !1,!1,null,null,0,0,0,0,!1,!1,!1,!1,0,null,
  110228. // DOM Level 3
  110229. 0,
  110230. // PointerEvent
  110231. 0,0,0,0,0,0,"",0,!1,
  110232. // event instance
  110233. "",null,null,0,0,0,0],s={pointerover:1,pointerout:1,pointerenter:1,pointerleave:1},t="undefined"!=typeof SVGElementInstance,u={pointermap:new p,eventMap:Object.create(null),captureInfo:Object.create(null),
  110234. // Scope objects for native events.
  110235. // This exists for ease of testing.
  110236. eventSources:Object.create(null),eventSourceList:[],/**
  110237. * Add a new event source that will generate pointer events.
  110238. *
  110239. * `inSource` must contain an array of event names named `events`, and
  110240. * functions with the names specified in the `events` array.
  110241. * @param {string} name A name for the event source
  110242. * @param {Object} source A new source of platform events.
  110243. */
  110244. registerSource:function(a,b){var c=b,d=c.events;d&&(d.forEach(function(a){c[a]&&(this.eventMap[a]=c[a].bind(c))},this),this.eventSources[a]=c,this.eventSourceList.push(c))},register:function(a){for(var b,c=this.eventSourceList.length,d=0;d<c&&(b=this.eventSourceList[d]);d++)
  110245. // call eventsource register
  110246. b.register.call(b,a)},unregister:function(a){for(var b,c=this.eventSourceList.length,d=0;d<c&&(b=this.eventSourceList[d]);d++)
  110247. // call eventsource register
  110248. b.unregister.call(b,a)},contains:/*scope.external.contains || */function(a,b){try{return a.contains(b)}catch(c){
  110249. // most likely: https://bugzilla.mozilla.org/show_bug.cgi?id=208427
  110250. return!1}},
  110251. // EVENTS
  110252. down:function(a){a.bubbles=!0,this.fireEvent("pointerdown",a)},move:function(a){a.bubbles=!0,this.fireEvent("pointermove",a)},up:function(a){a.bubbles=!0,this.fireEvent("pointerup",a)},enter:function(a){a.bubbles=!1,this.fireEvent("pointerenter",a)},leave:function(a){a.bubbles=!1,this.fireEvent("pointerleave",a)},over:function(a){a.bubbles=!0,this.fireEvent("pointerover",a)},out:function(a){a.bubbles=!0,this.fireEvent("pointerout",a)},cancel:function(a){a.bubbles=!0,this.fireEvent("pointercancel",a)},leaveOut:function(a){this.out(a),this.propagate(a,this.leave,!1)},enterOver:function(a){this.over(a),this.propagate(a,this.enter,!0)},
  110253. // LISTENER LOGIC
  110254. eventHandler:function(a){
  110255. // This is used to prevent multiple dispatch of pointerevents from
  110256. // platform events. This can happen when two elements in different scopes
  110257. // are set up to create pointer events, which is relevant to Shadow DOM.
  110258. if(!a._handledByPE){var b=a.type,c=this.eventMap&&this.eventMap[b];c&&c(a),a._handledByPE=!0}},
  110259. // set up event listeners
  110260. listen:function(a,b){b.forEach(function(b){this.addEvent(a,b)},this)},
  110261. // remove event listeners
  110262. unlisten:function(a,b){b.forEach(function(b){this.removeEvent(a,b)},this)},addEvent:/*scope.external.addEvent || */function(a,b){a.addEventListener(b,this.boundHandler)},removeEvent:/*scope.external.removeEvent || */function(a,b){a.removeEventListener(b,this.boundHandler)},
  110263. // EVENT CREATION AND TRACKING
  110264. /**
  110265. * Creates a new Event of type `inType`, based on the information in
  110266. * `inEvent`.
  110267. *
  110268. * @param {string} inType A string representing the type of event to create
  110269. * @param {Event} inEvent A platform event with a target
  110270. * @return {Event} A PointerEvent of type `inType`
  110271. */
  110272. makeEvent:function(b,c){
  110273. // relatedTarget must be null if pointer is captured
  110274. this.captureInfo[c.pointerId]&&(c.relatedTarget=null);var d=new a(b,c);return c.preventDefault&&(d.preventDefault=c.preventDefault),d._target=d._target||c.target,d},
  110275. // make and dispatch an event in one call
  110276. fireEvent:function(a,b){var c=this.makeEvent(a,b);return this.dispatchEvent(c)},/**
  110277. * Returns a snapshot of inEvent, with writable properties.
  110278. *
  110279. * @param {Event} inEvent An event that contains properties to copy.
  110280. * @return {Object} An object containing shallow copies of `inEvent`'s
  110281. * properties.
  110282. */
  110283. cloneEvent:function(a){for(var b,c=Object.create(null),d=0;d<q.length;d++)b=q[d],c[b]=a[b]||r[d],
  110284. // Work around SVGInstanceElement shadow tree
  110285. // Return the <use> element that is represented by the instance for Safari, Chrome, IE.
  110286. // This is the behavior implemented by Firefox.
  110287. !t||"target"!==b&&"relatedTarget"!==b||c[b]instanceof SVGElementInstance&&(c[b]=c[b].correspondingUseElement);
  110288. // keep the semantics of preventDefault
  110289. return a.preventDefault&&(c.preventDefault=function(){a.preventDefault()}),c},getTarget:function(a){var b=this.captureInfo[a.pointerId];return b?a._target!==b&&a.type in s?void 0:b:a._target},propagate:function(a,b,c){
  110290. // Order of conditions due to document.contains() missing in IE.
  110291. for(var d=a.target,e=[];d!==document&&!d.contains(a.relatedTarget);)
  110292. // Touch: Do not propagate if node is detached.
  110293. if(e.push(d),d=d.parentNode,!d)return;c&&e.reverse(),e.forEach(function(c){a.target=c,b.call(this,a)},this)},setCapture:function(b,c,d){this.captureInfo[b]&&this.releaseCapture(b,d),this.captureInfo[b]=c,this.implicitRelease=this.releaseCapture.bind(this,b,d),document.addEventListener("pointerup",this.implicitRelease),document.addEventListener("pointercancel",this.implicitRelease);var e=new a("gotpointercapture");e.pointerId=b,e._target=c,d||this.asyncDispatchEvent(e)},releaseCapture:function(b,c){var d=this.captureInfo[b];if(d){this.captureInfo[b]=void 0,document.removeEventListener("pointerup",this.implicitRelease),document.removeEventListener("pointercancel",this.implicitRelease);var e=new a("lostpointercapture");e.pointerId=b,e._target=d,c||this.asyncDispatchEvent(e)}},/**
  110294. * Dispatches the event to its target.
  110295. *
  110296. * @param {Event} inEvent The event to be dispatched.
  110297. * @return {Boolean} True if an event handler returns true, false otherwise.
  110298. */
  110299. dispatchEvent:/*scope.external.dispatchEvent || */function(a){var b=this.getTarget(a);if(b)return b.dispatchEvent(a)},asyncDispatchEvent:function(a){requestAnimationFrame(this.dispatchEvent.bind(this,a))}};u.boundHandler=u.eventHandler.bind(u);var v={shadow:function(a){if(a)return a.shadowRoot||a.webkitShadowRoot},canTarget:function(a){return a&&Boolean(a.elementFromPoint)},targetingShadow:function(a){var b=this.shadow(a);if(this.canTarget(b))return b},olderShadow:function(a){var b=a.olderShadowRoot;if(!b){var c=a.querySelector("shadow");c&&(b=c.olderShadowRoot)}return b},allShadows:function(a){for(var b=[],c=this.shadow(a);c;)b.push(c),c=this.olderShadow(c);return b},searchRoot:function(a,b,c){if(a){var d,e,f=a.elementFromPoint(b,c);for(
  110300. // is element a shadow host?
  110301. e=this.targetingShadow(f);e;){if(
  110302. // find the the element inside the shadow root
  110303. d=e.elementFromPoint(b,c)){
  110304. // shadowed element may contain a shadow root
  110305. var g=this.targetingShadow(d);return this.searchRoot(g,b,c)||d}
  110306. // check for older shadows
  110307. e=this.olderShadow(e)}
  110308. // light dom element is the target
  110309. return f}},owner:function(a){
  110310. // walk up until you hit the shadow root or document
  110311. for(var b=a;b.parentNode;)b=b.parentNode;
  110312. // the owner element is expected to be a Document or ShadowRoot
  110313. return b.nodeType!==Node.DOCUMENT_NODE&&b.nodeType!==Node.DOCUMENT_FRAGMENT_NODE&&(b=document),b},findTarget:function(a){var b=a.clientX,c=a.clientY,d=this.owner(a.target);
  110314. // if x, y is not in this root, fall back to document search
  110315. return d.elementFromPoint(b,c)||(d=document),this.searchRoot(d,b,c)}},w=Array.prototype.forEach.call.bind(Array.prototype.forEach),x=Array.prototype.map.call.bind(Array.prototype.map),y=Array.prototype.slice.call.bind(Array.prototype.slice),z=Array.prototype.filter.call.bind(Array.prototype.filter),A=window.MutationObserver||window.WebKitMutationObserver,B="[touch-action]",C={subtree:!0,childList:!0,attributes:!0,attributeOldValue:!0,attributeFilter:["touch-action"]};c.prototype={watchSubtree:function(a){
  110316. // Only watch scopes that can target find, as these are top-level.
  110317. // Otherwise we can see duplicate additions and removals that add noise.
  110318. //
  110319. // TODO(dfreedman): For some instances with ShadowDOMPolyfill, we can see
  110320. // a removal without an insertion when a node is redistributed among
  110321. // shadows. Since it all ends up correct in the document, watching only
  110322. // the document will yield the correct mutations to watch.
  110323. this.observer&&v.canTarget(a)&&this.observer.observe(a,C)},enableOnSubtree:function(a){this.watchSubtree(a),a===document&&"complete"!==document.readyState?this.installOnLoad():this.installNewSubtree(a)},installNewSubtree:function(a){w(this.findElements(a),this.addElement,this)},findElements:function(a){return a.querySelectorAll?a.querySelectorAll(B):[]},removeElement:function(a){this.removeCallback(a)},addElement:function(a){this.addCallback(a)},elementChanged:function(a,b){this.changedCallback(a,b)},concatLists:function(a,b){return a.concat(y(b))},
  110324. // register all touch-action = none nodes on document load
  110325. installOnLoad:function(){document.addEventListener("readystatechange",function(){"complete"===document.readyState&&this.installNewSubtree(document)}.bind(this))},isElement:function(a){return a.nodeType===Node.ELEMENT_NODE},flattenMutationTree:function(a){
  110326. // find children with touch-action
  110327. var b=x(a,this.findElements,this);
  110328. // flatten the list
  110329. // make sure the added nodes are accounted for
  110330. return b.push(z(a,this.isElement)),b.reduce(this.concatLists,[])},mutationWatcher:function(a){a.forEach(this.mutationHandler,this)},mutationHandler:function(a){if("childList"===a.type){var b=this.flattenMutationTree(a.addedNodes);b.forEach(this.addElement,this);var c=this.flattenMutationTree(a.removedNodes);c.forEach(this.removeElement,this)}else"attributes"===a.type&&this.elementChanged(a.target,a.oldValue)}};var D=["none","auto","pan-x","pan-y",{rule:"pan-x pan-y",selectors:["pan-x pan-y","pan-y pan-x"]}],E="",F=window.PointerEvent||window.MSPointerEvent,G=!window.ShadowDOMPolyfill&&document.head.createShadowRoot,H=u.pointermap,I=25,J=[1,4,2,8,16],K=!1;try{K=1===new MouseEvent("test",{buttons:1}).buttons}catch(L){}
  110331. // handler block for native mouse events
  110332. var M,N={POINTER_ID:1,POINTER_TYPE:"mouse",events:["mousedown","mousemove","mouseup","mouseover","mouseout"],register:function(a){u.listen(a,this.events)},unregister:function(a){u.unlisten(a,this.events)},lastTouches:[],
  110333. // collide with the global mouse listener
  110334. isEventSimulatedFromTouch:function(a){for(var b,c=this.lastTouches,d=a.clientX,e=a.clientY,f=0,g=c.length;f<g&&(b=c[f]);f++){
  110335. // simulated mouse events will be swallowed near a primary touchend
  110336. var h=Math.abs(d-b.x),i=Math.abs(e-b.y);if(h<=I&&i<=I)return!0}},prepareEvent:function(a){var b=u.cloneEvent(a),c=b.preventDefault;return b.preventDefault=function(){a.preventDefault(),c()},b.pointerId=this.POINTER_ID,b.isPrimary=!0,b.pointerType=this.POINTER_TYPE,b},prepareButtonsForMove:function(a,b){var c=H.get(this.POINTER_ID);
  110337. // Update buttons state after possible out-of-document mouseup.
  110338. 0!==b.which&&c?a.buttons=c.buttons:a.buttons=0,b.buttons=a.buttons},mousedown:function(a){if(!this.isEventSimulatedFromTouch(a)){var b=H.get(this.POINTER_ID),c=this.prepareEvent(a);K||(c.buttons=J[c.button],b&&(c.buttons|=b.buttons),a.buttons=c.buttons),H.set(this.POINTER_ID,a),b&&0!==b.buttons?u.move(c):u.down(c)}},mousemove:function(a){if(!this.isEventSimulatedFromTouch(a)){var b=this.prepareEvent(a);K||this.prepareButtonsForMove(b,a),b.button=-1,H.set(this.POINTER_ID,a),u.move(b)}},mouseup:function(a){if(!this.isEventSimulatedFromTouch(a)){var b=H.get(this.POINTER_ID),c=this.prepareEvent(a);if(!K){var d=J[c.button];
  110339. // Produces wrong state of buttons in Browsers without `buttons` support
  110340. // when a mouse button that was pressed outside the document is released
  110341. // inside and other buttons are still pressed down.
  110342. c.buttons=b?b.buttons&~d:0,a.buttons=c.buttons}H.set(this.POINTER_ID,a),
  110343. // Support: Firefox <=44 only
  110344. // FF Ubuntu includes the lifted button in the `buttons` property on
  110345. // mouseup.
  110346. // https://bugzilla.mozilla.org/show_bug.cgi?id=1223366
  110347. c.buttons&=~J[c.button],0===c.buttons?u.up(c):u.move(c)}},mouseover:function(a){if(!this.isEventSimulatedFromTouch(a)){var b=this.prepareEvent(a);K||this.prepareButtonsForMove(b,a),b.button=-1,H.set(this.POINTER_ID,a),u.enterOver(b)}},mouseout:function(a){if(!this.isEventSimulatedFromTouch(a)){var b=this.prepareEvent(a);K||this.prepareButtonsForMove(b,a),b.button=-1,u.leaveOut(b)}},cancel:function(a){var b=this.prepareEvent(a);u.cancel(b),this.deactivateMouse()},deactivateMouse:function(){H["delete"](this.POINTER_ID)}},O=u.captureInfo,P=v.findTarget.bind(v),Q=v.allShadows.bind(v),R=u.pointermap,S=2500,T=200,U="touch-action",V={events:["touchstart","touchmove","touchend","touchcancel"],register:function(a){M.enableOnSubtree(a)},unregister:function(){},elementAdded:function(a){var b=a.getAttribute(U),c=this.touchActionToScrollType(b);c&&(a._scrollType=c,u.listen(a,this.events),
  110348. // set touch-action on shadows as well
  110349. Q(a).forEach(function(a){a._scrollType=c,u.listen(a,this.events)},this))},elementRemoved:function(a){a._scrollType=void 0,u.unlisten(a,this.events),
  110350. // remove touch-action from shadow
  110351. Q(a).forEach(function(a){a._scrollType=void 0,u.unlisten(a,this.events)},this)},elementChanged:function(a,b){var c=a.getAttribute(U),d=this.touchActionToScrollType(c),e=this.touchActionToScrollType(b);
  110352. // simply update scrollType if listeners are already established
  110353. d&&e?(a._scrollType=d,Q(a).forEach(function(a){a._scrollType=d},this)):e?this.elementRemoved(a):d&&this.elementAdded(a)},scrollTypes:{EMITTER:"none",XSCROLLER:"pan-x",YSCROLLER:"pan-y",SCROLLER:/^(?:pan-x pan-y)|(?:pan-y pan-x)|auto$/},touchActionToScrollType:function(a){var b=a,c=this.scrollTypes;return"none"===b?"none":b===c.XSCROLLER?"X":b===c.YSCROLLER?"Y":c.SCROLLER.exec(b)?"XY":void 0},POINTER_TYPE:"touch",firstTouch:null,isPrimaryTouch:function(a){return this.firstTouch===a.identifier},setPrimaryTouch:function(a){
  110354. // set primary touch if there no pointers, or the only pointer is the mouse
  110355. (0===R.size||1===R.size&&R.has(1))&&(this.firstTouch=a.identifier,this.firstXY={X:a.clientX,Y:a.clientY},this.scrolling=!1,this.cancelResetClickCount())},removePrimaryPointer:function(a){a.isPrimary&&(this.firstTouch=null,this.firstXY=null,this.resetClickCount())},clickCount:0,resetId:null,resetClickCount:function(){var a=function(){this.clickCount=0,this.resetId=null}.bind(this);this.resetId=setTimeout(a,T)},cancelResetClickCount:function(){this.resetId&&clearTimeout(this.resetId)},typeToButtons:function(a){var b=0;return"touchstart"!==a&&"touchmove"!==a||(b=1),b},touchToPointer:function(a){var b=this.currentTouchEvent,c=u.cloneEvent(a),d=c.pointerId=a.identifier+2;c.target=O[d]||P(c),c.bubbles=!0,c.cancelable=!0,c.detail=this.clickCount,c.button=0,c.buttons=this.typeToButtons(b.type),c.width=2*(a.radiusX||a.webkitRadiusX||0),c.height=2*(a.radiusY||a.webkitRadiusY||0),c.pressure=a.force||a.webkitForce||.5,c.isPrimary=this.isPrimaryTouch(a),c.pointerType=this.POINTER_TYPE,
  110356. // forward modifier keys
  110357. c.altKey=b.altKey,c.ctrlKey=b.ctrlKey,c.metaKey=b.metaKey,c.shiftKey=b.shiftKey;
  110358. // forward touch preventDefaults
  110359. var e=this;return c.preventDefault=function(){e.scrolling=!1,e.firstXY=null,b.preventDefault()},c},processTouches:function(a,b){var c=a.changedTouches;this.currentTouchEvent=a;for(var d,e=0;e<c.length;e++)d=c[e],b.call(this,this.touchToPointer(d))},
  110360. // For single axis scrollers, determines whether the element should emit
  110361. // pointer events or behave as a scroller
  110362. shouldScroll:function(a){if(this.firstXY){var b,c=a.currentTarget._scrollType;if("none"===c)
  110363. // this element is a touch-action: none, should never scroll
  110364. b=!1;else if("XY"===c)
  110365. // this element should always scroll
  110366. b=!0;else{var d=a.changedTouches[0],e=c,f="Y"===c?"X":"Y",g=Math.abs(d["client"+e]-this.firstXY[e]),h=Math.abs(d["client"+f]-this.firstXY[f]);
  110367. // if delta in the scroll axis > delta other axis, scroll instead of
  110368. // making events
  110369. b=g>=h}return this.firstXY=null,b}},findTouch:function(a,b){for(var c,d=0,e=a.length;d<e&&(c=a[d]);d++)if(c.identifier===b)return!0},
  110370. // In some instances, a touchstart can happen without a touchend. This
  110371. // leaves the pointermap in a broken state.
  110372. // Therefore, on every touchstart, we remove the touches that did not fire a
  110373. // touchend event.
  110374. // To keep state globally consistent, we fire a
  110375. // pointercancel for this "abandoned" touch
  110376. vacuumTouches:function(a){var b=a.touches;
  110377. // pointermap.size should be < tl.length here, as the touchstart has not
  110378. // been processed yet.
  110379. if(R.size>=b.length){var c=[];R.forEach(function(a,d){
  110380. // Never remove pointerId == 1, which is mouse.
  110381. // Touch identifiers are 2 smaller than their pointerId, which is the
  110382. // index in pointermap.
  110383. if(1!==d&&!this.findTouch(b,d-2)){var e=a.out;c.push(e)}},this),c.forEach(this.cancelOut,this)}},touchstart:function(a){this.vacuumTouches(a),this.setPrimaryTouch(a.changedTouches[0]),this.dedupSynthMouse(a),this.scrolling||(this.clickCount++,this.processTouches(a,this.overDown))},overDown:function(a){R.set(a.pointerId,{target:a.target,out:a,outTarget:a.target}),u.enterOver(a),u.down(a)},touchmove:function(a){this.scrolling||(this.shouldScroll(a)?(this.scrolling=!0,this.touchcancel(a)):(a.preventDefault(),this.processTouches(a,this.moveOverOut)))},moveOverOut:function(a){var b=a,c=R.get(b.pointerId);
  110384. // a finger drifted off the screen, ignore it
  110385. if(c){var d=c.out,e=c.outTarget;u.move(b),d&&e!==b.target&&(d.relatedTarget=b.target,b.relatedTarget=e,
  110386. // recover from retargeting by shadow
  110387. d.target=e,b.target?(u.leaveOut(d),u.enterOver(b)):(
  110388. // clean up case when finger leaves the screen
  110389. b.target=e,b.relatedTarget=null,this.cancelOut(b))),c.out=b,c.outTarget=b.target}},touchend:function(a){this.dedupSynthMouse(a),this.processTouches(a,this.upOut)},upOut:function(a){this.scrolling||(u.up(a),u.leaveOut(a)),this.cleanUpPointer(a)},touchcancel:function(a){this.processTouches(a,this.cancelOut)},cancelOut:function(a){u.cancel(a),u.leaveOut(a),this.cleanUpPointer(a)},cleanUpPointer:function(a){R["delete"](a.pointerId),this.removePrimaryPointer(a)},
  110390. // prevent synth mouse events from creating pointer events
  110391. dedupSynthMouse:function(a){var b=N.lastTouches,c=a.changedTouches[0];
  110392. // only the primary finger will synth mouse events
  110393. if(this.isPrimaryTouch(c)){
  110394. // remember x/y of last touch
  110395. var d={x:c.clientX,y:c.clientY};b.push(d);var e=function(a,b){var c=a.indexOf(b);c>-1&&a.splice(c,1)}.bind(null,b,d);setTimeout(e,S)}}};M=new c(V.elementAdded,V.elementRemoved,V.elementChanged,V);var W,X,Y,Z=u.pointermap,$=window.MSPointerEvent&&"number"==typeof window.MSPointerEvent.MSPOINTER_TYPE_MOUSE,_={events:["MSPointerDown","MSPointerMove","MSPointerUp","MSPointerOut","MSPointerOver","MSPointerCancel","MSGotPointerCapture","MSLostPointerCapture"],register:function(a){u.listen(a,this.events)},unregister:function(a){u.unlisten(a,this.events)},POINTER_TYPES:["","unavailable","touch","pen","mouse"],prepareEvent:function(a){var b=a;return $&&(b=u.cloneEvent(a),b.pointerType=this.POINTER_TYPES[a.pointerType]),b},cleanup:function(a){Z["delete"](a)},MSPointerDown:function(a){Z.set(a.pointerId,a);var b=this.prepareEvent(a);u.down(b)},MSPointerMove:function(a){var b=this.prepareEvent(a);u.move(b)},MSPointerUp:function(a){var b=this.prepareEvent(a);u.up(b),this.cleanup(a.pointerId)},MSPointerOut:function(a){var b=this.prepareEvent(a);u.leaveOut(b)},MSPointerOver:function(a){var b=this.prepareEvent(a);u.enterOver(b)},MSPointerCancel:function(a){var b=this.prepareEvent(a);u.cancel(b),this.cleanup(a.pointerId)},MSLostPointerCapture:function(a){var b=u.makeEvent("lostpointercapture",a);u.dispatchEvent(b)},MSGotPointerCapture:function(a){var b=u.makeEvent("gotpointercapture",a);u.dispatchEvent(b)}},aa=window.navigator;aa.msPointerEnabled?(W=function(a){i(a),j(this),k(a)&&(u.setCapture(a,this,!0),this.msSetPointerCapture(a))},X=function(a){i(a),u.releaseCapture(a,!0),this.msReleasePointerCapture(a)}):(W=function(a){i(a),j(this),k(a)&&u.setCapture(a,this)},X=function(a){i(a),u.releaseCapture(a)}),Y=function(a){return!!u.captureInfo[a]},g(),h(),l();var ba={dispatcher:u,Installer:c,PointerEvent:a,PointerMap:p,targetFinding:v};return ba});
  110396. /***/ }),
  110397. /* 34 */
  110398. /***/ (function(module, exports, __webpack_require__) {
  110399. "use strict";
  110400. Object.defineProperty(exports, "__esModule", { value: true });
  110401. var defaultViewer_1 = __webpack_require__(4);
  110402. var mappers_1 = __webpack_require__(1);
  110403. function InitTags(selector) {
  110404. if (selector === void 0) { selector = 'babylon'; }
  110405. var elements = document.querySelectorAll(selector);
  110406. for (var i = 0; i < elements.length; ++i) {
  110407. var element = elements.item(i);
  110408. var configMapper = mappers_1.mapperManager.getMapper('dom');
  110409. var config = configMapper.map(element);
  110410. var viewer = new defaultViewer_1.DefaultViewer(element, config);
  110411. }
  110412. }
  110413. exports.InitTags = InitTags;
  110414. /***/ })
  110415. /******/ ]);
  110416. return BabylonViewer;
  110417. });